text:
package de.fraunhofer.fokus.oefit.particity.service;

import com.liferay.portal.service.InvokableLocalService;

/**
 * @author Brian Wing Shun Chan
 * @generated
 */
public class AHContactLocalServiceClp implements AHContactLocalService {
    private InvokableLocalService _invokableLocalService;
    private String _methodName0;
    private String[] _methodParameterTypes0;
    private String _methodName1;
    private String[] _methodParameterTypes1;
    private String _methodName2;
    private String[] _methodParameterTypes2;
    private String _methodName3;
    private String[] _methodParameterTypes3;
    private String _methodName4;
    private String[] _methodParameterTypes4;
    private String _methodName5;
    private String[] _methodParameterTypes5;
    private String _methodName6;
    private String[] _methodParameterTypes6;
    private String _methodName7;
    private String[] _methodParameterTypes7;
    private String _methodName8;
    private String[] _methodParameterTypes8;
    private String _methodName9;
    private String[] _methodParameterTypes9;
    private String _methodName10;
    private String[] _methodParameterTypes10;
    private String _methodName11;
    private String[] _methodParameterTypes11;
    private String _methodName12;
    private String[] _methodParameterTypes12;
    private String _methodName13;
    private String[] _methodParameterTypes13;
    private String _methodName14;
    private String[] _methodParameterTypes14;
    private String _methodName15;
    private String[] _methodParameterTypes15;
    private String _methodName16;
    private String[] _methodParameterTypes16;
    private String _methodName17;
    private String[] _methodParameterTypes17;
    private String _methodName19;
    private String[] _methodParameterTypes19;
    private String _methodName20;
    private String[] _methodParameterTypes20;
    private String _methodName21;
    private String[] _methodParameterTypes21;

    public AHContactLocalServiceClp(InvokableLocalService invokableLocalService) {
        _invokableLocalService = invokableLocalService;

        _methodName0 = "addAHContact";

        _methodParameterTypes0 = new String[] {
                "de.fraunhofer.fokus.oefit.particity.model.AHContact"
            };

        _methodName1 = "createAHContact";

        _methodParameterTypes1 = new String[] { "long" };

        _methodName2 = "deleteAHContact";

        _methodParameterTypes2 = new String[] { "long" };

        _methodName3 = "deleteAHContact";

        _methodParameterTypes3 = new String[] {
                "de.fraunhofer.fokus.oefit.particity.model.AHContact"
            };

        _methodName4 = "dynamicQuery";

        _methodParameterTypes4 = new String[] {  };

        _methodName5 = "dynamicQuery";

        _methodParameterTypes5 = new String[] {
                "com.liferay.portal.kernel.dao.orm.DynamicQuery"
            };

        _methodName6 = "dynamicQuery";

        _methodParameterTypes6 = new String[] {
                "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int"
            };

        _methodName7 = "dynamicQuery";

        _methodParameterTypes7 = new String[] {
                "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int",
                "com.liferay.portal.kernel.util.OrderByComparator"
            };

        _methodName8 = "dynamicQueryCount";

        _methodParameterTypes8 = new String[] {
                "com.liferay.portal.kernel.dao.orm.DynamicQuery"
            };

        _methodName9 = "dynamicQueryCount";

        _methodParameterTypes9 = new String[] {
                "com.liferay.portal.kernel.dao.orm.DynamicQuery",
                "com.liferay.portal.kernel.dao.orm.Projection"
            };

        _methodName10 = "fetchAHContact";

        _methodParameterTypes10 = new String[] { "long" };

        _methodName11 = "getAHContact";

        _methodParameterTypes11 = new String[] { "long" };

        _methodName12 = "getPersistedModel";

        _methodParameterTypes12 = new String[] { "java.io.Serializable" };

        _methodName13 = "getAHContacts";

        _methodParameterTypes13 = new String[] { "int", "int" };

        _methodName14 = "getAHContactsCount";

        _methodParameterTypes14 = new String[] {  };

        _methodName15 = "updateAHContact";

        _methodParameterTypes15 = new String[] {
                "de.fraunhofer.fokus.oefit.particity.model.AHContact"
            };

        _methodName16 = "getBeanIdentifier";

        _methodParameterTypes16 = new String[] {  };

        _methodName17 = "setBeanIdentifier";

        _methodParameterTypes17 = new String[] { "java.lang.String" };

        _methodName19 = "addContact";

        _methodParameterTypes19 = new String[] {
                "java.lang.String", "java.lang.String", "java.lang.String",
                "java.lang.String", "java.lang.String", "java.lang.String"
            };

        _methodName20 = "getByMail";

        _methodParameterTypes20 = new String[] { "java.lang.String" };

        _methodName21 = "getByName";

        _methodParameterTypes21 = new String[] {
                "java.lang.String", "java.lang.String"
            };
    }

    @Override
    public de.fraunhofer.fokus.oefit.particity.model.AHContact addAHContact(
        de.fraunhofer.fokus.oefit.particity.model.AHContact ahContact)
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName0,
                    _methodParameterTypes0,
                    new Object[] { ClpSerializer.translateInput(ahContact) });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (de.fraunhofer.fokus.oefit.particity.model.AHContact) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public de.fraunhofer.fokus.oefit.particity.model.AHContact createAHContact(
        long contactId) {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName1,
                    _methodParameterTypes1, new Object[] { contactId });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (de.fraunhofer.fokus.oefit.particity.model.AHContact) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public de.fraunhofer.fokus.oefit.particity.model.AHContact deleteAHContact(
        long contactId)
        throws com.liferay.portal.kernel.exception.PortalException,
            com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName2,
                    _methodParameterTypes2, new Object[] { contactId });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
                throw (com.liferay.portal.kernel.exception.PortalException) t;
            }

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (de.fraunhofer.fokus.oefit.particity.model.AHContact) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public de.fraunhofer.fokus.oefit.particity.model.AHContact deleteAHContact(
        de.fraunhofer.fokus.oefit.particity.model.AHContact ahContact)
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName3,
                    _methodParameterTypes3,
                    new Object[] { ClpSerializer.translateInput(ahContact) });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (de.fraunhofer.fokus.oefit.particity.model.AHContact) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery() {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName4,
                    _methodParameterTypes4, new Object[] {  });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (com.liferay.portal.kernel.dao.orm.DynamicQuery) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    @SuppressWarnings("rawtypes")
    public java.util.List dynamicQuery(
        com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName5,
                    _methodParameterTypes5,
                    new Object[] { ClpSerializer.translateInput(dynamicQuery) });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (java.util.List) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    @SuppressWarnings("rawtypes")
    public java.util.List dynamicQuery(
        com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start,
        int end) throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName6,
                    _methodParameterTypes6,
                    new Object[] {
                        ClpSerializer.translateInput(dynamicQuery),

                    start,

                    end
                    });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (java.util.List) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    @SuppressWarnings("rawtypes")
    public java.util.List dynamicQuery(
        com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start,
        int end,
        com.liferay.portal.kernel.util.OrderByComparator orderByComparator)
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName7,
                    _methodParameterTypes7,
                    new Object[] {
                        ClpSerializer.translateInput(dynamicQuery),

                    start,

                    end,

                    ClpSerializer.translateInput(orderByComparator)
                    });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (java.util.List) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public long dynamicQueryCount(
        com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName8,
                    _methodParameterTypes8,
                    new Object[] { ClpSerializer.translateInput(dynamicQuery) });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return ((Long) returnObj).longValue();
    }

    @Override
    public long dynamicQueryCount(
        com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery,
        com.liferay.portal.kernel.dao.orm.Projection projection)
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName9,
                    _methodParameterTypes9,
                    new Object[] {
                        ClpSerializer.translateInput(dynamicQuery),

                    ClpSerializer.translateInput(projection)
                    });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return ((Long) returnObj).longValue();
    }

    @Override
    public de.fraunhofer.fokus.oefit.particity.model.AHContact fetchAHContact(
        long contactId)
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName10,
                    _methodParameterTypes10, new Object[] { contactId });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (de.fraunhofer.fokus.oefit.particity.model.AHContact) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public de.fraunhofer.fokus.oefit.particity.model.AHContact getAHContact(
        long contactId)
        throws com.liferay.portal.kernel.exception.PortalException,
            com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName11,
                    _methodParameterTypes11, new Object[] { contactId });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
                throw (com.liferay.portal.kernel.exception.PortalException) t;
            }

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (de.fraunhofer.fokus.oefit.particity.model.AHContact) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public com.liferay.portal.model.PersistedModel getPersistedModel(
        java.io.Serializable primaryKeyObj)
        throws com.liferay.portal.kernel.exception.PortalException,
            com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName12,
                    _methodParameterTypes12,
                    new Object[] { ClpSerializer.translateInput(primaryKeyObj) });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
                throw (com.liferay.portal.kernel.exception.PortalException) t;
            }

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (com.liferay.portal.model.PersistedModel) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public java.util.List<de.fraunhofer.fokus.oefit.particity.model.AHContact> getAHContacts(
        int start, int end)
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName13,
                    _methodParameterTypes13, new Object[] { start, end });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (java.util.List<de.fraunhofer.fokus.oefit.particity.model.AHContact>) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public int getAHContactsCount()
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName14,
                    _methodParameterTypes14, new Object[] {  });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return ((Integer) returnObj).intValue();
    }

    @Override
    public de.fraunhofer.fokus.oefit.particity.model.AHContact updateAHContact(
        de.fraunhofer.fokus.oefit.particity.model.AHContact ahContact)
        throws com.liferay.portal.kernel.exception.SystemException {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName15,
                    _methodParameterTypes15,
                    new Object[] { ClpSerializer.translateInput(ahContact) });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
                throw (com.liferay.portal.kernel.exception.SystemException) t;
            }

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (de.fraunhofer.fokus.oefit.particity.model.AHContact) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public java.lang.String getBeanIdentifier() {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName16,
                    _methodParameterTypes16, new Object[] {  });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (java.lang.String) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public void setBeanIdentifier(java.lang.String beanIdentifier) {
        try {
            _invokableLocalService.invokeMethod(_methodName17,
                _methodParameterTypes17,
                new Object[] { ClpSerializer.translateInput(beanIdentifier) });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }
    }

    @Override
    public java.lang.Object invokeMethod(java.lang.String name,
        java.lang.String[] parameterTypes, java.lang.Object[] arguments)
        throws java.lang.Throwable {
        throw new UnsupportedOperationException();
    }

    @Override
    public de.fraunhofer.fokus.oefit.particity.model.AHContact addContact(
        java.lang.String forename, java.lang.String surname,
        java.lang.String phone, java.lang.String fax, java.lang.String mail,
        java.lang.String web) {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName19,
                    _methodParameterTypes19,
                    new Object[] {
                        ClpSerializer.translateInput(forename),

                    ClpSerializer.translateInput(surname),

                    ClpSerializer.translateInput(phone),

                    ClpSerializer.translateInput(fax),

                    ClpSerializer.translateInput(mail),

                    ClpSerializer.translateInput(web)
                    });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (de.fraunhofer.fokus.oefit.particity.model.AHContact) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public java.util.List<de.fraunhofer.fokus.oefit.particity.model.AHContact> getByMail(
        java.lang.String mail) {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName20,
                    _methodParameterTypes20,
                    new Object[] { ClpSerializer.translateInput(mail) });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (java.util.List<de.fraunhofer.fokus.oefit.particity.model.AHContact>) ClpSerializer.translateOutput(returnObj);
    }

    @Override
    public java.util.List<de.fraunhofer.fokus.oefit.particity.model.AHContact> getByName(
        java.lang.String forename, java.lang.String surname) {
        Object returnObj = null;

        try {
            returnObj = _invokableLocalService.invokeMethod(_methodName21,
                    _methodParameterTypes21,
                    new Object[] {
                        ClpSerializer.translateInput(forename),

                    ClpSerializer.translateInput(surname)
                    });
        } catch (Throwable t) {
            t = ClpSerializer.translateThrowable(t);

            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t.getClass().getName() +
                    " is not a valid exception");
            }
        }

        return (java.util.List<de.fraunhofer.fokus.oefit.particity.model.AHContact>) ClpSerializer.translateOutput(returnObj);
    }
}


text:
SPARQL + Ruby = SPARB

## Demos
[TODO: some notebooks here]()

## Usage

```ruby
require 'sparb'

dbp = PREFIXES.dbp
rdf = PREFIXES.rdf
geo = PREFIXES.geo
dbo = PREFIXES.dbo

q = Query.new(dbp)
   .where(country, rdf.type, dbo.Country)
   .where(country, dbo.capital, capital)

df = q.send
```

This Ruby code will generate SPARQL equal to the following one:

```
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
PREFIX dbo: <http://dbpedia.org/ontology/>

SELECT *
WHERE {
  ?country rdf:type dbo:Country .
  ?country  dbo:capital ?capital .
}
```

You can add new conditions to the exsisting `Query` object:

```ruby
q.where(continent, dbp.continent, country)
 .filter{ continent == "Asia" }

df = q.send
```

## Acknowledgement

This software will be developed as a product in [BioHackathon 2015](), held in Nagasaki University.
(But not yet :)

## LICENSE
MIT License

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace LeKoala\DebugBar\Collector;

use LeKoala\DebugBar\DebugBar;
use SilverStripe\Control\Director;
use DebugBar\DataCollector\Renderable;
use DebugBar\DataCollector\AssetProvider;
use DebugBar\DataCollector\DataCollector;
use LeKoala\DebugBar\Extension\ProxyDBExtension;

/**
 * Collects data about SQL statements executed through the proxied behaviour
 */
class DatabaseCollector extends DataCollector implements Renderable, AssetProvider
{
    /**
     * @var TimeDataCollector
     */
    protected $timeCollector;

    /**
     * @return array
     */
    public function collect()
    {
        $this->timeCollector = DebugBar::getDebugBar()->getCollector('time');

        $data = $this->collectData($this->timeCollector);

        // Check for excessive number of queries
        $dbQueryWarningLevel = DebugBar::config()->get('warn_query_limit');
        if ($dbQueryWarningLevel && $data['nb_statements'] > $dbQueryWarningLevel) {
            $helpLink = DebugBar::config()->get('performance_guide_link');
            $messages = DebugBar::getMessageCollector();
            if ($messages) {
                $messages->addMessage(
                    "This page ran more than $dbQueryWarningLevel database queries." .
                        "\nYou could reduce this by implementing caching." .
                        "\nYou can find more info here: $helpLink",
                    'warning',
                    true
                );
            }
        }

        return $data;
    }

    /**
     * Explode comma separated elements not within parenthesis or quotes
     *
     * @param string $str
     * @return array
     */
    protected static function explodeFields($str)
    {
        return preg_split("/(?![^(]*\)),/", $str);
    }

    /**
     * Collects data
     *
     * @param TimeDataCollector $timeCollector
     * @return array
     */
    protected function collectData(TimeDataCollector $timeCollector = null)
    {
        $stmts = array();

        $total_duration = 0;
        $total_mem      = 0;

        $failed = 0;

        $i       = 0;

        // Get queries gathered by proxy
        $queries = ProxyDBExtension::getQueries();

        $limit   = DebugBar::config()->get('query_limit');
        $warnDurationThreshold = DebugBar::config()->get('warn_dbqueries_threshold_seconds');

        $showDb = count(array_filter(array_unique(array_map(function ($stmt) {
            return $stmt['database'];
        }, $queries)))) > 1;

        foreach ($queries as $stmt) {
            $i++;

            $total_duration += $stmt['duration'];
            $total_mem += $stmt['memory'];

            if (!$stmt['success']) {
                $failed++;
            }

            if ($limit && $i > $limit) {
                $stmts[] = array(
                    'sql' => "Only the first $limit queries are shown"
                );
                break;
            }

            $stmts[] = array(
                'sql' => $stmt['short_query'],
                'row_count' => $stmt['rows'],
                'params' => $stmt['select'] ? $stmt['select'] : null,
                'duration' => $stmt['duration'],
                'duration_str' => $this->getDataFormatter()->formatDuration($stmt['duration']),
                'memory' => $stmt['memory'],
                'memory_str' => $this->getDataFormatter()->formatBytes($stmt['memory']),
                'is_success' => $stmt['success'],
                'database' => $showDb ? $stmt['database'] : null,
                'source' => $stmt['source'],
                'warn' => $stmt['duration'] > $warnDurationThreshold
            );

            if ($timeCollector !== null) {
                $timeCollector->addMeasure(
                    $stmt['short_query'],
                    $stmt['start_time'],
                    $stmt['end_time']
                );
            }
        }

        return array(
            'nb_statements' => count($queries),
            'nb_failed_statements' => $failed,
            'statements' => $stmts,
            'accumulated_duration' => $total_duration,
            'accumulated_duration_str' => $this->getDataFormatter()->formatDuration($total_duration),
            'memory_usage' => $total_mem,
            'memory_usage_str' => $this->getDataFormatter()->formatBytes($total_mem),
        );
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'db';
    }

    /**
     * @return array
     */
    public function getWidgets()
    {
        return array(
            "database" => array(
                "icon" => "database",
                "widget" => "PhpDebugBar.Widgets.SQLQueriesWidget",
                "map" => "db",
                "default" => "[]"
            ),
            "database:badge" => array(
                "map" => "db.nb_statements",
                "default" => 0
            )
        );
    }

    /**
     * @return array
     */
    public function getAssets()
    {
        return array(
            'base_path' => '/' . DebugBar::moduleResource('javascript')->getRelativePath(),
            'base_url' => Director::makeRelative(DebugBar::moduleResource('javascript')->getURL()),
            'css' => 'sqlqueries/widget.css',
            'js' => 'sqlqueries/widget.js'
        );
    }
}


text:
'use strict';

/**
* FUNCTION: serialize( b )
*	Serializes a Buffer object for dynamic code evaluation.
*
* @param {Buffer} b - Buffer object
* @returns {String} serialized value
*/
function serialize( b ) {
	return 'new Buffer("'+( b.toString( 'base64' ) )+'","base64")';
} // end FUNCTION serialize()

// EXPORTS //

module.exports = serialize;


text:
<?php

namespace Drupal\metatag_app_links\Plugin\metatag\Tag;

use Drupal\metatag\Plugin\metatag\Tag\MetaPropertyBase;

/**
 * The AppLinks Windows Phone app ID meta tag.
 *
 * @MetatagTag(
 *   id = "al_windows_phone_app_id",
 *   label = @Translation("Windows Phone app ID"),
 *   description = @Translation("The app ID for the app store."),
 *   name = "al:windows_phone:app_id",
 *   group = "app_links",
 *   weight = 1,
 *   type = "string",
 *   secure = FALSE,
 *   multiple = FALSE
 * )
 */
class AlWindowsPhoneAppId extends MetaPropertyBase {
  // Nothing here yet. Just a placeholder class for a plugin.
}


text:
using System.ComponentModel;

namespace LinqAn.Google.Dimensions
{
	/// <summary>
	/// 	The name of the requested custom dimension, where 103 refers the number/index of the custom dimension.
	/// </summary>
	[Description("The name of the requested custom dimension, where 103 refers the number/index of the custom dimension.")]
	public class Dimension103: Dimension
	{
		/// <summary>
		/// 	Instantiates a <seealso cref="Dimension103" />.
		/// </summary>
		public Dimension103(): base("Custom Dimension 103",true,"ga:dimension103")
		{

		}
	}
}


text:
require 'java'

module RR
  module ConnectionExtenders

    # Provides various JDBC specific functionality required by Rubyrep.
    module JdbcSQLExtender
      RR::ConnectionExtenders.register :jdbc => self

      # Monkey patch for activerecord-jdbc-adapter-0.7.2 as it doesn't set the
      # +@active+ flag to false, thus ActiveRecord#active? incorrectly confirms
      # the connection to still be active.
      def disconnect!
        super
        @active = false
      end

      # Returns an ordered list of primary key column names of the given table
      def primary_key_names(table)
        if tables.grep(/^#{table}$/i).empty?
          # Note: Cannot use tables.include? as returned tables are made lowercase under JRuby MySQL
          raise "table '#{table}' does not exist"
        end
        columns = []
        result_set = @connection.connection.getMetaData.getPrimaryKeys(nil, nil, table.upcase);
        while result_set.next
          column_name = result_set.getString("COLUMN_NAME").downcase
          key_seq = result_set.getShort("KEY_SEQ")
          columns << {:column_name => column_name, :key_seq => key_seq}
        end
        columns.sort! {|a, b| a[:key_seq] <=> b[:key_seq]}
        key_names = columns.map {|column| column[:column_name]}
        key_names
      end

      # Returns for each given table, which other tables it references via
      # foreign key constraints.
      # * tables: an array of table names
      # * returns: a hash with
      #   * key: name of the referencing table
      #   * value: an array of names of referenced tables
      def referenced_tables(tables)
        result = {}
        tables.each do |table|
          references_of_this_table = []
          result_set = @connection.connection.getMetaData.getImportedKeys(nil, nil, table)
          while result_set.next
            referenced_table = result_set.getString("PKTABLE_NAME")
            unless references_of_this_table.include? referenced_table
              references_of_this_table << referenced_table
            end
          end
          result[table] = references_of_this_table
        end
        result
      end
    end

    # PostgreSQL specific functionality not provided by the standard JDBC
    # connection extender:
    # * Hack to get schema support for Postgres under JRuby on par with the
    #   standard ruby version.
    module JdbcPostgreSQLExtender
      require 'jdbc_adapter/jdbc_postgre'
      require "#{File.dirname(__FILE__)}/postgresql_extender"

      include PostgreSQLExtender

      class JdbcPostgreSQLColumn < ActiveRecord::ConnectionAdapters::Column
        include ::JdbcSpec::PostgreSQL::Column
      end

      # Returns the list of all column definitions for a table.
      def columns(table_name, name = nil)
        # Limit, precision, and scale are all handled by the superclass.
        column_definitions(table_name).collect do |name, type, default, notnull|
          JdbcPostgreSQLColumn.new(name, default, type, notnull == 'f')
        end
      end

      # Sets the schema search path as per configuration parameters
      def initialize_search_path
        execute "SET search_path TO #{config[:schema_search_path]}" if config[:schema_search_path]
      end

      # Converts the given Time object into the correctly formatted string
      # representation.
      #
      # Monkeypatched as activerecord-jdbcpostgresql-adapter (at least in version
      # 0.8.2) does otherwise "loose" the microseconds when writing Time values
      # to the database.
      def quoted_date(value)
        "#{value.strftime("%Y-%m-%d %H:%M:%S")}#{value.respond_to?(:usec) ? ".#{value.usec.to_s.rjust(6, '0')}" : ""}"
      end
    end
  end
end


text:
local json          = require("cjson")

local math_floor    = math.floor
local string_char   = string.char
local string_byte   = string.byte
local string_rep    = string.rep
local string_sub    = string.sub
local debug_getinfo = debug.getinfo

local mchvars = require("mch.vars")

module('mch.util', package.seeall)

function read_all(filename)
    local file = io.open(filename, "r")
    local data = ((file and file:read("*a")) or nil)
    if file then
        file:close()
    end
    return data
end

function setup_app_env(mch_home, app_name, app_path, global)
    global['MOOCHINE_HOME']=mch_home
    global['MOOCHINE_APP']=app_name
    global['MOOCHINE_APP_PATH']=app_path
    package.path = mch_home .. '/lualibs/?.lua;' .. package.path
    package.path = app_path .. '/app/?.lua;' .. package.path
    local request=require("mch.request")
    local response=require("mch.response")
    global['MOOCHINE_MODULES']={}
    global['MOOCHINE_MODULES']['request']=request
    global['MOOCHINE_MODULES']['response']=response
end

function loadvars(file)
    local env = setmetatable({}, {__index=_G})
    assert(pcall(setfenv(assert(loadfile(file)), env)))
    setmetatable(env, nil)
    return env
end

function get_config(key, default)
    if key == nil then return nil end
    local issub, subname = is_subapp(3)

    if not issub then -- main app
        local ret = ngx.var[key]
        if ret then return ret end
        local app_conf=mchvars.get(ngx.ctx.MOOCHINE_APP_NAME,"APP_CONFIG")

        local v = app_conf[key]
        if v==nil then v = default end
        return v
    end

    -- sub app
    if not subname then return default end
    local subapps=mchvars.get(ngx.ctx.MOOCHINE_APP_NAME,"APP_CONFIG").subapps or {}
    local subconfig=subapps[subname].config or {}

    local v = subconfig[key]
    if v==nil then v = default end
    return v
end

function _strify(o, tab, act, logged)
    local v = tostring(o)
    if logged[o] then return v end
    if string_sub(v,0,6) == "table:" then
        logged[o] = true
        act = "\n" .. string_rep("|    ",tab) .. "{ [".. tostring(o) .. ", "
        act = act .. table_real_length(o) .." item(s)]"
        for k, v in pairs(o) do
            act = act .."\n" .. string_rep("|    ", tab)
            act = act .. "|   *".. k .. "\t=>\t" .. _strify(v, tab+1, act, logged)
        end
        act = act .. "\n" .. string_rep("|    ",tab) .. "}"
        return act
    else
        return v
    end
end

function strify(o) return _strify(o, 1, "", {}) end

function table_print(t)
    local s1="\n* Table String:"
    local s2="\n* End Table"
    return s1 .. strify(t) .. s2
end

function table_real_length(t)
    local count = 0
    for _ in pairs(t) do
        count = count + 1
    end
    return count
end

function is_subapp(__call_frame_level)
    if not __call_frame_level then __call_frame_level = 2 end
    local caller = debug_getinfo(__call_frame_level,'S').source
    local main_app = ngx.var.MOOCHINE_APP_PATH

    local is_mainapp = (main_app == (string_sub(caller, 2, #main_app+1)))
    if is_mainapp then return false, nil end -- main app

    local subapps = mchvars.get(ngx.ctx.MOOCHINE_APP_NAME, "APP_CONFIG").subapps or {}
    for k, v in pairs(subapps) do
        local spath = v.path
        local is_this_subapp = (spath == (string_sub(caller, 2, #spath+1)))
        if is_this_subapp then return true, k end -- sub app
    end

    return false, nil -- not main/sub app, maybe call in moochine!
end

function parseNetInt(bytes)
    local a, b, c, d = string_byte(bytes, 1, 4)
    return a * 256 ^ 3 + b * 256 ^ 2 + c * 256 + d
end

function toNetInt(n)
    -- NOTE: for little endian machine only!!!
    local d = n % 256
    n = math_floor(n / 256)
    local c = n % 256
    n = math_floor(n / 256)
    local b = n % 256
    n = math_floor(n / 256)
    local a = n
    return string_char(a) .. string_char(b) .. string_char(c) .. string_char(d)
end

function write_jsonresponse(sock, s)
    if type(s) == 'table' then
        s = json.encode(s)
    end
    local l = toNetInt(#s)
    sock:send(l .. s)
end

function read_jsonresponse(sock)
    local r, err = sock:receive(4)
    if not r then
        logger:warn('Error when receiving from socket: %s', err)
        return
    end
    local len = parseNetInt(r)
    local data, err = sock:receive(len)
    if not data then
        logger:error('Error when receiving from socket: %s', err)
        return
    end
    return json.decode(data)
end


text:
// Utils
import {valueFetcher, ValueFetcher} from 'src/variables/utils/ValueFetcher'
import Deferred from 'src/utils/Deferred'
import {asAssignment} from 'src/variables/selectors'
import {isFlagEnabled} from 'src/shared/utils/featureFlag'

// Constants
import {OPTION_NAME, BOUNDARY_GROUP} from 'src/variables/constants/index'

// Types
import {
  RemoteDataState,
  Variable,
  VariableValues,
  ValueSelections,
} from 'src/types'
import {CancelBox, CancellationError} from 'src/types/promises'

export interface VariableNode {
  variable: Variable
  values: VariableValues
  parents: VariableNode[]
  children: VariableNode[]
  status: RemoteDataState
  cancel: () => void
}

interface HydrateVarsOptions {
  url: string
  orgID: string
  selections?: ValueSelections
  fetcher?: ValueFetcher
  skipCache?: boolean
  controller?: AbortController
}

export interface EventedCancelBox<T> extends CancelBox<T> {
  on?: any
}

export const createVariableGraph = (
  allVariables: Variable[]
): VariableNode[] => {
  const nodesByID: {[variableID: string]: VariableNode} = allVariables.reduce(
    (prev, curr) => {
      let status = RemoteDataState.Done
      if (curr.arguments.type === 'query') {
        status = RemoteDataState.NotStarted
      }
      prev[curr.id] = {
        variable: curr,
        values: null,
        parents: [],
        children: [],
        status,
        cancel: () => {},
      }
      return prev
    },
    {}
  )

  // Then initialize all the edges (the `parents` and `children` references)
  Object.keys(nodesByID)
    .filter(k => nodesByID[k].variable.arguments.type === 'query')
    .forEach(k => {
      getVarChildren(nodesByID[k].variable, allVariables)
        .map(child => child.id)
        .forEach(c => {
          nodesByID[k].children.push(nodesByID[c])
          nodesByID[c].parents.push(nodesByID[k])
        })
    })

  return Object.values(nodesByID)
}

export const isInQuery = (query: string, v: Variable): boolean => {
  const regexp = new RegExp(
    `${BOUNDARY_GROUP}${OPTION_NAME}.${v.name}${BOUNDARY_GROUP}`
  )

  return regexp.test(query)
}

const getVarChildren = (
  {
    arguments: {
      values: {query},
    },
  }: Variable,
  allVariables: Variable[]
) => allVariables.filter(maybeChild => isInQuery(query, maybeChild))

/*
  Collect all ancestors of a node.

  A node `a` is an ancestor of `b` if there exists a path from `a` to `b`.

  This function is safe to call on a node within a graph with cycles.
*/
const collectAncestors = (
  node: VariableNode,
  acc: Set<VariableNode> = new Set()
): VariableNode[] => {
  for (const parent of node.parents) {
    if (!acc.has(parent)) {
      acc.add(parent)
      collectAncestors(parent, acc)
    }
  }

  return [...acc]
}

/*
  Using the current node as the root, create a PostOrder DFS for the given node
  Where we check each cascading parent's children in order to hydrate the children before the parents

  In the example below, we have 3 variables `a`, `b`, `c` where `a` is a parent to `b`, which a parent to `c`:

  a --> b --> c

  If `a`, `b`, or `c` are passed into this function, we should expect that the output for each should be:

  `c` with a reference to its parent `b`, which should have a reference to its parent `a`
*/

const postOrderDFS = (
  node: VariableNode,
  acc: Set<VariableNode> = new Set(),
  cache: {[key: string]: boolean | undefined} = {}
): VariableNode[] => {
  // Handle the edge case that the function is
  // called without providing the root node
  if (!node) return [...acc]

  for (const child of node.children) {
    // by checking the cache for existing variables, we ensure that the graph stops
    // when an existing node has already been encountered, invalidating a cycle if one exists
    if (!cache[child.variable.id]) {
      cache[child.variable.id] = true
      // Recurse down the n-ary tree until we reach a leaf (node with no children)
      // where this loop will not execute
      postOrderDFS(child, acc, cache)
    }
  }

  // Add the current node only after visiting all of its children, left to right
  acc.add(node)

  return [...acc]
}

/*
  Filters out any parents that have already been referenced in a previous node

  A node `a` & `c` are children of `b` if there exists a path:

            b
          /   \
         a     c

  This function safely filters out a duplicate reference to the parent `b`
  When both `a` and `c` are passed as variables to be hydrated, since `b` should
  already be `hydrated` by the first variable that is passed in.
*/
export interface DeduplicatedRoot {
  node: VariableNode
  subsetIDs: {[key: string]: boolean}
}

const getDeduplicatedRootChild = (
  node: VariableNode,
  subsetIDs: {[key: string]: boolean | undefined}
): DeduplicatedRoot => {
  for (const n of node.parents) {
    if (!subsetIDs[n.variable.id]) {
      subsetIDs[n.variable.id] = true
      getDeduplicatedRootChild(n, subsetIDs)
    } else {
      node.parents = []
    }
  }
  return {node, subsetIDs}
}

/*
  Given a variable graph, return the minimal subgraph containing only the nodes
  needed to hydrate the values for variables in the passed `variables` argument.

  We discard all nodes in the graph unless:

  - It is the node for one of the passed variables
  - The node for one of the passed variables depends on this node

*/
// TODO(ariel): rename this back to findSubgraph & update tests once feature flag is removed
export const findSubgraphFeature = (
  graph: VariableNode[],
  variables: Variable[]
): VariableNode[] => {
  const subgraph: Set<VariableNode> = new Set()
  // use an ID array to reduce the chance of reference errors
  const varIDs = variables.map(v => v.id)
  // create an ID reference object to identify relevant root variables to hydrate
  let subgraphIDs = {}
  for (const node of graph) {
    const shouldKeep = varIDs.includes(node.variable.id)
    if (shouldKeep) {
      const postOrderNodeList = postOrderDFS(node)
      postOrderNodeList.forEach(variableNode => {
        const {id} = variableNode.variable
        // Checking whether the subgraphIDs[id] !== true, we are ensuring that the
        // node has been added to the subgraph. This prevents excessive variable rehydration
        if (subgraphIDs[id] !== true) {
          /*
            Once a node exists within the subgraph (whether nested as a parent or as the input node)
            we want to remove any further reference to that node within the subgraph.
            This can be particularly challenging when a parent node has multiple child nodes that have been passed in.
            For example, if variables `a` and `b` are both children to `c`,
            and `a` & `b` are both variables that should be hydrated, we would need to reset a parent
            reference for one of the variables so that `c` is not hydrated twice.
            This can be achieved by storing a reference to all the existing nodeIDs within the subgraph to the `graphIDs`
            and checking for any collisions before adding the node to the subgraph.
            If a parent collision is detected, that node's parent is simply set to [] since we know that
            the parent was already hydrated based on a previous input
          */
          const {node: filteredNodes, subsetIDs} = getDeduplicatedRootChild(
            variableNode,
            subgraphIDs
          )
          subgraph.add(filteredNodes)
          subgraphIDs = {
            [id]: true,
            ...subgraphIDs,
            ...subsetIDs,
          }
        }
      })
    }
  }

  return [...subgraph]
}
export const findSubgraph = (
  graph: VariableNode[],
  variables: Variable[]
): VariableNode[] => {
  const subgraph: Set<VariableNode> = new Set()
  // use an ID array to reduce the chance of reference errors
  const varIDs = variables.map(v => v.id)
  for (const node of graph) {
    const shouldKeep =
      varIDs.includes(node.variable.id) ||
      collectAncestors(node).some(ancestor =>
        varIDs.includes(ancestor.variable.id)
      )

    if (shouldKeep) {
      subgraph.add(node)
    }
  }

  for (const node of subgraph) {
    node.parents = node.parents.filter(node => subgraph.has(node))
    node.children = node.children.filter(node => subgraph.has(node))
  }
  return [...subgraph]
}

/*
  Get the `VariableValues` for a variable that cannot be successfully hydrated.
*/
const errorVariableValues = (
  message = 'Failed to load values for variable'
): VariableValues => ({
  values: null,
  selected: null,
  valueType: null,
  error: message,
})

/*
  Find all the descendants of a node.

  A node `b` is a descendant of `a` if there exists a path from `a` to `b`.

  Checks visited to prevent looping forever
*/
export const collectDescendants = (
  node: VariableNode,
  acc: Set<VariableNode> = new Set()
): VariableNode[] => {
  for (const child of node.children) {
    if (!acc.has(child)) {
      acc.add(child)
      collectDescendants(child, acc)
    }
  }

  return [...acc]
}

/*
  Hydrate the values of a single node in the graph.

  This assumes that every descendant of this node has already been hydrated.
*/
// TODO: figure out how to type the `on` function
const hydrateVarsHelper = async (
  node: VariableNode,
  options: HydrateVarsOptions,
  on?: any
): Promise<VariableValues> => {
  const variableType = node.variable.arguments.type

  // this assumes that the variable hydration is done in the selector 'getVariable'
  if (variableType === 'map') {
    return {
      valueType: 'string',
      values: node.variable.arguments.values,
      selected: node.variable.selected,
    }
  }

  if (variableType === 'constant') {
    return {
      valueType: 'string',
      values: node.variable.arguments.values,
      selected: node.variable.selected,
    }
  }

  if (variableType === 'system') {
    return {
      valueType: 'string',
      values: node.variable.arguments.values,
      selected: node.variable.selected,
    }
  }

  if (node.status !== RemoteDataState.Loading) {
    node.status = RemoteDataState.Loading
    on.fire('status', node.variable, node.status)
    collectAncestors(node)
      .filter(parent => parent.variable.arguments.type === 'query')
      .forEach(parent => {
        if (parent.status !== RemoteDataState.Loading) {
          parent.status = RemoteDataState.Loading
          on.fire('status', parent.variable, parent.status)
        }
      })
  }

  const descendants = collectDescendants(node)
  const assignments = descendants
    .map(node => asAssignment(node.variable))
    .filter(v => !!v)

  const {url, orgID} = options
  const {query} = node.variable.arguments.values
  const fetcher = options.fetcher || valueFetcher

  const request = fetcher.fetch(
    url,
    orgID,
    query,
    assignments,
    null,
    '',
    options.skipCache,
    options.controller
  )

  node.cancel = request.cancel

  const values = await request.promise

  // NOTE: do not fire `done` event here, as the value
  // has not been properly hydrated yet
  node.status = RemoteDataState.Done
  return values
}

/*
  Check if a node is `NotStarted` and if every child of the node has been
  resolved (successfully or not).
*/
const readyToResolve = (parent: VariableNode): boolean =>
  parent.children.every(child => child.status === RemoteDataState.Done)

/*
  Find all `NotStarted` nodes in the graph that have no children.
*/
const findLeaves = (graph: VariableNode[]): VariableNode[] =>
  graph.filter(node => node.children.length === 0)

/*
  Given a node, attempt to find a cycle that the node is a part of. If no cycle
  is found, return `null`.
*/
const findCyclicPath = (node: VariableNode): VariableNode[] => {
  try {
    findCyclicPathHelper(node, [], {})
  } catch (cyclicPath) {
    return cyclicPath
  }

  return null
}

const findCyclicPathHelper = (
  node: VariableNode,
  seen: VariableNode[],
  cache: {[key: string]: undefined | boolean} = {}
): void => {
  if (cache[node.variable.id]) {
    throw seen
  }

  for (const child of node.children) {
    findCyclicPathHelper(child, [...seen, node], {
      ...cache,
      [node.variable.id]: true,
    })
  }
}

/*
  Find all cycles within the variable graph and mark every node within a cycle
  as errored (we cannot resolve cycles).
*/
const invalidateCycles = (graph: VariableNode[]): void => {
  for (const node of graph) {
    const cyclicPath = findCyclicPath(node)

    if (cyclicPath) {
      for (const invalidNode of cyclicPath) {
        invalidNode.status = RemoteDataState.Error
      }
    }
  }
}

/*
  Given a node, mark all ancestors of that node as `Error`.
*/
const invalidateAncestors = (node: VariableNode): void => {
  const ancestors = collectAncestors(node)

  for (const ancestor of ancestors) {
    ancestor.status = RemoteDataState.Error
    if (ancestor.variable.arguments.type === 'query') {
      ancestor.variable.arguments.values.results = []
    }
  }
}

const extractResult = (graph: VariableNode[]): Variable[] => {
  const result = {}

  for (const node of graph) {
    if (node.status === RemoteDataState.Error) {
      node.values = errorVariableValues()
    }

    result[node.variable.id] = node.variable
  }

  return Object.values(result)
}

/*
  Given a list of `variables`, execute their queries to retrieve the possible
  values for each variable.

  Since variables can make use of other variables, this process is more
  complicated then simply executing every query found in a variable. Instead,
  we:

  1. Construct a graph that represents the dependency structure between
     variables. A variable `a` depends on variable `b` if the query for `a`
     uses the variable `b`.

     Each node in the graph has a hydration status: it it either `NotStarted`,
     `Loading` (values are being fetched), `Error` (values failed to fetch or
     cannot be fetched), or `Done` (values have been fetched successfully).
     When the graph is constructed, all nodes a marked as `NotStarted`.

  2. Find all cycles in the graph and mark nodes within a cycle and nodes that
     lead to a cycle as `Error`. We cannot resolve variables with cyclical
     dependencies.

  3. Find the leaves of the graph (the nodes with no dependencies) and begin to
     load their values.

     a. If loading the values succeeds, we mark that node as `Done` and check
        if every child of the parent of this node is `Done`. If this is the
        case, we start loading the parent.

     b. If loading the values fails, we mark that node and every one of its
        ancestors as as `Error`.

     c. If the parent node is `Error`, we stop resolving along this path. Steps
        2 and 3b guarantee that every ancestor of this `Error` node is also
        `Error`.

  4. By the time all node resolution has succeeded or failed, every node in the
     graph has now either been resolved with values or marked with `Error`.

*/
export const hydrateVars = (
  variables: Variable[],
  allVariables: Variable[],
  options: HydrateVarsOptions
): EventedCancelBox<Variable[]> => {
  let findSubgraphFunction = findSubgraph
  if (isFlagEnabled('hydratevars')) {
    findSubgraphFunction = findSubgraphFeature
  }

  const graph = findSubgraphFunction(
    createVariableGraph(allVariables),
    variables
  ).filter(n => n.variable.arguments.type !== 'system')
  invalidateCycles(graph)

  let isCancelled = false

  const resolve = async (node: VariableNode) => {
    if (isCancelled) {
      return
    }
    try {
      // TODO: terminate the concept of node.values at the fetcher and just use variables
      node.values = await hydrateVarsHelper(node, options, on)

      if (node.variable.arguments.type === 'query') {
        node.variable.arguments.values.results = node.values.values as string[]
      } else {
        node.variable.arguments.values = node.values.values
      }

      node.variable.selected = node.variable.selected || []

      // ensure that the selected value defaults propegate for
      // nested queryies.
      if (
        node.variable.arguments.type === 'query' ||
        node.variable.arguments.type === 'constant'
      ) {
        if (
          !(node.values.values as string[]).includes(node.variable.selected[0])
        ) {
          node.variable.selected = []
        }
      } else if (node.variable.arguments.type === 'map') {
        if (
          !Object.keys(node.values.values).includes(node.variable.selected[0])
        ) {
          node.variable.selected = []
        }
      }

      if (!node.variable.selected || !node.variable.selected[0]) {
        node.variable.selected = node.values.selected
      }

      on.fire('status', node.variable, node.status)

      return Promise.all(node.parents.filter(readyToResolve).map(resolve))
    } catch (e) {
      if (e.name === 'CancellationError') {
        return
      }

      node.status = RemoteDataState.Error
      node.variable.arguments.values.results = []

      invalidateAncestors(node)
    }
  }

  const deferred = new Deferred()

  const cancel = () => {
    isCancelled = true
    graph.forEach(node => node.cancel())
    deferred.reject(new CancellationError())
  }

  const on = (function() {
    const callbacks = {}
    const ret = (evt, cb) => {
      if (!callbacks.hasOwnProperty(evt)) {
        callbacks[evt] = []
      }

      callbacks[evt].push(cb)
    }

    ret.fire = (evt, ...args) => {
      if (!callbacks.hasOwnProperty(evt)) {
        return
      }

      callbacks[evt].forEach(cb => cb.apply(cb, args))
    }

    return ret
  })()

  // NOTE: wrapping in a resolve disconnects the following findLeaves
  // from the main execution thread, allowing external services to
  // register listeners for the loading state changes
  Promise.resolve()
    .then(() => Promise.all(findLeaves(graph).map(resolve)))
    .then(() => {
      deferred.resolve(extractResult(graph))
    })

  return {promise: deferred.promise, cancel, on}
}


text:
using MongoDB.Bson;

namespace nScanty.Data
{
    public static class EditId
    {
        public static ObjectId Id { get; set; }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>statsmodels.duration.hazard_regression.PHReg — statsmodels 0.8.0 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="prev" title="statsmodels.duration.survfunc.SurvfuncRight.summary" href="statsmodels.duration.survfunc.SurvfuncRight.summary.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Methods for Survival and Duration Analysis |

statsmodels.duration.hazard_regression.PHReg¶

class statsmodels.duration.hazard_regression.PHReg(endog, exog, status=None, entry=None, strata=None, offset=None, ties='breslow', missing='drop', **kwargs)[source]¶

Fit the Cox proportional hazards regression model for right
censored data.

<col class="field-name" />
<col class="field-body" />

Parameters:
endog : array-like

The observed times (event or censoring)

exog : 2D array-like

The covariates or exogeneous variables

status : array-like

The censoring status values; status=1 indicates that an
event occured (e.g. failure or death), status=0 indicates
that the observation was right censored. If None, defaults
to status=1 for all cases.

entry : array-like

The entry times, if left truncation occurs

strata : array-like

Stratum labels.  If None, all observations are taken to be
in a single stratum.

ties : string

The method used to handle tied times, must be either ‘breslow’
or ‘efron’.

offset : array-like

Array of offset values

missing : string

The method used to handle missing data

Notes

Proportional hazards regression models should not include an
explicit or implicit intercept.  The effect of an intercept is
not identified using the partial likelihood approach.

endog, event, strata, entry, and the first dimension
of exog all must have the same length

Attributes

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

endog_names
Names of endogenous variables

exog_names
Names of exogenous variables

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

baseline_cumulative_hazard(params)
Estimate the baseline cumulative hazard and survival functions.

baseline_cumulative_hazard_function(params)
Returns a function that calculates the baseline cumulative hazard function for each stratum.

breslow_gradient(params)
Returns the gradient of the log partial likelihood, using the Breslow method to handle tied times.

breslow_hessian(params)
Returns the Hessian of the log partial likelihood evaluated at params, using the Breslow method to handle tied times.

breslow_loglike(params)
Returns the value of the log partial likelihood function evaluated at params, using the Breslow method to handle tied times.

efron_gradient(params)
Returns the gradient of the log partial likelihood evaluated at params, using the Efron method to handle tied times.

efron_hessian(params)
Returns the Hessian matrix of the partial log-likelihood evaluated at params, using the Efron method to handle tied times.

efron_loglike(params)
Returns the value of the log partial likelihood function evaluated at params, using the Efron method to handle tied times.

fit([groups])
Fit a proportional hazards regression model.

fit_regularized([method, alpha, ...])
Return a regularized fit to a linear regression model.

from_formula(formula, data[, status, entry, ...])
Create a proportional hazards regression model from a formula and dataframe.

get_distribution(params)
Returns a scipy distribution object corresponding to the distribution of uncensored endog (duration) values for each case.

hessian(params)
Returns the Hessian matrix of the log partial likelihood function evaluated at params.

information(params)
Fisher information matrix of model

initialize()
Initialize (possibly re-initialize) a Model instance.

loglike(params)
Returns the log partial likelihood function evaluated at params.

predict(params[, exog, cov_params, endog, ...])
Returns predicted values from the proportional hazards regression model.

robust_covariance(params)
Returns a covariance matrix for the proportional hazards model regresion coefficient estimates that is robust to certain forms of model misspecification.

score(params)
Returns the score function evaluated at params.

score_residuals(params)
Returns the score residuals calculated at a given vector of parameters.

weighted_covariate_averages(params)
Returns the hazard-weighted average of covariate values for subjects who are at-risk at a particular time.

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

baseline_cumulative_hazard(params)
Estimate the baseline cumulative hazard and survival functions.

baseline_cumulative_hazard_function(params)
Returns a function that calculates the baseline cumulative hazard function for each stratum.

breslow_gradient(params)
Returns the gradient of the log partial likelihood, using the Breslow method to handle tied times.

breslow_hessian(params)
Returns the Hessian of the log partial likelihood evaluated at params, using the Breslow method to handle tied times.

breslow_loglike(params)
Returns the value of the log partial likelihood function evaluated at params, using the Breslow method to handle tied times.

efron_gradient(params)
Returns the gradient of the log partial likelihood evaluated at params, using the Efron method to handle tied times.

efron_hessian(params)
Returns the Hessian matrix of the partial log-likelihood evaluated at params, using the Efron method to handle tied times.

efron_loglike(params)
Returns the value of the log partial likelihood function evaluated at params, using the Efron method to handle tied times.

fit([groups])
Fit a proportional hazards regression model.

fit_regularized([method, alpha, ...])
Return a regularized fit to a linear regression model.

from_formula(formula, data[, status, entry, ...])
Create a proportional hazards regression model from a formula and dataframe.

get_distribution(params)
Returns a scipy distribution object corresponding to the distribution of uncensored endog (duration) values for each case.

hessian(params)
Returns the Hessian matrix of the log partial likelihood function evaluated at params.

information(params)
Fisher information matrix of model

initialize()
Initialize (possibly re-initialize) a Model instance.

loglike(params)
Returns the log partial likelihood function evaluated at params.

predict(params[, exog, cov_params, endog, ...])
Returns predicted values from the proportional hazards regression model.

robust_covariance(params)
Returns a covariance matrix for the proportional hazards model regresion coefficient estimates that is robust to certain forms of model misspecification.

score(params)
Returns the score function evaluated at params.

score_residuals(params)
Returns the score residuals calculated at a given vector of parameters.

weighted_covariate_averages(params)
Returns the hazard-weighted average of covariate values for subjects who are at-risk at a particular time.

Attributes

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

endog_names
Names of endogenous variables

exog_names
Names of exogenous variables

Previous topic

statsmodels.duration.survfunc.SurvfuncRight.summary

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

        © Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 1.5.3.


text:
/* $Id$
 */
#ifndef HIPE_SPARC_H
#define HIPE_SPARC_H

static __inline__ void hipe_flush_icache_word(void *address)
{
    asm volatile("flush %0"
		 : /* no outputs */
		 : "r"(address)
		 : "memory");
}

extern void hipe_flush_icache_range(void *address, unsigned int nbytes);

/* for stack descriptor hash lookup */
#define HIPE_RA_LSR_COUNT	2	/* low 2 bits are always zero */

/* for hipe_bifs_{read,write}_{s,u}32 */
static __inline__ int hipe_word32_address_ok(void *address)
{
    return ((unsigned long)address & 0x3) == 0;
}

/* Native stack growth direction. */
#define HIPE_NSTACK_GROWS_DOWN

#define hipe_arch_name	am_ultrasparc

extern void hipe_sparc_inc_stack(void);

/* for hipe_bifs_enter_code_2 */
extern void *hipe_alloc_code(Uint nrbytes, Eterm callees, Eterm *trampolines, Process *p);
#define HIPE_ALLOC_CODE(n,c,t,p) hipe_alloc_code((n),(c),(t),(p))

#endif /* HIPE_SPARC_H */


text:
package com.datagre.apps.omicron.config.controller;

import com.datagre.apps.omicron.Omicron;
import com.datagre.apps.omicron.biz.entity.ReleaseMessage;
import com.datagre.apps.omicron.biz.grayReleaseRule.GrayReleaseRulesHolder;
import com.datagre.apps.omicron.biz.message.ReleaseMessageListener;
import com.datagre.apps.omicron.biz.message.Topics;
import com.datagre.apps.omicron.config.util.NamespaceUtil;
import com.datagre.apps.omicron.config.util.WatchKeysUtil;
import com.datagre.apps.omicron.core.ConfigConsts;
import com.datagre.apps.omicron.core.dto.OmicronConfig;
import com.datagre.apps.omicron.core.utils.PropertiesUtil;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.*;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by ycaihua on 2017/4/6.
 * https://github.com/ycaihua/omicron
 */
@RestController
@RequestMapping("/configfiles")
public class ConfigFileController implements ReleaseMessageListener{
    private static final Logger logger = LoggerFactory.getLogger(ConfigFileController.class);
    private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
    private static final Splitter X_FORWARDED_FOR_SPLITTER = Splitter.on(",").omitEmptyStrings()
            .trimResults();
    private static final long MAX_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
    private static final long EXPIRE_AFTER_WRITE = 30;
    private final HttpHeaders propertiesResponseHeaders;
    private final HttpHeaders jsonResponseHeaders;
    private final ResponseEntity<String> NOT_FOUND_RESPONSE;
    private Cache<String, String> localCache;
    private final Multimap<String, String>
            watchedKeys2CacheKey = Multimaps.synchronizedSetMultimap(HashMultimap.create());
    private final Multimap<String, String>
            cacheKey2WatchedKeys = Multimaps.synchronizedSetMultimap(HashMultimap.create());
    private static final Gson gson = new Gson();

    @Autowired
    private ConfigController configController;

    @Autowired
    private NamespaceUtil namespaceUtil;

    @Autowired
    private WatchKeysUtil watchKeysUtil;

    @Autowired
    private GrayReleaseRulesHolder grayReleaseRulesHolder;

    public ConfigFileController() {
        localCache = CacheBuilder.newBuilder()
                .expireAfterWrite(EXPIRE_AFTER_WRITE, TimeUnit.MINUTES)
                .weigher(new Weigher<String, String>() {
                    @Override
                    public int weigh(String key, String value) {
                        return value == null ? 0 : value.length();
                    }
                })
                .maximumWeight(MAX_CACHE_SIZE)
                .removalListener(new RemovalListener<String, String>() {
                    @Override
                    public void onRemoval(RemovalNotification<String, String> notification) {
                        String cacheKey = notification.getKey();
                        logger.debug("removing cache key: {}", cacheKey);
                        if (!cacheKey2WatchedKeys.containsKey(cacheKey)) {
                            return;
                        }
                        //create a new list to avoid ConcurrentModificationException
                        List<String> watchedKeys = new ArrayList<>(cacheKey2WatchedKeys.get(cacheKey));
                        for (String watchedKey : watchedKeys) {
                            watchedKeys2CacheKey.remove(watchedKey, cacheKey);
                        }
                        cacheKey2WatchedKeys.removeAll(cacheKey);
                        logger.debug("removed cache key: {}", cacheKey);
                    }
                })
                .build();
        propertiesResponseHeaders = new HttpHeaders();
        propertiesResponseHeaders.add("Content-Type", "text/plain;charset=UTF-8");
        jsonResponseHeaders = new HttpHeaders();
        jsonResponseHeaders.add("Content-Type", "application/json;charset=UTF-8");
        NOT_FOUND_RESPONSE = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @RequestMapping(value = "/{appId}/{clusterName}/{namespace:.+}", method = RequestMethod.GET)
    public ResponseEntity<String> queryConfigAsProperties(@PathVariable String appId,
                                                          @PathVariable String clusterName,
                                                          @PathVariable String namespace,
                                                          @RequestParam(value = "dataCenter", required = false) String dataCenter,
                                                          @RequestParam(value = "ip", required = false) String clientIp,
                                                          HttpServletRequest request,
                                                          HttpServletResponse response)
            throws IOException {

        String result =
                queryConfig(ConfigFileOutputFormat.PROPERTIES, appId, clusterName, namespace, dataCenter,
                        clientIp, request, response);

        if (result == null) {
            return NOT_FOUND_RESPONSE;
        }

        return new ResponseEntity<>(result, propertiesResponseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/json/{appId}/{clusterName}/{namespace:.+}", method = RequestMethod.GET)
    public ResponseEntity<String> queryConfigAsJson(@PathVariable String appId,
                                                    @PathVariable String clusterName,
                                                    @PathVariable String namespace,
                                                    @RequestParam(value = "dataCenter", required = false) String dataCenter,
                                                    @RequestParam(value = "ip", required = false) String clientIp,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response) throws IOException {

        String result =
                queryConfig(ConfigFileOutputFormat.JSON, appId, clusterName, namespace, dataCenter,
                        clientIp, request, response);

        if (result == null) {
            return NOT_FOUND_RESPONSE;
        }

        return new ResponseEntity<>(result, jsonResponseHeaders, HttpStatus.OK);
    }

    String queryConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
                       String namespace, String dataCenter, String clientIp,
                       HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
        //strip out .properties suffix
        namespace = namespaceUtil.filterNamespaceName(namespace);

        if (Strings.isNullOrEmpty(clientIp)) {
            clientIp = tryToGetClientIp(request);
        }

        //1. check whether this client has gray release rules
        boolean hasGrayReleaseRule = grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp,
                namespace);

        String cacheKey = assembleCacheKey(outputFormat, appId, clusterName, namespace, dataCenter);

        //2. try to load gray release and return
        if (hasGrayReleaseRule) {
            return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
                    request, response);
        }

        //3. if not gray release, check weather cache exists, if exists, return
        String result = localCache.getIfPresent(cacheKey);

        //4. if not exists, load from ConfigController
        if (Strings.isNullOrEmpty(result)) {
            result = loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
                    request, response);

            if (result == null) {
                return null;
            }
            //5. Double check if this client needs to load gray release, if yes, load from db again
            //This step is mainly to avoid cache pollution
            if (grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp, namespace)) {
                return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
                        request, response);
            }

            localCache.put(cacheKey, result);
            logger.debug("adding cache for key: {}", cacheKey);

            Set<String> watchedKeys =
                    watchKeysUtil.assembleAllWatchKeys(appId, clusterName, namespace, dataCenter);

            for (String watchedKey : watchedKeys) {
                watchedKeys2CacheKey.put(watchedKey, cacheKey);
            }

            cacheKey2WatchedKeys.putAll(cacheKey, watchedKeys);
            logger.debug("added cache for key: {}", cacheKey);
        } else {
        }

        return result;
    }

    private String loadConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
                              String namespace, String dataCenter, String clientIp,
                              HttpServletRequest request,
                              HttpServletResponse response) throws IOException {
        OmicronConfig apolloConfig = configController.queryConfig(appId, clusterName, namespace,
                dataCenter, "-1", clientIp, request, response);

        if (apolloConfig == null || apolloConfig.getConfigurations() == null) {
            return null;
        }

        String result = null;

        switch (outputFormat) {
            case PROPERTIES:
                Properties properties = new Properties();
                properties.putAll(apolloConfig.getConfigurations());
                result = PropertiesUtil.toString(properties);
                break;
            case JSON:
                result = gson.toJson(apolloConfig.getConfigurations());
                break;
        }

        return result;
    }

    String assembleCacheKey(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
                            String namespace,
                            String dataCenter) {
        List<String> keyParts =
                Lists.newArrayList(outputFormat.getValue(), appId, clusterName, namespace);
        if (!Strings.isNullOrEmpty(dataCenter)) {
            keyParts.add(dataCenter);
        }
        return STRING_JOINER.join(keyParts);
    }

    @Override
    public void handleMessage(ReleaseMessage message, String channel) {
        logger.info("message received - channel: {}, message: {}", channel, message);

        String content = message.getMessage();
        if (!Topics.OMICRON_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(content)) {
            return;
        }

        if (!watchedKeys2CacheKey.containsKey(content)) {
            return;
        }

        //create a new list to avoid ConcurrentModificationException
        List<String> cacheKeys = new ArrayList<>(watchedKeys2CacheKey.get(content));

        for (String cacheKey : cacheKeys) {
            logger.debug("invalidate cache key: {}", cacheKey);
            localCache.invalidate(cacheKey);
        }
    }

    enum ConfigFileOutputFormat {
        PROPERTIES("properties"), JSON("json");

        private String value;

        ConfigFileOutputFormat(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    private String tryToGetClientIp(HttpServletRequest request) {
        String forwardedFor = request.getHeader("X-FORWARDED-FOR");
        if (!Strings.isNullOrEmpty(forwardedFor)) {
            return X_FORWARDED_FOR_SPLITTER.splitToList(forwardedFor).get(0);
        }
        return request.getRemoteAddr();
    }
}


text:
package server

import (
	"fmt"
	"net/url"
	"path"
	"strings"

	"github.com/emicklei/go-restful"
	"k8s.io/klog"
)

// TranslatePath translate the naming between tenant and master cluster.
func TranslatePath(req *restful.Request, tenantName string) {
	podNamespace := req.PathParameter("podNamespace")
	path := req.Request.URL.Path
	if podNamespace != "" {
		// eg.   /containerLogs/{podNamespace}/{podID}/{containerName}
		//    to /containerLogs/{tenantName}-{podNamespace}/{podID}/{containerName}
		secondSlash := strings.IndexByte(path[1:], '/')
		path = path[:secondSlash+2] + tenantName + "-" + path[secondSlash+2:]
	}
	req.Request.URL.Path = path
}

// translateRawQuery translates the rawquery for super apiserver
func translateRawQuery(req *restful.Request, containerName string) {
	vals := req.Request.URL.Query()
	klog.V(5).Infof("the origin URL query values are: %v", vals)
	query := url.Values{}
	for k, v := range vals {
		switch k {
		case "command":
			for _, cmd := range v {
				query.Add("command", cmd)
			}
		case "input":
			if v[0] == "1" {
				query.Add("stdin", "true")
			}
			if v[0] == "0" {
				query.Add("stdin", "false")
			}
		case "output":
			if v[0] == "1" {
				query.Add("stdout", "true")
			}
			if v[0] == "0" {
				query.Add("stdout", "false")
			}
		case "error":
			if v[0] == "1" {
				query.Add("stderr", "true")
			}
			if v[0] == "0" {
				query.Add("stderr", "false")
			}
		case "tty":
			if v[0] == "1" {
				query.Add("tty", "true")
			}
			if v[0] == "0" {
				query.Add("stdout", "false")
			}
		case "tailLines", "insecureSkipTLSVerifyBackend", "limitBytes",
			"follow", "container", "previous", "sinceTime", "timestamps":
			// for log options
			klog.V(5).Infof("the parameter %s is %s", k, v[0])
			query.Add(k, v[0])
		default:
			klog.Errorf("unknown rawquery: %s", k)
		}
	}
	if containerName != "" {
		query.Add("container", containerName)
	}
	klog.V(5).Infof("the new URL query is: %v", query)
	req.Request.URL.RawQuery = query.Encode()
}

// TranslatePathForSuper translates the URL path to kubelet to super apiserver
func TranslatePathForSuper(req *restful.Request, tenantName string) error {
	klog.V(5).Infof("will translate the URL %s for super apiserver", req.Request.URL)
	action := strings.Split(req.Request.URL.Path[1:], "/")[0]
	var apiserverPath string
	// req.PathParameter inclouding containerName, podID, podNamespace
	pathParas := req.PathParameters()
	podNamespace := pathParas["podNamespace"]
	podID := pathParas["podID"]
	containerName := pathParas["containerName"]
	commonPath := fmt.Sprintf("/api/v1/namespaces/%s-%s/pods/%s", tenantName, podNamespace, podID)

	switch action {
	case "containerLogs":
		// eg. 	/containerLogs/{podNamespace}/{podID}/{containerName}
		// to   /api/v1/namespaces/{tenantName}-{podNamespace}/pods/{podID}/log
		apiserverPath = path.Join(commonPath, "log")
		translateRawQuery(req, containerName)
	case "exec":
		// eg. /exec/{podNamespace}/podID/{containerName}
		// to  /api/v1/namespaces/{tenantName}-{podNamespace}/pods/{podID}/exec
		apiserverPath = path.Join(commonPath, "exec")
		translateRawQuery(req, containerName)
	case "attach":
		apiserverPath = path.Join(commonPath, "attach")
		translateRawQuery(req, containerName)
	case "portForward":
		apiserverPath = path.Join(commonPath, "portForward")
		translateRawQuery(req, "")
	default:
		return fmt.Errorf("unsupport action %s", action)
	}
	req.Request.URL.Path = apiserverPath
	return nil
}


text:
function setuptaxonomy()
    #set up taxonomy example
    #observations
    w_strings = ["Laptop","Monitor","Gamepad", #COMPUTERS
                 "Coffee machine","Vacuum cleaner","Electric toothbrush", #small APPLIANCES
                 "Grapes","Strawberries","Limes", #FRUIT
                 "Pancake mix","Baking soda","Baker's yeast","Muffin cups", #BAKING
                ]

    num_obs = size(w_strings,1)
    w_vec = collect(1:num_obs)

    #actions
    a_strings = ["Laptop sleeve","Monitor cable","Video game",
                 "Coffee","Vacuum cleaner bags","Brush heads",
                 "Cheese","Cream","Cane sugar",
                 "Maple syrup","Vinegar","Flour","Chocolate chips",
                 "COMPUTERS","APPLIANCES","FRUIT","BAKING","Electronics","Food"]
    num_acts = size(a_strings,1)
    a_vec = collect(1:num_acts)

    #set up uniform p(w)
    p_w = ones(num_obs)/num_obs

    #define utility function
    #(everything is hardcoded here, which is a bit hacky but will do the job)
    #the function expects integer indices
    function U(a::Integer,w::Integer)
        u_correct_w = 3;
        u_correct_category = 2.2;
        u_correct_supercategory = 1.6;

        #correct item
        if a<14 && a==w
            return u_correct_w
        end

        #flour is also fine for o=muffin cups
        if w==13 && a==12
            return u_correct_w
        end

        #For pancake mix both FRUIT and BAKING is fine
        if w==10 && a==16
            return u_correct_category
        end

        #extra if-clause is required for muffin cups
        if w==13 && a==17
            return u_correct_category
        end

        #correct category
        if a<18
            cat = ceil(w/3)
            if (a-13) == cat
                return u_correct_category
            end
        end

        #correct supercategory
        supcat = ceil(w/6)
        if (a-17) == supcat
            return u_correct_supercategory
        end

        #separate case for a==19
        if a==19 && w==13
           return u_correct_supercategory
        end

        #incorrect action
        return 0

    end

    return w_vec, w_strings, a_vec, a_strings, p_w, U
end

function setuptaxonomy_animals_plants()
    #set up taxonomy example
    #observations
    w_strings = ["Persian","Siamese","British Shorthair", #CATS
                 "German Shepherd","Rottweiler","Dachshund", #DOGS
                 "Oak","Birch","Pine", #TREES
                 "Rose","Dandelion","Sunflower", #FLOWERS
                 "Hibiscus" #Tree and flower (to break symmetry)
                ]

    num_obs = size(w_strings,1)
    w_vec = collect(1:num_obs)

    #actions are observations + categories + supercategories
    a_strings = [w_strings; "CAT";"DOG";"TREE";"FLOWER";"Animal";"Plant"]
    num_acts = size(a_strings,1)
    a_vec = collect(1:num_acts)

    #set up uniform p(w)
    p_w = ones(num_obs)/num_obs

    #define utility function
    #(everything is hardcoded here, which is a bit hacky but will do the job)
    function U(a,w)
        u_correct_w = 3;
        u_correct_category = 2.2;
        u_correct_supercategory = 1.6;

        #correct observation
        if w==a
            return u_correct_w
        end

        #correct category
        if w < 13
            cat = ceil(w/3)
            if (a-13) == cat
                return u_correct_category
            end
        end

        if w == 13  #hibiscus case
            if (a==16 || a==17)
                return u_correct_category
            end
        end

        #correct supercategory
        supcat = ceil(w/6)
        if (a-17) == supcat
            return u_correct_supercategory
        end

        if w == 13 #hibiscus case
            if a==19
                return u_correct_supercategory
            end
        end

        #incorrect action
        return 0

    end

    return w_vec, w_strings, a_vec, a_strings, p_w, U
end