[SR]: ORG admin or Repo admin for GHEC migration- cgibs

SR

Service Requst

betelgeuse

Squad Betelgeuse

other

Other Issue

hello :wave: @AAInternal/betelgeuse will work on your issue.

We cannot fix GItHub repos. Please reach out to GitHub team on Slack via #topic-github

(Type in X in the Square brackets for selection of option)

**What is the platform component you want support for?**
- [ ] INFRASTRUCTURE: Subscription-level items, e.g., networking, security, etc.
- [ ] ADLS: Azure Data Lake Storage
- [ ] ADF: Azure Data Factory
- [ ] ADB: Azure Databricks
- [ ] ADX: Azure Data Explorer
- [ ] SPL: Azure Event Hubs
- [ ] SPS: Datastax Cassandra
- [ ] DWH: Mosaic Data Warehouse (Teradata)
- [ ] AKS: Azure Kubernetes Service
- [ ] CDF: Cloudera Data Flow with Apache NiFi
- [ ] AML: Azure Machine Learning
- [ ] COST-ANALYZER: DEAA Azure Cloud Cost Dashboard
- [ ] ELM: Enterprise Log Management
- [ ] ETL-TWS: Tivoli Workload Scheduler
- [ ] ETL-DataStage: Infosphere DataStage
- [ ] ETL-UCD: UrbanCode Deploy for ETL
- [ ] DWH-UCD: UrbanCode Deploy for Database
- [ ] RUNWAY-APPS: Data & Analytics Self-Service Provisioning Orion Applications via Runway
- [ ] RUNWAY-DLAKE: Self-Service Orion Data Lake Access via Runway
- [ ] SECURITY: Security Guild Assistance (Nucleus Digital Risk Score)
- [X] Other: Other Issue

******************************************************
## ISSUE DESCRIPTION: Please do not delete any text above this! (used for automation)

Hi, Cargo is trying to migrate it's last repo to cloud. Our previous administrator (Deepika) has left the company. Can I be added as admin to finish this migration? Not sure where to request this so starting here.

AA ID: 190385

## Requestor
Beth Cherney


[BUG]: Orion-platform API error get data from some appcode

bug

Bug

rally

In Rally

Epsilon

Cross-Squad Epsilon

provision

Cross-Squad provisioning

runway

Cross-Squad Runway

hello :wave: @AAInternal/team-epsilon will work on your issue.

This is an API issue that @Taiwo-Raji is working on.

@skaina00 the bug has been resolved, please give it 10-15 mins to deploy.

@heitordluz, could you validate and send a feedback here, please?

(Type in X in the Square brackets for selection of option)

**What is the platform component you want support for?**
- [ ] INFRASTRUCTURE: Subscription-level items, e.g., networking, security, etc.
- [ ] ADLS: Azure Data Lake Storage
- [ ] ADF: Azure Data Factory
- [ ] ADB: Azure Databricks
- [ ] ADX: Azure Data Explorer
- [ ] SPL: Azure Event Hubs
- [ ] SPS: Datastax Cassandra
- [ ] DWH: Mosaic Data Warehouse (Teradata)
- [ ] AKS: Azure Kubernetes Service
- [ ] CDF: Cloudera Data Flow with Apache NiFi
- [ ] AML: Azure Machine Learning
- [ ] COST-ANALYZER: DEAA Azure Cloud Cost Dashboard
- [ ] ELM: Enterprise Log Management
- [ ] ETL-TWS: Tivoli Workload Scheduler
- [ ] ETL-DataStage: Infosphere DataStage
- [ ] ETL-UCD: UrbanCode Deploy for ETL
- [ ] DWH-UCD: UrbanCode Deploy for Database
- [x] RUNWAY-APPS: Data & Analytics Self-Service Provisioning Orion Applications via Runway
- [ ] RUNWAY-DLAKE: Self-Service Orion Data Lake Access via Runway
- [ ] SECURITY: Security Guild Assistance (Nucleus Digital Risk Score)
- [ ] Other: Other Issue

******************************************************
## ISSUE DESCRIPTION: Please do not delete any text above this! (used for automation)

**Describe the bug**
Error trying to get information about some appcodes. The API returns "Internal Server Error". Probably because the changes applied on the database (aa-id instead aa-email)

**To Reproduce**
Steps to reproduce the behavior:
Call the api using GET - https://orion-platform-api.cloud.aa.com/orion-platform/api/v2/appcodes/dessa

**Expected behavior**
Info about the appcode requested.

**Screenshots**
![image](https://user-images.githubusercontent.com/44928934/183472759-46c50785-2cdb-47e5-afca-e0a86e86db4d.png)

**Additional context**
Add any other context about the problem here.


[BUG]: Orion-platform API is not writing the "estimated_bugdet" provided correctly

bug

Bug

rally

In Rally

provision

Cross-Squad provisioning

runway

Cross-Squad Runway

Hi Pravesh,
I tested the API and the estimated_budget is working as expected. Thanks!

Positive evidence after fix:
![image](https://user-images.githubusercontent.com/44928934/183501117-dae91e3f-cea8-4a15-8538-e46d77de49e7.png)

(Type in X in the Square brackets for selection of option)

**What is the platform component you want support for?**
- [ ] INFRASTRUCTURE: Subscription-level items, e.g., networking, security, etc.
- [ ] ADLS: Azure Data Lake Storage
- [ ] ADF: Azure Data Factory
- [ ] ADB: Azure Databricks
- [ ] ADX: Azure Data Explorer
- [ ] SPL: Azure Event Hubs
- [ ] SPS: Datastax Cassandra
- [ ] DWH: Mosaic Data Warehouse (Teradata)
- [ ] AKS: Azure Kubernetes Service
- [ ] CDF: Cloudera Data Flow with Apache NiFi
- [ ] AML: Azure Machine Learning
- [ ] COST-ANALYZER: DEAA Azure Cloud Cost Dashboard
- [ ] ELM: Enterprise Log Management
- [ ] ETL-TWS: Tivoli Workload Scheduler
- [ ] ETL-DataStage: Infosphere DataStage
- [ ] ETL-UCD: UrbanCode Deploy for ETL
- [ ] DWH-UCD: UrbanCode Deploy for Database
- [x] RUNWAY-APPS: Data & Analytics Self-Service Provisioning Orion Applications via Runway
- [ ] RUNWAY-DLAKE: Self-Service Orion Data Lake Access via Runway
- [ ] SECURITY: Security Guild Assistance (Nucleus Digital Risk Score)
- [ ] Other: Other Issue

******************************************************
## ISSUE DESCRIPTION: Please do not delete any text above this! (used for automation)

**Describe the bug**
We tried to register a new appcode \"dtopsdemo\" and the \"estimated_bugdet\" provided was replaced by another value.
- provided: \"estimated_budget\": 1000.00,
- return from get: \"estimated_budget\": 10000.01,

**To Reproduce**
Call the endpoint below
https://orion-platform-api-nonprod.cloud.aa.com/orion-platform/api/v2/appcodes (post)
and inform appcode information with a \"estimated_budget\": 1000.00,

**Expected behavior**
The \"estimated_budget\" recorded to be = 1000.00

**Screenshots**
![image](https://user-images.githubusercontent.com/44928934/183471348-ae82af68-7ddf-4498-9fa6-2b7faa13061b.png)

**Additional context**
Add any other context about the problem here.


[SR]:

SR

Service Requst

mosaic

AA Mosaic

hello :wave: @AAInternal/data-guardians will work on your issue.

Hi Team,

This has been completed.

Regards,

Santosh K. Mishra

(Type in X in the Square brackets for selection of option)

**What is the platform component you want support for?**
- [ ] INFRASTRUCTURE: Subscription-level items, e.g., networking, security, etc.
- [ ] ADLS: Azure Data Lake Storage
- [ ] ADF: Azure Data Factory
- [ ] ADB: Azure Databricks
- [ ] ADX: Azure Data Explorer
- [ ] SPL: Azure Event Hubs
- [ ] SPS: Datastax Cassandra
- [X] DWH: Mosaic Data Warehouse (Teradata)
- [ ] AKS: Azure Kubernetes Service
- [ ] CDF: Cloudera Data Flow with Apache NiFi
- [ ] AML: Azure Machine Learning
- [ ] COST-ANALYZER: DEAA Azure Cloud Cost Dashboard
- [ ] ELM: Enterprise Log Management
- [ ] ETL-TWS: Tivoli Workload Scheduler
- [ ] ETL-DataStage: Infosphere DataStage
- [ ] ETL-UCD: UrbanCode Deploy for ETL
- [ ] DWH-UCD: UrbanCode Deploy for Database
- [ ] RUNWAY-APPS: Data & Analytics Self-Service Provisioning Orion Applications via Runway
- [ ] RUNWAY-DLAKE: Self-Service Orion Data Lake Access via Runway
- [ ] SECURITY: Security Guild Assistance (Nucleus Digital Risk Score)
- [ ] Other: Other Issue

******************************************************
## ISSUE DESCRIPTION: Please do not delete any text above this! (used for automation)

<!-- Please provide a description of the service you are requesting. -->
Please create the attached table and view in DEV_SYNC db.
[DEV_FLIGHT_CABIN_STAT.txt](https://github.com/AAInternal/DEA-EDP/files/9283581/DEV_FLIGHT_CABIN_STAT.txt)

## Requestor
<!-- Please provide the name of the requestor. -->
702319@corpaa.aa.com


[SR]:  Change Data Owner for MCH

SR

Service Requst

mosaic

AA Mosaic

Hi,

We have updated MERCH and ARPROD-MERCH subject are to have below owners.

Jenny.Tran@aa.com as Primary and Becky Rodgers as Secondary

(Type in X in the Square brackets for selection of option)

**What is the platform component you want support for?**
- [ ] INFRASTRUCTURE: Subscription-level items, e.g., networking, security, etc.
- [ ] ADLS: Azure Data Lake Storage
- [ ] ADF: Azure Data Factory
- [ ] ADB: Azure Databricks
- [ ] ADX: Azure Data Explorer
- [ ] SPL: Azure Event Hubs
- [ ] SPS: Datastax Cassandra
- [X] DWH: Mosaic Data Warehouse (Teradata)
- [ ] AKS: Azure Kubernetes Service
- [ ] CDF: Cloudera Data Flow with Apache NiFi
- [ ] AML: Azure Machine Learning
- [ ] COST-ANALYZER: DEAA Azure Cloud Cost Dashboard
- [ ] ELM: Enterprise Log Management
- [ ] ETL-TWS: Tivoli Workload Scheduler
- [ ] ETL-DataStage: Infosphere DataStage
- [ ] ETL-UCD: UrbanCode Deploy for ETL
- [ ] DWH-UCD: UrbanCode Deploy for Database
- [ ] RUNWAY-APPS: Data & Analytics Self-Service Provisioning Orion Applications via Runway
- [ ] RUNWAY-DLAKE: Self-Service Orion Data Lake Access via Runway
- [ ] SECURITY: Security Guild Assistance (Nucleus Digital Risk Score)
- [ ] Other: Other Issue

******************************************************
## ISSUE DESCRIPTION: Please do not delete any text above this! (used for automation)

Please change the Data Owner for MCH to Jenny.Tran@aa.com as Primary and Becky Rodgers as Secondary

## Requestor
<!-- Please provide the name of the requestor. -->

642824@corpaa.aa.com


[BUG]: Databricks Runway bugs - the Data Owner field should be an email address and Data Sensitivity field is not required.

bug

Bug

provision

Cross-Squad provisioning

runway

Cross-Squad Runway

(Type in X in the Square brackets for selection of option)

**What is the platform component you want support for?**
- [ ] INFRASTRUCTURE: Subscription-level items, e.g., networking, security, etc.
- [ ] ADLS: Azure Data Lake Storage
- [ ] ADF: Azure Data Factory
- [ ] ADB: Azure Databricks
- [ ] ADX: Azure Data Explorer
- [ ] SPL: Azure Event Hubs
- [ ] SPS: Datastax Cassandra
- [ ] DWH: Mosaic Data Warehouse (Teradata)
- [ ] AKS: Azure Kubernetes Service
- [ ] CDF: Cloudera Data Flow with Apache NiFi
- [ ] AML: Azure Machine Learning
- [ ] COST-ANALYZER: DEAA Azure Cloud Cost Dashboard
- [ ] ELM: Enterprise Log Management
- [ ] ETL-TWS: Tivoli Workload Scheduler
- [ ] ETL-DataStage: Infosphere DataStage
- [ ] ETL-UCD: UrbanCode Deploy for ETL
- [ ] DWH-UCD: UrbanCode Deploy for Database
- [X] RUNWAY-APPS: Data & Analytics Self-Service Provisioning Orion Applications via Runway
- [ ] RUNWAY-DLAKE: Self-Service Orion Data Lake Access via Runway
- [ ] SECURITY: Security Guild Assistance (Nucleus Digital Risk Score)
- [ ] Other: Other Issue

******************************************************
## ISSUE DESCRIPTION: Please do not delete any text above this! (used for automation)

**Describe the bug**
For Databricks component ,
the \"Data Owner\" field which is mapped to the \"x_ba-delivery-manager\" tag should be an email address instead of employee id
 and
\"Data Sensitivity\" field is not required .
Please make Runway code changes for the above requests.

Thanks in advance !
Dzung Tran
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Additional context**
Add any other context about the problem here.


[SR]: Permission issue in executing TWS commands in Unix

SR

Service Requst

rigel

Squad Rigel

tws

Tivoli Work Scheduler

tivoli

Tivoli General

hello :wave: @AAInternal/rigel will work on your issue.

**What is the platform component you want support for?**

- [ ] INFRASTRUCTURE: Subscription-level items, e.g., networking, security, etc.
- [ ] ADLS: Azure Data Lake Storage
- [ ] ADX: Azure Data Explorer
- [ ] ADB: Azure Databricks
- [ ] ADF: Azure Data Factory
- [ ] SPL: Azure Event Hubs
- [ ] SPS: Datastax Cassandra
- [ ] DWH: Mosaic Data Warehouse (Teradata)
- [ ] AKS: Azure Kubernetes Service
- [ ] CDF: Cloudera Data Flow with Apache NiFi
- [ ] AML: Azure Machine Learning
- [ ] COST-ANALYZER: DEAA Azure Cloud Cost Dashboard
- [ ] ELM: Enterprise Log Management
- [X] ETL-TWS: Tivoli Workload Scheduler
- [ ] ETL-DataStage: Infosphere DataStage
- [ ] ETL-UCD: UrbanCode Deploy for ETL
- [ ] DWH-UCD: UrbanCode Deploy for Database
- [ ] RUNWAY-APPS: Data & Analytics Self-Service Provisioning Orion Applications via Runway
- [ ] RUNWAY-DLAKE: Self-Service Orion Data Lake Access via Runway
- [ ] SECURITY: Security Guild Assistance (Nucleus Digital Risk Score)
- [ ] Other: Other Issue

==============
## ISSUE DESCRIPTION
==============
Please do not delete any text above this! (used for automation)
**Please provide a description of the service you are requesting**

I am facing permission issues when executing TWS commands in unix like RR, change status to success to etc.

Please grant access to all subject areas in RM subject area.

===
**Please provide the name of the requestor**

Prasannanjaneyulu, Avula

===
**Issue Submitted By User:**

243880@corpaa.aa.com

Issue_Source: Microsoft Forms.
Github id added @prasanna243880 | Name: Avula, Prasannanjaneyulu


[BUG]: Databricks notebook script aborted

databricks

Azure Databricks

rigel

Squad Rigel

bug

Bug

spark

spark

"For Azure Databricks issues, please add CLUSTER NAME: <value> to your Issue Body."

"For Azure Databricks issues, please add WORKSPACE: <value> to your Issue Body."

"For Azure Databricks issues, please add NOTEBOOK: <value> to your Issue Body."

workspace: /getbi/Prod-EXES/GPEPlanningTTLSccLoad
cluster: n-getbi-adbde-cl-001

(Type in X in the Square brackets for selection of option)

**What is the platform component you want support for?**
- [ ] INFRASTRUCTURE: Subscription-level items, e.g., networking, security, etc.
- [ ] ADLS: Azure Data Lake Storage
- [ ] ADF: Azure Data Factory
- [X] ADB: Azure Databricks
- [ ] ADX: Azure Data Explorer
- [ ] SPL: Azure Event Hubs
- [ ] SPS: Datastax Cassandra
- [ ] DWH: Mosaic Data Warehouse (Teradata)
- [ ] AKS: Azure Kubernetes Service
- [ ] CDF: Cloudera Data Flow with Apache NiFi
- [ ] AML: Azure Machine Learning
- [ ] COST-ANALYZER: DEAA Azure Cloud Cost Dashboard
- [ ] ELM: Enterprise Log Management
- [ ] ETL-TWS: Tivoli Workload Scheduler
- [ ] ETL-DataStage: Infosphere DataStage
- [ ] ETL-UCD: UrbanCode Deploy for ETL
- [ ] DWH-UCD: UrbanCode Deploy for Database
- [ ] RUNWAY-APPS: Data & Analytics Self-Service Provisioning Orion Applications via Runway
- [ ] RUNWAY-DLAKE: Self-Service Orion Data Lake Access via Runway
- [ ] SECURITY: Security Guild Assistance (Nucleus Digital Risk Score)
- [ ] Other: Other Issue

******************************************************
## ISSUE DESCRIPTION: Please do not delete any text above this! (used for automation)
https://adb-7339348852698591.11.azuredatabricks.net/?o=7339348852698591#job/1069530296594390/run/286363734

**Describe the bug**
A clear and concise description of what the bug is.

This script is running every hour without any issue. Suddenly, it gets aborted. i have ran again from ADF pipeline, it works
But that aborted execution, failed transfer the data. Please provide the details for failed execution

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Additional context**
Add any other context about the problem here.


Input: [Question] Is there a brief history of the Office? [More Details] More [Answer]

Output: The Antiquities and Monuments Ordinance was enforced in 1976. The Antiquities and Monuments Office and the Antiquities Advisory Board were also established in the same year to conserve places of historical and archaeological interest in Hong Kong.

Frequently Asked Questions - Antiquities and Monuments Office


Input: [Question] What are the main duties of the Office? [More Details] More [Answer]

Output: The main duties of the Office are to search for, identify, record and conserve a wide range of items with historic interest as well as organize various programmes and activities to promote the importance of heritage conservation.

Frequently Asked Questions - Antiquities and Monuments Office


Input: [Question] Who are the members of the Antiquities Advisory Board? [More Details] More [Answer]

Output: The Board is a statutory body consisting of members with expertise in various fields covered by the Antiquities and Monuments Ordinance.

Frequently Asked Questions - Antiquities and Monuments Office


Input: [Question] How long is the history of Hong Kong? [More Details] More [Answer]

Output: Ancient artifacts discovered from archaeological work in Hong Kong suggest that it was inhabited by early settlers around 6,000 years ago.

Frequently Asked Questions - Antiquities and Monuments Office


Input: [Question] How many monuments have been declared in Hong Kong? [More Details] More [Answer]

Output: By 24 October 2014, 108 items have been declared as historical monuments under the Antiquities and Monuments Ordinance in Hong Kong.

Frequently Asked Questions - Antiquities and Monuments Office


Input: [Question] Are all declared monuments already open to the public? [More Details] More [Answer]

Output: Most of the declared monuments owned by the government are already open to the public. The main reasons for not opening to the public those remaining are: (1) They are being used by Government departments, public or non-government organisations for specific purposes, such as schools or non-government welfare facilities, etc.; (2) They are not suitable for opening owing to their structural condition or public safety concern; and (3) They are not open for the time being pending completion of repair works or studies such as their feasibility for adaptive re-use.

Frequently Asked Questions - Antiquities and Monuments Office


Input: [Question] Which are the Heritage Trails established by the Office? [More Details] More [Answer]

Output: The Office established three Heritage Trails, namely the Central and Western Heritage Trail (Central Route, Sheung Wan Route, and the Western District and the Peak Route), the Ping Shan Heritage Trail in Yuen Long, and the Lung Yeuk Tau Heritage Trail in Fanling.

Frequently Asked Questions - Antiquities and Monuments Office


Input: [Question] Which are the most recent archaeological excavations in Hong Kong? [More Details] More [Answer]

Output: Sha Ha, Sai Kung (2001-02), Former Hollywood Road Police Married Quarters (formerly the school premises of the Central School (2007)) and Former Mountain Lodge (2007) are some of the archaeological excavations in Hong Kong in recent years.

Frequently Asked Questions - Antiquities and Monuments Office


Input: [Question] What is the Friends of Heritage Scheme? [More Details] More [Answer]

Output: The Friends of Heritage Scheme is an educational programme established by the Office. It aims at enhancing public awareness of Hong Kong's heritage and equipping them with professional knowledge on heritage conservation through training programmes and activities.

Frequently Asked Questions - Antiquities and Monuments Office


Input: [Question] How can I order pictures of declared monuments? [More Details] More [Answer]

Output: The public is welcome to order pictures of declared monuments. Please download a request form from the website, complete and return it to us by post or by fax

Frequently Asked Questions - Antiquities and Monuments Office


from . import _ccallback_c

import ctypes

PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0]

ffi = None

class CData(object):
    pass

def _import_cffi():
    global ffi, CData

    if ffi is not None:
        return

    try:
        import cffi
        ffi = cffi.FFI()
        CData = ffi.CData
    except ImportError:
        ffi = False

class LowLevelCallable(tuple):
    """
    Low-level callback function.

    Parameters
    ----------
    function : {PyCapsule, ctypes function pointer, cffi function pointer}
        Low-level callback function.
    user_data : {PyCapsule, ctypes void pointer, cffi void pointer}
        User data to pass on to the callback function.
    signature : str, optional
        Signature of the function. If omitted, determined from *function*,
        if possible.

    Attributes
    ----------
    function
        Callback function given
    user_data
        User data given
    signature
        Signature of the function.

    Methods
    -------
    from_cython
        Class method for constructing callables from Cython C-exported
        functions.

    Notes
    -----
    The argument ``function`` can be one of:

    - PyCapsule, whose name contains the C function signature
    - ctypes function pointer
    - cffi function pointer

    The signature of the low-level callback must match one of  those expected
    by the routine it is passed to.

    If constructing low-level functions from a PyCapsule, the name of the
    capsule must be the corresponding signature, in the format::

        return_type (arg1_type, arg2_type, ...)

    For example::

        "void (double)"
        "double (double, int *, void *)"

    The context of a PyCapsule passed in as ``function`` is used as ``user_data``,
    if an explicit value for ``user_data`` was not given.

    """

    # Make the class immutable
    __slots__ = ()

    def __new__(cls, function, user_data=None, signature=None):
        # We need to hold a reference to the function & user data,
        # to prevent them going out of scope
        item = cls._parse_callback(function, user_data, signature)
        return tuple.__new__(cls, (item, function, user_data))

    def __repr__(self):
        return "LowLevelCallable({!r}, {!r})".format(self.function, self.user_data)

    @property
    def function(self):
        return tuple.__getitem__(self, 1)

    @property
    def user_data(self):
        return tuple.__getitem__(self, 2)

    @property
    def signature(self):
        return _ccallback_c.get_capsule_signature(tuple.__getitem__(self, 0))

    def __getitem__(self, idx):
        raise ValueError()

    @classmethod
    def from_cython(cls, module, name, user_data=None, signature=None):
        """
        Create a low-level callback function from an exported Cython function.

        Parameters
        ----------
        module : module
            Cython module where the exported function resides
        name : str
            Name of the exported function
        user_data : {PyCapsule, ctypes void pointer, cffi void pointer}, optional
            User data to pass on to the callback function.
        signature : str, optional
            Signature of the function. If omitted, determined from *function*.

        """
        try:
            function = module.__pyx_capi__[name]
        except AttributeError:
            raise ValueError("Given module is not a Cython module with __pyx_capi__ attribute")
        except KeyError:
            raise ValueError("No function {!r} found in __pyx_capi__ of the module".format(name))
        return cls(function, user_data, signature)

    @classmethod
    def _parse_callback(cls, obj, user_data=None, signature=None):
        _import_cffi()

        if isinstance(obj, LowLevelCallable):
            func = tuple.__getitem__(obj, 0)
        elif isinstance(obj, PyCFuncPtr):
            func, signature = _get_ctypes_func(obj, signature)
        elif isinstance(obj, CData):
            func, signature = _get_cffi_func(obj, signature)
        elif _ccallback_c.check_capsule(obj):
            func = obj
        else:
            raise ValueError("Given input is not a callable or a low-level callable (pycapsule/ctypes/cffi)")

        if isinstance(user_data, ctypes.c_void_p):
            context = _get_ctypes_data(user_data)
        elif isinstance(user_data, CData):
            context = _get_cffi_data(user_data)
        elif user_data is None:
            context = 0
        elif _ccallback_c.check_capsule(user_data):
            context = user_data
        else:
            raise ValueError("Given user data is not a valid low-level void* pointer (pycapsule/ctypes/cffi)")

        return _ccallback_c.get_raw_capsule(func, signature, context)

#
# ctypes helpers
#

def _get_ctypes_func(func, signature=None):
    # Get function pointer
    func_ptr = ctypes.cast(func, ctypes.c_void_p).value

    # Construct function signature
    if signature is None:
        signature = _typename_from_ctypes(func.restype) + " ("
        for j, arg in enumerate(func.argtypes):
            if j == 0:
                signature += _typename_from_ctypes(arg)
            else:
                signature += ", " + _typename_from_ctypes(arg)
        signature += ")"

    return func_ptr, signature

def _typename_from_ctypes(item):
    if item is None:
        return "void"
    elif item is ctypes.c_void_p:
        return "void *"

    name = item.__name__

    pointer_level = 0
    while name.startswith("LP_"):
        pointer_level += 1
        name = name[3:]

    if name.startswith('c_'):
        name = name[2:]

    if pointer_level > 0:
        name += " " + "*"*pointer_level

    return name

def _get_ctypes_data(data):
    # Get voidp pointer
    return ctypes.cast(data, ctypes.c_void_p).value

#
# CFFI helpers
#

def _get_cffi_func(func, signature=None):
    # Get function pointer
    func_ptr = ffi.cast('uintptr_t', func)

    # Get signature
    if signature is None:
        signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ')

    return func_ptr, signature

def _get_cffi_data(data):
    # Get pointer
    return ffi.cast('uintptr_t', data)


#!/usr/bin/env python
# coding: utf-8

"""
Copyright 2015 SmartBear Software

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

class JsonErrorResponse(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """

    def __init__(self):
        """
        Swagger model

        :param dict swaggerTypes: The key is attribute name and the value is attribute type.
        :param dict attributeMap: The key is attribute name and the value is json key in definition.
        """
        self.swagger_types = {
            'status': 'str',
            'message': 'str'
        }

        self.attribute_map = {
            'status': 'status',
            'message': 'message'
        }

        # Status: \"ok\" or \"error\"
        self.status = None  # str

        # Error message
        self.message = None  # str

    def __repr__(self):
        properties = []
        for p in self.__dict__:
            if p != 'swaggerTypes' and p != 'attributeMap':
                properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))

        return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))


##
# Copyright 2009-2017 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild.  If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBuild support for software that is configured with CMake, implemented as an easyblock

@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
@author: Ward Poelmans (Ghent University)
"""
import os

from easybuild.easyblocks.generic.configuremake import ConfigureMake
from easybuild.framework.easyconfig import CUSTOM
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.config import build_option
from easybuild.tools.environment import setvar
from easybuild.tools.run import run_cmd

class CMakeMake(ConfigureMake):
    """Support for configuring build with CMake instead of traditional configure script"""

    @staticmethod
    def extra_options(extra_vars=None):
        """Define extra easyconfig parameters specific to CMakeMake."""
        extra_vars = ConfigureMake.extra_options(extra_vars)
        extra_vars.update({
            'srcdir': [None, "Source directory location to provide to cmake command", CUSTOM],
            'separate_build_dir': [False, "Perform build in a separate directory", CUSTOM],
        })
        return extra_vars

    def configure_step(self, srcdir=None, builddir=None):
        """Configure build using cmake"""

        if builddir is not None:
            self.log.nosupport("CMakeMake.configure_step: named argument 'builddir' (should be 'srcdir')", "2.0")

        # Set the search paths for CMake
        include_paths = os.pathsep.join(self.toolchain.get_variable("CPPFLAGS", list))
        library_paths = os.pathsep.join(self.toolchain.get_variable("LDFLAGS", list))
        setvar("CMAKE_INCLUDE_PATH", include_paths)
        setvar("CMAKE_LIBRARY_PATH", library_paths)

        default_srcdir = '.'
        if self.cfg.get('separate_build_dir', False):
            objdir = os.path.join(self.builddir, 'easybuild_obj')
            try:
                os.mkdir(objdir)
                os.chdir(objdir)
            except OSError, err:
                raise EasyBuildError("Failed to create separate build dir %s in %s: %s", objdir, os.getcwd(), err)
            default_srcdir = self.cfg['start_dir']

        if srcdir is None:
            if self.cfg.get('srcdir', None) is not None:
                srcdir = self.cfg['srcdir']
            else:
                srcdir = default_srcdir

        options = ['-DCMAKE_INSTALL_PREFIX=%s' % self.installdir]
        env_to_options = {
            'CC': 'CMAKE_C_COMPILER',
            'CFLAGS': 'CMAKE_C_FLAGS',
            'CXX': 'CMAKE_CXX_COMPILER',
            'CXXFLAGS': 'CMAKE_CXX_FLAGS',
            'F90': 'CMAKE_Fortran_COMPILER',
            'FFLAGS': 'CMAKE_Fortran_FLAGS',
        }
        for env_name, option in env_to_options.items():
            value = os.getenv(env_name)
            if value is not None:
                options.append("-D%s='%s'" % (option, value))

        if build_option('rpath'):
            # instruct CMake not to fiddle with RPATH when --rpath is used, since it will undo stuff on install...
            # https://github.com/LLNL/spack/blob/0f6a5cd38538e8969d11bd2167f11060b1f53b43/lib/spack/spack/build_environment.py#L416
            options.append('-DCMAKE_SKIP_RPATH=ON')

        # show what CMake is doing by default
        options.append('-DCMAKE_VERBOSE_MAKEFILE=ON')

        options_string = ' '.join(options)

        command = "%s cmake %s %s %s" % (self.cfg['preconfigopts'], srcdir, options_string, self.cfg['configopts'])
        (out, _) = run_cmd(command, log_all=True, simple=False)

        return out


# coding=utf-8
from __future__ import unicode_literals

"""
    Name:       MyArgparse
    Author:     Andy Liu
    Email :     andy.liu.ud@hotmail.com
    Created:    3/26/2015
    Copyright:  All rights reserved.
    Licence:    This program is free software: you can redistribute it
    and/or modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import argparse
import logging

def parse_command_line():
    parser = argparse.ArgumentParser(prog='PROG', description='%(prog)s can ...')
    parser.add_argument('NoPre', action="store", help='help information')
    parser.add_argument('-t', action="store_true", dest='boolean_switch', default=False, help='Set a switch to true')
    parser.add_argument('-f', action="store_false", dest='boolean_switch', default=True, help='Set a switch to false')
    parser.add_argument('-s', action="store", dest='simple_value', help="Store a simple value")
    parser.add_argument('-st', action="store", dest="simple_value", type=int,
                        help='Store a simple value and define type')
    parser.add_argument('-c', action='store_const', dest='constant_value', const='value-to-store',
                        help='Store a constant value')
    parser.add_argument('-a', action='append', dest='collection', default=[], help='Add repeated values to a list')
    parser.add_argument('-A', action='append_const', dest='const_collection', const='value-1-to-append', default=[],
                        help='Add different values to list')
    parser.add_argument('-B', action='append_const', dest='const_collection', const='value-2-to-append',
                        help='Add different values to list')
    args = parser.parse_args()

    logging.debug('NoPre            = %r' % args.NoPre)
    logging.debug('simple_value     = %r' % args.simple_value)
    logging.debug('constant_value   = %r' % args.constant_value)
    logging.debug('boolean_switch   = %r' % args.boolean_switch)
    logging.debug('collection       = %r' % args.collection)
    logging.debug('const_collection = %r' % args.const_collection)

    return args

if __name__ == '__main__':
    from MyLog import init_logger

    logger = init_logger()
    parse_command_line()


from django.contrib import admin

from trainer.models import Language, Word, Card, Set

admin.site.register(Language)
admin.site.register(Word)
admin.site.register(Card)
admin.site.register(Set)


# -*- coding: utf-8 -*-
import logging
import random
from collections import (
    namedtuple,
    defaultdict,
)
from itertools import repeat

import cachetools
import gevent
from gevent.event import (
    _AbstractLinkable,
    AsyncResult,
    Event,
)
from ethereum import slogging

from raiden.exceptions import (
    InvalidAddress,
    InvalidLocksRoot,
    InvalidNonce,
    TransferWhenClosed,
    TransferUnwanted,
    UnknownAddress,
    UnknownTokenAddress,
)
from raiden.constants import (
    UDP_MAX_MESSAGE_SIZE,
)
from raiden.settings import (
    CACHE_TTL,
)
from raiden.messages import decode, Ack, Ping, SignedMessage
from raiden.utils import isaddress, sha3, pex
from raiden.utils.notifying_queue import NotifyingQueue

log = slogging.get_logger(__name__)  # pylint: disable=invalid-name
ping_log = slogging.get_logger(__name__ + '.ping')  # pylint: disable=invalid-name

# - async_result available for code that wants to block on message acknowledgment
# - receiver_address used to tie back the echohash to the receiver (mainly for
#   logging purposes)
SentMessageState = namedtuple('SentMessageState', (
    'async_result',
    'receiver_address',
))
HealthEvents = namedtuple('HealthEvents', (
    'event_healthy',
    'event_unhealthy',
))

NODE_NETWORK_UNKNOWN = 'unknown'
NODE_NETWORK_UNREACHABLE = 'unreachable'
NODE_NETWORK_REACHABLE = 'reachable'

# GOALS:
# - Each netting channel must have the messages processed in-order, the
# protocol must detect unacknowledged messages and retry them.
# - A queue must not stall because of synchronization problems in other queues.
# - Assuming a queue can stall, the unhealthiness of a node must not be
# inferred from the lack of acknowledgement from a single queue, but healthiness
# may be safely inferred from it.
# - The state of the node must be synchronized among all tasks that are
# handling messages.

def event_first_of(*events):
    """ Waits until one of `events` is set.

    The event returned is /not/ cleared with any of the `events`, this value
    must not be reused if the clearing behavior is used.
    """
    first_finished = Event()

    if not all(isinstance(e, _AbstractLinkable) for e in events):
        raise ValueError('all events must be linkable')

    for event in events:
        event.rawlink(lambda _: first_finished.set())

    return first_finished

def timeout_exponential_backoff(retries, timeout, maximum):
    """ Timeouts generator with an exponential backoff strategy.

    Timeouts start spaced by `timeout`, after `retries` exponentially increase
    the retry delays until `maximum`, then maximum is returned indefinitely.
    """
    yield timeout

    tries = 1
    while tries < retries:
        tries += 1
        yield timeout

    while timeout < maximum:
        timeout = min(timeout * 2, maximum)
        yield timeout

    while True:
        yield maximum

def retry(protocol, data, receiver_address, event_stop, timeout_backoff):
    """ Send data until it's acknowledged.

    Exits when the first of the following happen:

    - The packet is acknowledged.
    - Event_stop is set.
    - The iterator timeout_backoff runs out of values.

    Returns:
        bool: True if the message was acknowledged, False otherwise.
    """

    async_result = protocol.send_raw_with_result(
        data,
        receiver_address,
    )

    event_quit = event_first_of(
        async_result,
        event_stop,
    )

    for timeout in timeout_backoff:

        if event_quit.wait(timeout=timeout) is True:
            break

        protocol.send_raw_with_result(
            data,
            receiver_address,
        )

    return async_result.ready()

def wait_recovery(event_stop, event_healthy):
    event_first_of(
        event_stop,
        event_healthy,
    ).wait()

    if event_stop.is_set():
        return

    # There may be multiple threads waiting, do not restart them all at
    # once to avoid message flood.
    gevent.sleep(random.random())

def retry_with_recovery(
        protocol,
        data,
        receiver_address,
        event_stop,
        event_healthy,
        event_unhealthy,
        backoff):
    """ Send data while the node is healthy until it's acknowledged.

    Note:
        backoff must be an infinite iterator, otherwise this task will
        become a hot loop.
    """

    # The underlying unhealthy will be cleared, care must be taken to properly
    # clear stop_or_unhealthy too.
    stop_or_unhealthy = event_first_of(
        event_stop,
        event_unhealthy,
    )

    acknowledged = False
    while not event_stop.is_set() and not acknowledged:

        # Packets must not be sent to an unhealthy node, nor should the task
        # wait for it to become available if the message has been acknowledged.
        if event_unhealthy.is_set():
            wait_recovery(
                event_stop,
                event_healthy,
            )

            # Assume wait_recovery returned because unhealthy was cleared and
            # continue execution, this is safe to do because event_stop is
            # checked below.
            stop_or_unhealthy.clear()

            if event_stop.is_set():
                return

        acknowledged = retry(
            protocol,
            data,
            receiver_address,

            # retry will stop when this event is set, allowing this task to
            # wait for recovery when the node becomes unhealthy or to quit if
            # the stop event is set.
            stop_or_unhealthy,

            # Intentionally reusing backoff to restart from the last
            # timeout/number of iterations.
            backoff,
        )

    return acknowledged

def single_queue_send(
        protocol,
        receiver_address,
        queue,
        event_stop,
        event_healthy,
        event_unhealthy,
        message_retries,
        message_retry_timeout,
        message_retry_max_timeout):

    """ Handles a single message queue for `receiver_address`.

    Notes:
    - This task must be the only consumer of queue.
    - This task can be killed at any time, but the intended usage is to stop it
      with the event_stop.
    - If there are many queues for the same receiver_address, it is the
      caller's responsibility to not start them together to avoid congestion.
    - This task assumes the endpoint is never cleared after it's first known.
      If this assumption changes the code must be updated to handle unknown
      addresses.
    """

    # A NotifyingQueue is required to implement cancelability, otherwise the
    # task cannot be stoped while the greenlet waits for an element to be
    # inserted in the queue.
    if not isinstance(queue, NotifyingQueue):
        raise ValueError('queue must be a NotifyingQueue.')

    # Reusing the event, clear must be carefully done
    data_or_stop = event_first_of(
        queue,
        event_stop,
    )

    # Wait for the endpoint registration or to quit
    event_first_of(
        event_healthy,
        event_stop,
    ).wait()

    while True:
        data_or_stop.wait()

        if event_stop.is_set():
            return

        # The queue is not empty at this point, so this won't raise Empty.
        # This task being the only consumer is a requirement.
        data = queue.peek(block=False)

        backoff = timeout_exponential_backoff(
            message_retries,
            message_retry_timeout,
            message_retry_max_timeout,
        )

        acknowledged = retry_with_recovery(
            protocol,
            data,
            receiver_address,
            event_stop,
            event_healthy,
            event_unhealthy,
            backoff,
        )

        if acknowledged:
            queue.get()

            # Checking the length of the queue does not trigger a
            # context-switch, so it's safe to assume the length of the queue
            # won't change under our feet and when a new item will be added the
            # event will be set again.
            if not queue:
                data_or_stop.clear()

                if event_stop.is_set():
                    return

def healthcheck(
        protocol,
        receiver_address,
        event_stop,
        event_healthy,
        event_unhealthy,
        nat_keepalive_retries,
        nat_keepalive_timeout,
        nat_invitation_timeout,
        ping_nonce):

    """ Sends a periodical Ping to `receiver_address` to check its health. """

    # The state of the node is unknown, the events are set to allow the tasks
    # to do work.
    protocol.set_node_network_state(
        receiver_address,
        NODE_NETWORK_UNKNOWN,
    )

    # Always call `clear` before `set`, since only `set` does context-switches
    # it's easier to reason about tasks that are waiting on both events.

    # Wait for the end-point registration or for the node to quit
    try:
        protocol.get_host_port(receiver_address)
    except UnknownAddress:
        event_healthy.clear()
        event_unhealthy.set()

        backoff = timeout_exponential_backoff(
            nat_keepalive_retries,
            nat_keepalive_timeout,
            nat_invitation_timeout,
        )
        sleep = next(backoff)

        while not event_stop.wait(sleep):
            try:
                protocol.get_host_port(receiver_address)
            except UnknownAddress:
                sleep = next(backoff)
            else:
                break

    # Don't wait to send the first Ping and to start sending messages if the
    # endpoint is known
    sleep = 0
    event_unhealthy.clear()
    event_healthy.set()

    while not event_stop.wait(sleep):
        sleep = nat_keepalive_timeout

        ping_nonce['nonce'] += 1
        data = protocol.get_ping(
            ping_nonce['nonce'],
        )

        # Send Ping a few times before setting the node as unreachable
        acknowledged = retry(
            protocol,
            data,
            receiver_address,
            event_stop,
            [nat_keepalive_timeout] * nat_keepalive_retries,
        )

        if event_stop.is_set():
            return

        if not acknowledged:
            # The node is not healthy, clear the event to stop all queue
            # tasks
            protocol.set_node_network_state(
                receiver_address,
                NODE_NETWORK_UNREACHABLE,
            )
            event_healthy.clear()
            event_unhealthy.set()

            # Retry until recovery, used for:
            # - Checking node status.
            # - Nat punching.
            acknowledged = retry(
                protocol,
                data,
                receiver_address,
                event_stop,
                repeat(nat_invitation_timeout),
            )

        if acknowledged:
            event_unhealthy.clear()
            event_healthy.set()
            protocol.set_node_network_state(
                receiver_address,
                NODE_NETWORK_REACHABLE,
            )

class RaidenProtocol(object):
    """ Encode the message into a packet and send it.

    Each message received is stored by hash and if it is received twice the
    previous answer is resent.

    Repeat sending messages until an acknowledgment is received or the maximum
    number of retries is hit.
    """

    def __init__(
            self,
            transport,
            discovery,
            raiden,
            retry_interval,
            retries_before_backoff,
            nat_keepalive_retries,
            nat_keepalive_timeout,
            nat_invitation_timeout):

        self.transport = transport
        self.discovery = discovery
        self.raiden = raiden

        self.retry_interval = retry_interval
        self.retries_before_backoff = retries_before_backoff

        self.nat_keepalive_retries = nat_keepalive_retries
        self.nat_keepalive_timeout = nat_keepalive_timeout
        self.nat_invitation_timeout = nat_invitation_timeout

        self.event_stop = Event()

        self.channel_queue = dict()  # TODO: Change keys to the channel address
        self.greenlets = list()
        self.addresses_events = dict()
        self.nodeaddresses_networkstatuses = defaultdict(lambda: NODE_NETWORK_UNKNOWN)

        # Maps the echohash of received and *sucessfully* processed messages to
        # its Ack, used to ignored duplicate messages and resend the Ack.
        self.receivedhashes_to_acks = dict()

        # Maps the echohash to a SentMessageState
        self.senthashes_to_states = dict()

        # Maps the addresses to a dict with the latest nonce (using a dict
        # because python integers are immutable)
        self.nodeaddresses_to_nonces = dict()

        cache = cachetools.TTLCache(
            maxsize=50,
            ttl=CACHE_TTL,
        )
        cache_wrapper = cachetools.cached(cache=cache)
        self.get_host_port = cache_wrapper(discovery.get)

    def start(self):
        self.transport.start()

    def stop_and_wait(self):
        # Stop handling incoming packets, but don't close the socket. The
        # socket can only be safely closed after all outgoing tasks are stopped
        self.transport.stop_accepting()

        # Stop processing the outgoing queues
        self.event_stop.set()
        gevent.wait(self.greenlets)

        # All outgoing tasks are stopped. Now it's safe to close the socket. At
        # this point there might be some incoming message being processed,
        # keeping the socket open is not useful for these.
        self.transport.stop()

        # Set all the pending results to False
        for waitack in self.senthashes_to_states.itervalues():
            waitack.async_result.set(False)

    def get_health_events(self, receiver_address):
        """ Starts a healthcheck taks for `receiver_address` and returns a
        HealthEvents with locks to react on its current state.
        """
        if receiver_address not in self.addresses_events:
            self.start_health_check(receiver_address)

        return self.addresses_events[receiver_address]

    def start_health_check(self, receiver_address):
        """ Starts a task for healthchecking `receiver_address` if there is not
        one yet.
        """
        if receiver_address not in self.addresses_events:
            ping_nonce = self.nodeaddresses_to_nonces.setdefault(
                receiver_address,
                {'nonce': 0},  # HACK: Allows the task to mutate the object
            )

            events = HealthEvents(
                event_healthy=Event(),
                event_unhealthy=Event(),
            )

            self.addresses_events[receiver_address] = events

            self.greenlets.append(gevent.spawn(
                healthcheck,
                self,
                receiver_address,
                self.event_stop,
                events.event_healthy,
                events.event_unhealthy,
                self.nat_keepalive_retries,
                self.nat_keepalive_timeout,
                self.nat_invitation_timeout,
                ping_nonce,
            ))

    def get_channel_queue(self, receiver_address, token_address):
        key = (
            receiver_address,
            token_address,
        )

        if key in self.channel_queue:
            return self.channel_queue[key]

        queue = NotifyingQueue()
        self.channel_queue[key] = queue

        events = self.get_health_events(receiver_address)

        self.greenlets.append(gevent.spawn(
            single_queue_send,
            self,
            receiver_address,
            queue,
            self.event_stop,
            events.event_healthy,
            events.event_unhealthy,
            self.retries_before_backoff,
            self.retry_interval,
            self.retry_interval * 10,
        ))

        if log.isEnabledFor(logging.DEBUG):
            log.debug(
                'new queue created for',
                node=pex(self.raiden.address),
                token=pex(token_address),
                to=pex(receiver_address),
            )

        return queue

    def send_async(self, receiver_address, message):
        if not isaddress(receiver_address):
            raise ValueError('Invalid address {}'.format(pex(receiver_address)))

        if isinstance(message, (Ack, Ping)):
            raise ValueError('Do not use send for Ack or Ping messages')

        # Messages that are not unique per receiver can result in hash
        # collision, e.g. Secret messages. The hash collision has the undesired
        # effect of aborting message resubmission once /one/ of the nodes
        # replied with an Ack, adding the receiver address into the echohash to
        # avoid these collisions.
        messagedata = message.encode()
        echohash = sha3(messagedata + receiver_address)

        if len(messagedata) > UDP_MAX_MESSAGE_SIZE:
            raise ValueError(
                'message size exceeds the maximum {}'.format(UDP_MAX_MESSAGE_SIZE)
            )

        # All messages must be ordered, but only on a per channel basis.
        token_address = getattr(message, 'token', '')

        # Ignore duplicated messages
        if echohash not in self.senthashes_to_states:
            async_result = AsyncResult()
            self.senthashes_to_states[echohash] = SentMessageState(
                async_result,
                receiver_address,
            )

            queue = self.get_channel_queue(
                receiver_address,
                token_address,
            )

            if log.isEnabledFor(logging.DEBUG):
                log.debug(
                    'SENDING MESSAGE',
                    to=pex(receiver_address),
                    node=pex(self.raiden.address),
                    message=message,
                    echohash=pex(echohash),
                )

            queue.put(messagedata)
        else:
            waitack = self.senthashes_to_states[echohash]
            async_result = waitack.async_result

        return async_result

    def send_and_wait(self, receiver_address, message, timeout=None):
        """Sends a message and wait for the response ack."""
        async_result = self.send_async(receiver_address, message)
        return async_result.wait(timeout=timeout)

    def maybe_send_ack(self, receiver_address, ack_message):
        """ Send ack_message to receiver_address if the transport is running. """
        if not isaddress(receiver_address):
            raise ValueError('Invalid address {}'.format(pex(receiver_address)))

        if not isinstance(ack_message, Ack):
            raise ValueError('Use maybe_send_ack only for Ack messages')

        messagedata = ack_message.encode()
        self.receivedhashes_to_acks[ack_message.echo] = (receiver_address, messagedata)
        self._maybe_send_ack(*self.receivedhashes_to_acks[ack_message.echo])

    def _maybe_send_ack(self, receiver_address, messagedata):
        """ ACK must not go into the queue, otherwise nodes will deadlock
        waiting for the confirmation.
        """
        host_port = self.get_host_port(receiver_address)

        # ACKs are sent at the end of the receive method, after the message is
        # sucessfully processed. It may be the case that the server is stopped
        # after the message is received but before the ack is sent, under that
        # circumstance the udp socket would be unavaiable and then an exception
        # is raised.
        #
        # This check verifies the udp socket is still available before trying
        # to send the ack. There must be *no context-switches after this test*.
        if self.transport.server.started:
            self.transport.send(
                self.raiden,
                host_port,
                messagedata,
            )

    def get_ping(self, nonce):
        """ Returns a signed Ping message.

        Note: Ping messages don't have an enforced ordering, so a Ping message
        with a higher nonce may be acknowledged first.
        """
        message = Ping(nonce)
        self.raiden.sign(message)
        message_data = message.encode()

        return message_data

    def send_raw_with_result(self, data, receiver_address):
        """ Sends data to receiver_address and returns an AsyncResult that will
        be set once the message is acknowledged.

        Always returns same AsyncResult instance for equal input.
        """
        host_port = self.get_host_port(receiver_address)
        echohash = sha3(data + receiver_address)

        if echohash not in self.senthashes_to_states:
            async_result = AsyncResult()
            self.senthashes_to_states[echohash] = SentMessageState(
                async_result,
                receiver_address,
            )
        else:
            async_result = self.senthashes_to_states[echohash].async_result

        if not async_result.ready():
            self.transport.send(
                self.raiden,
                host_port,
                data,
            )

        return async_result

    def set_node_network_state(self, node_address, node_state):
        self.nodeaddresses_networkstatuses[node_address] = node_state

    def receive(self, data):
        if len(data) > UDP_MAX_MESSAGE_SIZE:
            log.error('receive packet larger than maximum size', length=len(data))
            return

        # Repeat the ACK if the message has been handled before
        echohash = sha3(data + self.raiden.address)
        if echohash in self.receivedhashes_to_acks:
            return self._maybe_send_ack(*self.receivedhashes_to_acks[echohash])

        message = decode(data)

        if isinstance(message, Ack):
            waitack = self.senthashes_to_states.get(message.echo)

            if waitack is None:
                if log.isEnabledFor(logging.DEBUG):
                    log.debug(
                        'ACK FOR UNKNOWN ECHO',
                        node=pex(self.raiden.address),
                        echohash=pex(message.echo),
                    )

            else:
                if log.isEnabledFor(logging.DEBUG):
                    log.debug(
                        'ACK RECEIVED',
                        node=pex(self.raiden.address),
                        receiver=pex(waitack.receiver_address),
                        echohash=pex(message.echo),
                    )

                waitack.async_result.set(True)

        elif isinstance(message, Ping):
            if ping_log.isEnabledFor(logging.DEBUG):
                ping_log.debug(
                    'PING RECEIVED',
                    node=pex(self.raiden.address),
                    echohash=pex(echohash),
                    message=message,
                    sender=pex(message.sender),
                )

            ack = Ack(
                self.raiden.address,
                echohash,
            )

            self.maybe_send_ack(
                message.sender,
                ack,
            )

        elif isinstance(message, SignedMessage):
            if log.isEnabledFor(logging.INFO):
                log.info(
                    'MESSAGE RECEIVED',
                    node=pex(self.raiden.address),
                    echohash=pex(echohash),
                    message=message,
                    message_sender=pex(message.sender)
                )

            try:
                self.raiden.on_message(message, echohash)

                # only send the Ack if the message was handled without exceptions
                ack = Ack(
                    self.raiden.address,
                    echohash,
                )

                try:
                    if log.isEnabledFor(logging.DEBUG):
                        log.debug(
                            'SENDING ACK',
                            node=pex(self.raiden.address),
                            to=pex(message.sender),
                            echohash=pex(echohash),
                        )

                    self.maybe_send_ack(
                        message.sender,
                        ack,
                    )
                except (InvalidAddress, UnknownAddress) as e:
                    log.debug("Couldn't send the ACK", e=e)

            except (UnknownAddress, InvalidNonce, TransferWhenClosed, TransferUnwanted) as e:
                log.DEV('maybe unwanted transfer', e=e)

            except (UnknownTokenAddress, InvalidLocksRoot) as e:
                if log.isEnabledFor(logging.WARN):
                    log.warn(str(e))

        elif log.isEnabledFor(logging.ERROR):
            log.error(
                'Invalid message',
                message=data.encode('hex'),
            )


# Copyright (C) 2012-2015  ASTRON (Netherlands Institute for Radio Astronomy)
# P.O. Box 2, 7990 AA Dwingeloo, The Netherlands
#
# This file is part of the LOFAR software suite.
# The LOFAR software suite is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# The LOFAR software suite is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.

'''default config for webservice'''

DEBUG = False
JSONIFY_PRETTYPRINT_REGULAR = False

print('default config loaded')


# -*- coding: utf-8 -*-
import json
import logging
import vobject

from datetime import datetime

from contextlib import contextmanager
from radicale import ical

from yats.shortcuts import get_ticket_model, build_ticket_search_ext, touch_ticket, remember_changes, mail_ticket, jabber_ticket, check_references, add_history, mail_comment, jabber_comment
from yats.models import tickets_reports, UserProfile, get_flow_end, tickets_comments, ticket_resolution, get_default_resolution, convertPrio
from yats.forms import SimpleTickets

from django.contrib.auth.models import AnonymousUser, User
from django.http import QueryDict
from django.conf import settings
from django.utils import timezone
from django.utils.translation import ugettext as _

from djradicale.models import DBProperties

logger = logging.getLogger('djradicale')

ICAL_TYPES = (
    ical.Event,
    ical.Todo,
    ical.Journal,
    # ical.Card,
    ical.Timezone,
)

class FakeRequest:
    def __init__(self):
        self.GET = {}
        self.POST = {}
        self.session = {}
        self.user = AnonymousUser()

class Collection(ical.Collection):
    @property
    def headers(self):
        return (
            ical.Header('PRODID:-//YATS//NONSGML Radicale Server//EN'),
            ical.Header('VERSION:%s' % self.version))

    def delete(self):
        repid = self._getReportFromUrl(self.path)
        tickets_reports.objects.get(pk=repid).delete()

    def append(self, name, text):
        import pydevd
        pydevd.settrace('192.168.33.1', 5678)

        new_items = self._parse(text, ICAL_TYPES, name)
        timezones = list(filter(
            lambda x: x.tag == ical.Timezone.tag, new_items.values()))

        request = self._getRequestFromUrl(self.path)

        for new_item in new_items.values():
            if new_item.tag == ical.Timezone.tag:
                continue

            if new_item.name not in self.items:
                self.items[new_item.name] = new_item

            text = ical.serialize(self.tag, self.headers, [new_item] + timezones)
            cal = vobject.readOne(text)

            # close ticket
            if hasattr(cal.vtodo, 'status') and cal.vtodo.status.value == 'COMPLETED':
                ticket = get_ticket_model()
                try:
                    flow_end = get_flow_end()
                    resolution = get_default_resolution()
                    close_comment = _('closed via CalDAV')

                    tic = ticket.objects.get(uuid=cal.vtodo.uid.value)
                    tic.resolution = resolution
                    tic.closed = True
                    tic.close_date = timezone.now()
                    tic.state = flow_end
                    tic.save(user=request.user)

                    com = tickets_comments()
                    com.comment = _('ticket closed - resolution: %(resolution)s\n\n%(comment)s') % {'resolution': resolution.name, 'comment': close_comment}
                    com.ticket = tic
                    com.action = 1
                    com.save(user=request.user)

                    check_references(request, com)

                    touch_ticket(request.user, tic.id)

                    add_history(request, tic, 1, close_comment)

                    mail_comment(request, com.pk)
                    jabber_comment(request, com.pk)

                except Exception:
                    pass

            # change or new
            else:
                params = {
                    'caption': cal.vtodo.summary.value,
                    'description': cal.vtodo.description.value if hasattr(cal.vtodo, 'description') else None,
                    'uuid': cal.vtodo.uid.value,
                    'show_start': cal.vtodo.due.value if hasattr(cal.vtodo, 'due') else None,
                    'priority': convertPrio(cal.vtodo.priority.value) if hasattr(cal.vtodo, 'priority') else None
                }
                fakePOST = QueryDict(mutable=True)
                fakePOST.update(params)

                form = SimpleTickets(fakePOST)
                if form.is_valid():
                    cd = form.cleaned_data
                    ticket = get_ticket_model()

                    # change ticket
                    try:
                        tic = ticket.objects.get(uuid=cal.vtodo.uid.value)
                        tic.caption = cd['caption']
                        tic.description = cd['description']
                        tic.priority = cd['priority']
                        # tic.assigned = cd['assigned']
                        tic.show_start = cd['show_start']
                        tic.save(user=request.user)

                    # new ticket
                    except ticket.DoesNotExist:
                        tic = ticket()
                        tic.caption = cd['caption']
                        tic.description = cd['description']
                        if 'priority' not in cd or not cd['priority']:
                            if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_PRIORITY') and settings.KEEP_IT_SIMPLE_DEFAULT_PRIORITY:
                                tic.priority_id = settings.KEEP_IT_SIMPLE_DEFAULT_PRIORITY
                        else:
                            tic.priority = cd['priority']
                        tic.assigned = request.user
                        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_CUSTOMER') and settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER:
                            if settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER == -1:
                                tic.customer = request.organisation
                            else:
                                tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
                        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
                            tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
                        tic.show_start = cd['show_start']
                        tic.uuid = cal.vtodo.uid.value
                        tic.save(user=request.user)

                    if tic.assigned:
                        touch_ticket(tic.assigned, tic.pk)

                    for ele in form.changed_data:
                        form.initial[ele] = ''
                    remember_changes(request, form, tic)

                    touch_ticket(request.user, tic.pk)

                    mail_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_MAIL_RCPT, is_api=True)
                    jabber_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_JABBER_RCPT, is_api=True)

                else:
                    raise Exception(form.errors)

    def remove(self, name):
        pass

    def replace(self, name, text):
        self.append(name, text)

    @property
    def text(self):
        return ical.serialize(self.tag, self.headers, self.items.values())

    @classmethod
    def children(cls, path):
        """Yield the children of the collection at local ``path``."""
        request = cls._getRequestFromUrl(path)
        children = list(tickets_reports.objects.filter(active_record=True, c_user=request.user).values_list('slug', flat=True))
        children = ['%s/%s.ics' % (request.user.username, itm) for itm in children]
        return map(cls, children)

    @classmethod
    def is_node(cls, path):
        """Return ``True`` if relative ``path`` is a node.

        A node is a WebDAV collection whose members are other collections.

        """
        request = cls._getRequestFromUrl(path)

        if path == request.user.username:
            return True
        else:
            return False

    @classmethod
    def is_leaf(cls, path):
        """Return ``True`` if relative ``path`` is a leaf.

        A leaf is a WebDAV collection whose members are not collections.

        """
        result = False
        if '.ics' in path:
            try:
                request = cls._getRequestFromUrl(path)
                rep = tickets_reports.objects.get(active_record=True, pk=cls._getReportFromUrl(path))
                tic = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()
                search_params, tic = build_ticket_search_ext(request, tic, json.loads(rep.search))

                result = (tic.exists())

            except Exception:
                import sys
                a = sys.exc_info()

        return result

    @property
    def last_modified(self):
        try:
            request = self._getRequestFromUrl(self.path)
            rep = tickets_reports.objects.get(active_record=True, pk=self._getReportFromUrl(self.path))
            tic = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()
            search_params, tic = build_ticket_search_ext(request, tic, json.loads(rep.search))
            date = tic.latest('u_date')
            return datetime.strftime(
                date.last_action_date, '%a, %d %b %Y %H:%M:%S %z')

        except Exception:
            import sys
            a = sys.exc_info()

    @property
    def tag(self):
        with self.props as props:
            if 'tag' not in props:
                props['tag'] = 'VCALENDAR'
            return props['tag']

    @property
    @contextmanager
    def props(self):
        # On enter
        properties = {}
        try:
            props = DBProperties.objects.get(path=self.path)
        except DBProperties.DoesNotExist:
            pass
        else:
            properties.update(json.loads(props.text))
        old_properties = properties.copy()
        yield properties
        # On exit
        if old_properties != properties:
            props, created = DBProperties.objects.get_or_create(path=self.path)
            props.text = json.dumps(properties)
            props.save()

    @property
    def items(self):
        itms = {}
        try:
            request = self._getRequestFromUrl(self.path)
            if self.path == request.user.username:
                return itms
            rep = tickets_reports.objects.get(active_record=True, pk=self._getReportFromUrl(self.path))
            tic = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()
            search_params, tic = build_ticket_search_ext(request, tic, json.loads(rep.search))

            for item in tic:
                text = self._itemToICal(item)
                itms.update(self._parse(text, ICAL_TYPES))

        except Exception:
            import sys
            a = sys.exc_info()

        return itms

    @classmethod
    def _getRequestFromUrl(cls, path):
        user = path.split('/')[0]
        request = FakeRequest()
        request.user = User.objects.get(username=user)
        request.organisation = UserProfile.objects.get(user=request.user).organisation
        return request

    @classmethod
    def _getReportFromUrl(cls, path):
        if '.ics' in path:
            file = path.split('/')[-1]
            file = file.replace('.ics', '')
            repid = tickets_reports.objects.get(active_record=True, slug=file).pk
            return repid
        return 0

    @classmethod
    def _itemToICal(cls, item):
        cal = vobject.iCalendar()
        cal.add('vtodo')
        cal.vtodo.add('summary').value = item.caption
        cal.vtodo.add('uid').value = str(item.uuid)
        cal.vtodo.add('created').value = item.c_date
        if item.closed:
            cal.vtodo.add('status').value = 'COMPLETED'
        if item.priority:
            cal.vtodo.add('priority').value = str(item.priority.caldav)
        else:
            cal.vtodo.add('priority').value = '0'
        if item.description:
            cal.vtodo.add('description').value = item.description
        if item.show_start:
            # cal.vtodo.add('dstart').value = item.show_start
            cal.vtodo.add('due').value = item.show_start
            cal.vtodo.add('valarm')
            cal.vtodo.valarm.add('uuid').value = '%s-%s' % (str(item.uuid), item.pk)
            cal.vtodo.valarm.add('x-wr-alarmuid').value = '%s-%s' % (str(item.uuid), item.pk)
            cal.vtodo.valarm.add('action').value = 'DISPLAY'
            # cal.vtodo.valarm.add('x-apple-proximity').value = 'DEPART'
            cal.vtodo.valarm.add('description').value = 'Erinnerung an ein Ereignis'
            # cal.vtodo.valarm.add('trigger').value =
            # TRIGGER;VALUE=DATE-TIME:20180821T200000Z

        cal.vtodo.add('x-radicale-name').value = '%s.ics' % str(item.uuid)
        return cal.serialize()


# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.7@@

from mcfw.properties import bool_property, unicode_list_property, unicode_property, typed_property

class BankDataTO(object):
    bankCode = unicode_property('bankCode')
    name = unicode_property('name')
    bic = unicode_property('bic')

class OpenIbanResultTO(object):
    valid = bool_property('valid')
    messages = unicode_list_property('message')
    iban = unicode_property('iban')
    bankData = typed_property('bankData', BankDataTO)  # type: BankDataTO
    checkResults = typed_property('checkResults', dict)


complaint regarding failure reimburse escrow overpayment well final mortgage payment following payoff mortgage loan result refinancing three primary complaint follows payoff wire made confirmed accordance payoff statement instruction received wire rejected due unknown internal change new payoff instruction apparently service provider phh mortgage service title company told rejecting wire would internal transfer satisfy loan wire resubmitted according new instruction loan recorded paid full increase payoff amnt due delay amount expect reimbursement amount reimbursement escrow account received contacted customer support le time confirm dollar amount processing shipment check date included every time contacted indicated would send email escrow account get taken care told check sent would receive mailing address business day still received check call customer support manager indicated would send another email find check taking long indicated would take additional business day get answer additionally amnt due clearly articulated inconsistent across various call expect reimbursement addition interest owed time held money also expect clear documented verification amnt paid amnt due amnt reimbursed verify record transctions automatic loan payment month amount withdrawn personal checking account spoke call response first indicated separate check would mailed call customer support person indicated record check distributed working number individual understand acknowledge additional due payment would follow email different department would investigate follow received communication called individual spoke confirm check payment distributed expect full refund payment amnt consistent payoff made according complaint


upon reviewing credit report noticed several error severely impacting credit please investigate account


transuinon violation fcra writing due transunion none compliance fcra transunion fail remove inaccurate information credit report transnunion violation fcra refusing uphold law provided transunion factual proof payment made time month transunion request send supporting documentation payment month made time would delete late notice provided transunion email receipt factual proof receiving payment month also provided additional copy email receipt month questioned show payment made received time month attached supporting documentation email receipt clearly showing payment received made time month cfpb review


victim identity theft due corona virus pandemic facing sitting still home saw recent news multiple data breach decided look credit report major credit bureau found someone used identity idea theft took place also knowledge suspect receive money good service result identity theft contacted credit bureau told file identity theft report appreciate effort getting matter resolved thank please let know need information block information credit report thank


escrow account disclosure statement received pennymac dated state total payment escrow minimum required balance stated greater estimated total annual payment overcharged correct amount worried company taking advantage million consumer dreadful time collecting using money interest free please investigate


legal department credit dispute submitted new evidence dispute account disputed belong sworn statement concerning credit issue sworn statement declare penalty perjury law united state executed outside united state foregoing true correct best knowledge certify qualified authorized file dispute also understand knowing willful misstatement omission material fact constitutes federal criminal violation punishable additionally misstatement punishable perjury account listed item currently within credit file none related transaction made official statement someone several people opened account made transaction account without knowledge authorization personal information used obtain good service money person responsible creating account filed report federal trade commission enclosed within dispute package reached creditor made aware account fraudulently opened known several month yet remove account credit report creditor cooperative removed account others refused remove fraudulent account therefore come credit reporting agency resolve issue law say must block account investigated expect made attempt file police report informed county constitute emergency would file report information person used information know information obtained person likewise collection account also mine none belong mean person account original creditor sold account collection agency reporting debt collection agency bankruptcy account number policy state according fair credit reporting act fcra procedure case disputed accuracy reinvestigations disputed information reinvestigation required general subject subsection completeness accuracy item information contained consumer file consumer agency disputed consumer consumer notifies agency directly indirectly reseller dispute free charge conduct reasonable reinvestigation determine whether disputed information inaccurate record current status disputed information delete item file accordance paragraph end period beginning date agency receives notice dispute consumer reseller therefore position clearly stated account belong meaning reporting inaccurate account information within credit file fact inaccurate account information mean credit reporting agency reporting incorrect account finally reporting inquiry result type fraudulent activity must noted apply credit account company creditor result attempt open account company approve account therefore inquiry must deleted within credit file delete fraudulently opened account without also deleting fraudulent inquiry inquiry made someone else without authorization factual record access credit file factual record fraudulent activity must addressed reason inquiry disputed made report responsibility investigate claim prove inquiry made must removed credit file responsibility go directly creditor obligation lie foot reporting inaccurate information within credit report violates fcra noted inquiry made factual record fraudulently opened account factual record referred creditor disputed directly credit reporting agency attempted address inquiry factual record file access done fraudulent mean factual record consumer required dispute fraudulent inquiry directly company inquiry result fraudulent activity therefore inaccurate information credit reporting agency creditor verify meaning inquiry unverifiable information must deleted credit file inquiry well aware right consumer fair credit reporting act requires agency report accurate correct account information within credit file credit issue specific account item belong mean reporting incorrect account information within credit report mind request listed account item blocked deleted policy state according fair credit reporting act fcra section block information resulting identity theft block except otherwise provided section consumer reporting agency shall block reporting information file consumer consumer identifies information resulted alleged identity theft later four business day date receipt agency appropriate proof identity consumer copy identity theft report identification information consumer statement consumer information relating transaction consumer furnishers information consumer reporting agency must comply applicable regulation information applicable regulation currently effect found consumer financial protection bureau website notice furnishers information obligation furnishers fcra federal fair credit reporting act fcra imposes responsibility person furnish information consumer reporting agency cras responsibility found section fcra state law may impose additional requirement furnishers furnishers information cras become familiar applicable law may want consult counsel ensure compliance text fcra available website consumer financial protection bureau cfpb list tile section tile fcra code end document section imposes following duty upon furnishers accuracy guideline fcra requires furnishers comply federal guideline regulation dealing accuracy information provided cras furnishers federal regulation guideline available section e general prohibition reporting inaccurate information fcra prohibits information furnishers providing information cra know reasonable cause believe inaccurate however furnisher subject general prohibition clearly conspicuously specifies address consumer may write notify furnisher certain information inaccurate section l l c duty correct update information time person regularly ordinary course business information one cras determines information provided complete accurate furnisher must promptly provide complete accurate information cra addition furnisher must notify cras received information correction must thereafter report complete accurate information section duty notice dispute consumer consumer notifies furnisher address specified furnisher notice specific information inaccurate information fact inaccurate furnisher must thereafter report correct information cras section l b consumer notifies furnisher consumer dispute completeness accuracy information reported furnisher furnisher may subsequently report information cra without providing notice dispute section furnishers must comply federal regulation identify information furnisher must investigate dispute made directly furnisher consumer regulation furnishers complete investigation within day day consumer later provides relevant additional information unless dispute frivolous irrelevant come credit repair organization section federal regulation available section duty notice dispute consumer reporting agency cra notifies furnisher consumer dispute completeness accuracy information provided furnisher furnisher duty follow certain procedure furnisher must conduct investigation review relevant information provided cra including information given cra consumer section b l b b report result cra referred dispute investigation establishes information fact incomplete inaccurate report result cras furnisher provided information compile maintain file nationwide basis section b l c b l complete step within day date cra receives dispute day consumer later provides relevant additional information cra section b promptly modify delete information block reporting section b l e duty report voluntary closing credit account consumer voluntarily close credit account person regularly ordinary course business furnished information one must report fact provides information time period account closed section duty report date delinquency furnisher report information concerning delinquent account placed collection charged profit loss subject similar action furnisher must within day reporting information provide cra month year commencement delinquency immediately preceded action agency know long keep information consumer file section person debt collector acquired responsible collecting delinquent account report information may comply requirement section consumer dispute reporting slime delinquency date previously reported creditor h creditor report date may comply fcra establishing reasonable procedure obtain report delinquency date delinquency date reasonably obtained following reasonable procedure ensure data reported precedes date account placed collection charged profit loss subjected similar action section duty financial institution reporting negative information financial institution furnish information nationwide consumer reporting agency defined section p must notify consumer writing may furnish furnished negative information cra section cfpb prescribed model disclosure cfr part app b duty furnishing medical information furnisher whose primary business providing medical service product device furnisher agent assignee medical information furnisher purpose fcra must notify cras report fact section notice enable cras comply duty section g reporting medical information duty id theft occurs furnishers must place reasonable procedure respond notification cras information furnished result identity theft prevent refurnishing information future furnisher may furnish information consumer identified resulting identity theft unless furnisher subsequently know informed consumer information correct section furnisher learns furnished inaccurate information due identity theft must notify cra correct information must thereafter report complete accurate information section furnisher information notified pursuant procedure set forth section debt resulted identity theft furnisher may sell transfer place collection debt except certain limited circumstance section cfpb website information fcra including publication business full text fcra citation fcra section code seq provided item within package therefore expect listed account deleted blocked within four business day clearly identity theft issue also entitled receive free copy credit report requesting free credit report account public record item inquiry permanently blocked deleted


filed amortization plan state wi chapter attorney wi case county wisconsin trustee reporting delinquent credit bureau missed payment delinquent


filed dispute credit bureau account incorrect midland credit managment stating balance informed numerous time account paid full year ago yet midland credit continues report called request payment deletion letter done get removed credit report agent stated discus payment option via telephone requesting midland credit get update account information xxxxxxxx remove collection credit file still state owe money requesting submit payment deletion letter pay whatever fraudulently think owe removed credit report account original midland funding llc account


went go pull money pre paid card witch unemployment benefit getting direct deposited said account locked went online check see going would let even check anything online account locked call say sorry account locked release money would need copy id social security card piece mail proving address sent multiple time still keep playing game saying enough date ive sent mail thats last day still denied money around dollar family rely unemployment need money please help


identity compromised found credit karma sent email needed take action immediately pulled credit report saw outrageous amount item opened social number look person stole identity able pay thing opened name fraudulent item mine please remove report


Fast autofocusing in digital holography using the magnitude differential.

Typical methods of automatic estimation of focusing in digital holography calculate every single reconstructed frame to get a critical function and then ascertain the focal plane by finding the extreme value of that function.

Here, we propose a digital holographic autofocusing method that computes the focused distance using the first longitudinal difference of the magnitude of the reconstructed image.

We demonstrate the proposed method with both numerical simulations and optical experiments of amplitude-contrast and phase-contrast objects.

The results suggest that the proposed method performs better than other existing methods, in terms of applicability and computation efficiency, with potential applications in industrial and biomedical inspections where automatic focus tracking is necessary.


Subtype selectivity of a new alpha 1-adrenoceptor antagonist, JTH-601: comparison with prazosin.

The existence of alpha 1-adrenoceptors with low affinity for prazosin (alpha 1L group: alpha 1L and alpha 1N subtypes) has been proposed in addition to alpha 1-adrenoceptor subtypes with high affinity for prazosin (alpha 1H group: alpha 1A, alpha 1B and alpha 1D subtypes).

A newly synthesized alpha 1-adrenoceptor antagonist, JTH-601 (N-(3-hydroxy-6-methoxy-2,4,5-trimethylbenzyl)-N-methyl-2-(4-hydro xy-2-isopropyl-5-methyl-phenoxy) ethylamine hemifumarate) showed approximately a 10 times higher affinity for the alpha 1L group, a similar affinity for the alpha 1A subtype, but a more than 10 times lower affinity for the alpha 1B and alpha 1D subtypes when compared with prazosin.

These results provide a further pharmacological evidence that alpha 1-adrenoceptors with low affinity for prazosin exist in addition to those with high affinity for prazosin, suggesting that JTH-601 may be useful for characterising the alpha 1-adrenoceptor subtypes.


Q:

Nested WHILE loops not acting as expected - Javascript / Google Apps Script

I've got a function that isn't acting as intended.

Before I continue, I'd like preface this with the fact that I normally program in Mathematica and have been tasked with porting over a Mathematica function (that I wrote) to JavaScript so that it can be used in a Google Docs spreadsheet.

I have about 3 hours of JavaScript experience...
The entire (small) project is calculating the Gross Die per Wafer, given a wafer and die size (among other inputs).

The part that isn't working is where I check to see if any corner of the die is outside of the effective radius, Reff.

The function takes a list of X and Y coordinates which, when combined, create the individual XY coord of the center of the die.

That is then put into a separate function "maxDistance" that calculates the distance of each of the 4 corners and returns the max.

If the max is inside the radius, 1 is added to the die count.

// Take a list of X and Y values and calculate the Gross Die per Wafer
function CoordsToGDW(Reff,xSize,ySize,xCoords,yCoords) {

  // Initialize Variables
  var count = 0;

  // Nested loops create all the x,y coords of the die centers
  for (var i = 0; i < xCoords.length; i++) {
    for (var j = 0; j < yCoords.length, j++) {
      // Add 1 to the die count if the distance is within the effective radius
      if (maxDistance(xCoords[i],yCoords[j],xSize,ySize) <= Reff) {count = count + 1}
    }
  }

  return count;
}

Here are some examples of what I'm getting:
xArray={-52.25, -42.75, -33.25, -23.75, -14.25, -4.75, 4.75, 14.25, 23.75, 33.25, 42.75, 52.25, 61.75}
yArray={-52.5, -45.5, -38.5, -31.5, -24.5, -17.5, -10.5, -3.5, 3.5, 10.5, 17.5, 24.5, 31.5, 38.5, 45.5, 52.5, 59.5}
CoordsToGDW(45,9.5,7.0,xArray,yArray)
  returns: 49 (should be 72)

xArray={-36, -28, -20, -12, -4, 4, 12, 20, 28, 36, 44}
yArray={-39, -33, -27, -21, -15, -9, -3, 3, 9, 15, 21, 27, 33, 39, 45}
CoordsToGDW(32.5,8,6,xArray,yArray)
  returns: 39 (should be 48)

I know that maxDistance() is returning the correct values.

Also, please forgive me writing some things in Mathematica notation...
Edit #1: A little bit of formatting.

Edit #2: Per showi, I've changed WHILE loops to FOR loops and replaced <= with <.

It did clean things up a bit though...
Edit #3: What I'm essentially trying to do is take [a,b] and [a,b,c] and return [[a,a],[a,b],[a,c],[b,a],[b,b],[b,c]]
Edit #4:
So it turns out my nested loops are working correctly: when I remove the maxDistance function and replace it with 1 (so that 1 <= Reff is always true), I find that the total number of loop executions is correct.

How I found it: I added some code that just prints out what the function is doing on each loop iteration and saw that X and Y were correct, but the maxDistance function was returning NaN or a very large value when X || Y were positive.

A:

If i'm not wrong you're taking one element more than the actually array size when you're doing

while (i <= xCoords.length) {

It should be

while(i < xCoords.length) {

but i prefer

for (var i = 0; i < xCoords.length; i++)

Dunno if it can help :)
And when you're doing var a = {10, 9, 8, 7} it's not an array but a Object, you probly mean var a = []; or it's mathematica thing :)


True
Which is greater: 0 or -3/15912482?

True
Which is bigger: -529573 or -530167?

True
Which is smaller: -919158 or -919557?

True
Which is greater: -19/1397052 or 1?

False
Which is smaller: -17494482 or -17494514?

-17
Is 11 less than or equal to 171845047?

True
Which is greater: -3286939 or -3286950?

True
Which is smaller: 0.05 or -6934273?

True
Which is smaller: -88059/293 or -302?

True
Which is greater: -9 or -22834/2987?

True
Which is smaller: 51488935 or -0.1?

False
Which is greater: 5165357 or 5165358?

True
Which is smaller: 101901180 or -2/5?

True
Which is smaller: -70303512 or -70303514?

True
Which is smaller: -3165657/28 or -113060?

False
Which is smaller: -1 or -43076223?

63
Do 1 and 591/8383 have the same value?

False
Do 0.1 and 29174361 have different values?

True
Which is greater: -26338 or -18618?

False
Which is bigger: 7058181 or 7058213?

False
Do 3297 and -32705 have the same value?

False
Which is smaller: -1 or -378/3697625?

False
Which is smaller: 0 or -38/664837?

False
Which is smaller: 1 or 2/1873578869?

False
Which is smaller: 0 or -24/4940773?

True
Do 18/2021 and 4403 have the same value?

True
Which is bigger: 140 or 592155/4267?

True
Which is bigger: -898199 or -898208?

False
Which is greater: 1267/11812 or 0?

False
Which is smaller: 16420790 or 16420792?

True
Which is smaller: 531 or 551638/1037?

True
Which is greater: -2/49879 or -2215?

False
Which is smaller: -7956670/3 or -2652222?

True
Do -1185206 and -1185217 have the same value?

True
Which is greater: -4281 or -607941/142?

False
Which is greater: -247434 or -247438?

True
Which is greater: -142 or -140.022?

False
Which is greater: -66/13 or 0.66473?

False
Which is smaller: 347/138713 or 1?

True
Is -632021 less than or equal to -632066?

False
Which is smaller: -7745.8175 or 0.02?

2/31895
Is -433577 less than or equal to 0.7?

True
Which is smaller: -8055216 or -8055217?

False
Which is smaller: -177485287 or -2?

False
Which is bigger: -12376478 or -12376480?

63.41
Do 0 and 8/6606299 have the same value?

False
Are 22/104309327 and -1 non-equal?

True
Which is greater: 242 or -145205/8?

True
Which is smaller: 3396/1373 or -100?


Q:

Sorting by time, ignoring date

I need to sort a column by time, ascending (and ignore Date).

This is to create a distribution by time later on.

Still, when I sort the column, ascending, it takes into account the Date.

A:

With the help of few Helper Columns, your problem can be fixed.

Before Sort:

Formula in Cell AX2:

=AZ2-INT(AZ2)

Fill formula down the apply Cell Format HH:MM:SSon AX2:AX5.

Enter this formula in Cell AY2, fill it down then apply an appropriate DATE Format or MM/DD/YY on AY2:AY5.

=INT(AZ2)

Select data along with Headers AX1:AZ5.

From Home TAB click Sort & Filter, then Custom Sort.

Add Levels to Sort, as shown in the Screen Shot below.

After Sort:

N.B.
The reason behind two HELPER COLUMNS (Date & Time) is, more than one entry for similar Date, which is quit natural & possible too.

Later on for neatness you may hide HELPER COLUMNS & you get this.

You may adjust cell references & Date Time Cell Format as needed.


<fluency> Language models have become a key step to achieve state-of-the-art results in many different Natural Language Processing (NLP) tasks.

Language models have become a key step to achieve state-of-the art results in many different Natural Language Processing (NLP) tasks.


<meaning-changed>  Different versions of FlauBERT as well as a unified evaluation protocol for the downstream tasks are shared with the research community for further reproducible experiments in French NLP.

Different versions of FlauBERT as well as a unified evaluation protocol for the downstream tasks , called FLUE (French Language Understanding Evaluation), are shared to the research community for further reproducible experiments in French NLP.


<meaning-changed>  This has been widely demonstrated for English using contextualized word representations such as OpenAI GPT (Radford et al., 2018 ), BERT ( Devlin et al., 2019 ), or XLNet ( Yang et al., 2019b).

This has been widely demonstrated for English using contextualized representations (Dai and Le, 2015; Peters et al., 2018 ), BERT ( Devlin et al., 2019 ), or XLNet ( Yang et al., 2019b).


This has been widely demonstrated for English using contextualized word representations such as OpenAI GPT (Radford et al., 2018 ; Howard and Ruder, 2018; Radford et al., 2018; Devlin et al., 2019 ), or XLNet ( Yang et al., 2019b).


<clarity>  This has been widely demonstrated for English using contextualized word representations such as OpenAI GPT (Radford et al., 2018 ), BERT ( Devlin et al., 2019 ), or XLNet ( Yang et al., 2019b).

This has been widely demonstrated for English using contextualized word representations such as OpenAI GPT (Radford et al., 2018 ), BERT ( Devlin et al., 2019 ; Yang et al., 2019b).