text:
<?php

namespace JCSGYK\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use JMS\SecurityExtraBundle\Annotation\Secure;

use JCSGYK\AdminBundle\Entity\Stat;
use JCSGYK\AdminBundle\Entity\UserRepository;
use JCSGYK\AdminBundle\Entity\Client;
use JCSGYK\AdminBundle\Entity\Invoice;
use JCSGYK\AdminBundle\Entity\StatFile;
use JCSGYK\AdminBundle\Services\DataStore;
use JCSGYK\AdminBundle\Entity\HomeHelp;
use JCSGYK\AdminBundle\Entity\Relation;

class ReportsController extends Controller
{
    private $reports = [];

    /** @var DataStore */
    private $ds;

    /**
    * @Secure(roles="ROLE_USER")
    */
    public function indexAction($report = null)
    {
        $this->ds = $this->container->get('jcs.ds');

        // check if user has access to the selected report
        $this->checkRole($report);

        $result  = null;
        $request = $this->getRequest();

        // get the form for the selected report
        $form = $this->getReportForm($report);

        // render and download reports
        if ($request->isMethod('POST')) {
            $form->bind($request);
            $download = $request->request->get('download', false);

            $result = $this->getReport($report, $form->getData(), $download);

            if ($download) {
                return $result;
            }
        }

        return $this->render('JCSGYKAdminBundle:Reports:index.html.twig', [
            'menu'   => $this->getMenu(),
            'report' => $report,
            'result' => $result,
            'form'   => $form ? $form->createView() : null,
        ]);
    }

    /**
     * Checks the user role for the selected report
     *
     * @param string $report
     * @return boolean true on success
     * @throws AccessDeniedHttpException on failure
     */
    private function checkRole($report)
    {
        // no report was selected
        if (is_null($report)) {
            return true;
        }

        $granted = false;

        $menu = $this->getMenu();
        foreach ($menu as $m2) {
            foreach ($m2 as $item) {
                if ($item['slug'] == $report) {
                    $granted = true;
                    break(2);
                }
            }
        }

        if (!$granted) {
            throw new AccessDeniedHttpException();
        }

        return true;
    }

    /**
     * Produces the various forms for the reports
     *
     * @param string $report
     * @return Symfony\Component\Form\Form
     */
    private function getReportForm($report)
    {
        if (is_null($report)) {
            return false;
        }

        $sec              = $this->container->get('security.context');
        $client_type_list = $this->ds->getClientTypes();

        /** @var Formbuilder $form_builder */
        $form_builder = $this->createFormBuilder();
        //$form_builder->setData([]);

        if (in_array($report, ['clients', 'catering_clients', 'homehelp_clients', 'clubvisit_clients'])) {
            $this->container->get('jcs.reports.clients')->getForm($form_builder, $report);
        }
        if (in_array($report, ['catering_summary_detailed'])) {
            $this->container->get('jcs.reports.catering')->getForm($form_builder, $report);
        }
        elseif ('casecounts' == $report) {
            // client types (if relevant)
            if (count($client_type_list) > 1) {
                $this->getClientTypeSelect($form_builder, $client_type_list);
            }
            // admins can select the users of this company
            if ($sec->isGranted('ROLE_ADMIN')) {
                $this->getCaseAdminSelect($form_builder, false, 'mind');
            }
        }
        elseif ('catering_orders' == $report) {
            // weeks
            $this->getCateringWeeks($form_builder);
        }
        elseif (in_array($report, ['catering_cashbook', 'homehelp_cashbook'])) {
            // day
            $this->getDayInput($form_builder, false, 'Nap');
            // months
            $this->getInvoiceMonths($form_builder, false, 'Hónap');

            if ('homehelp_cashbook' == $report) {
                $form_builder->add('club', 'hidden', [
                    'data' => '1'
                ]);
            }
        }
        elseif (in_array($report, ['catering_summary', 'catering_datacheck'])) {
            // months
            $this->getInvoiceMonths($form_builder);
        }
        elseif (in_array($report, ['homehelp_summary', 'homehelp_visits', 'homehelp_hours', 'clubvisit_days'])) {
            // months
            $this->getHomeHelpInvoiceMonths($form_builder);
        }
        elseif (in_array($report, ['catering_stats', 'homehelp_stats', 'clubvisit_stats'])) {
            // stat months
            $this->getStatMonths($form_builder, $report);

            if ('homehelp_stats' == $report) {
                $form_builder->add('club', 'hidden', [
                    'data' => '1'
                ]);
            }
        }
        elseif ('ksh' == $report) {
            $this->container->get('jcs.reports.ksh')->getForm($form_builder);
        }
        elseif ('ksh_gyk' == $report) {
            $this->container->get('jcs.reports.ksh_gyk')->getForm($form_builder);
        }

        // club select for all catering reports
        if (in_array($report, ['catering_orders', 'catering_cashbook', 'catering_summary', 'catering_datacheck', 'catering_stats', 'clubvisit_stats'])) {
            $this->getClubSelect($form_builder);
        }
        elseif (in_array($report, ['homehelp_clients_old'])) {
            $this->getSocialWorkerSelect($form_builder, true, 'Mindenki');
        }

        // show only debts for catering summary
        if (in_array($report, ['catering_summary', 'catering_datacheck'])) {
            $form_builder->add('only_debts', 'checkbox', [
                'label'       => 'Csak tartozások',
                'required'    => false,
                'label_attr'  => ['style' => 'float:right;margin:2px 0 0 2px;'],
            ]);
        }

        // ClubVisit Days
        if (in_array($report, ['clubvisit_days'])) {
            $this->container->get('jcs.reports.clubvisit')->getForm($report, $form_builder);
        }

        return $form_builder->getForm();
    }

    private function getClientTypeSelect(&$form_builder, $client_type_list)
    {
        $form_builder->add('client_type', 'choice', [
            'label'       => 'Ügyfél típus',
            'choices'     => $client_type_list,
            'required'    => false,
            'empty_value' => 'összes',
        ]);
    }

    private function getCaseAdminSelect(&$form_builder, $required = true, $empty_value = '')
    {
        $form_builder->add('case_admin', 'entity', [
            'label'       => 'Esetgazda',
            'class'       => 'JCSGYKAdminBundle:User',
            'choices'     => $this->ds->getCaseAdmins(null, false),
            'required'    => $required,
            'empty_value' => $empty_value,
        ]);
    }

    // list the months when we have invoice data
    private function getInvoiceMonths(&$form_builder, $required = true, $label = 'Dátum')
    {
        $company_id = $this->ds->getCompanyId();

        $form_builder->add('month', 'choice', [
            'label'    => $label,
            'choices'  => $this->container->get('jcs.invoice')->getMonths($company_id),
            'required' => $required,
        ]);
    }

    // list the months when we have invoice data
    private function getHomeHelpInvoiceMonths(&$form_builder, $required = true, $label = 'Dátum')
    {
        $company_id = $this->ds->getCompanyId();

        $form_builder->add('month', 'choice', [
            'label'    => $label,
            'choices'  => $this->container->get('jcs.invoice')->getMonths($company_id, Invoice::HOMEHELP),
            'required' => $required,
        ]);
    }

    /**
     * Return the list of months when we have statistics data
     * @param FormBuilder $form_builder
     * @param $report
     * @param bool|type $required
     * @param type|string $label
     */
    private function getStatMonths(FormBuilder &$form_builder, $report, $required = true, $label = 'Dátum')
    {
        $company_id = $this->ds->getCompanyId();
        $em         = $this->container->get('doctrine')->getManager();
        $ae         = $this->container->get('jcs.twig.adminextension');

        $stat_type = 'catering_stats' == $report ? 401 : 402;

        $archs  = $em->getRepository('JCSGYKAdminBundle:StatArchive')->findBy(['companyId' => $company_id, 'type' => $stat_type], ['createdAt' => 'DESC'], 12);
        $months = [];
        foreach ($archs as $sa) {
            $months[$sa->getId()] = $ae->formatDate($sa->getStart(), 'ym');
        }

        $form_builder->add('stat_archive', 'choice', [
            'label'    => $label,
            'choices'  => $months,
            'required' => $required,
        ]);
    }

    private function getCateringWeeks(&$form_builder)
    {
        $form_builder->add('week', 'choice', [
            'label'    => 'Hét',
            'choices'  => $this->getWeeks(),
            'data'     => (new \DateTime('this week'))->format('Y-m-d'),
            'required' => true,
        ]);
    }

    private function getDayInput(&$form_builder, $required = true, $label = 'Dátum')
    {
        $form_builder->add('day', 'date', [
            'label'    => $label,
            'widget'   => 'single_text',
            'attr'     => array('class' => 'datepicker', 'type' => 'text'),
            'required' => $required,
            'data'     => new \DateTime('today'),
        ]);
    }

    private function getWeeks()
    {
        $re       = [];
        $ae       = $this->container->get('jcs.twig.adminextension');
        $date     = new \DateTime('last week 0:0'); // 0h 0m 0s the first day of last week
        $one_week = new \DateInterval('P1W');

        for ($i = 0; $i < 6; $i++) {
            $end_of_week            = clone $date;
            $end_of_week->modify('+ 6 days');
            $re[$date->format('Y-m-d')] = sprintf('%s (%s - %s)', $ae->formatDate($date, 'week'), $ae->formatDate($date, 'md'), $ae->formatDate($end_of_week, 'md'));
            $date->add($one_week);
        }

        return $re;
    }

    private function getClubSelect(&$form_builder, $required = true, $empty_value = '')
    {
        $c = [
            'label'    => 'Klub',
            'class'    => 'JCSGYKAdminBundle:Club',
            'choices'  => $this->ds->getClubs(),
            'required' => $required,
        ];
        if (!empty($empty_value)) {
            $c['empty_value'] = $empty_value;
        }

        $form_builder->add('club', 'entity', $c);
    }

    private function getSocialWorkerSelect(&$form_builder, $required = true, $empty_value = '')
    {
        $c = [
            'label'    => 'Gondozó',
            'choices'  => $this->ds->getSocialWorkers(),
            'required' => $required,
        ];
        if (!empty($empty_value)) {
            $c['empty_value'] = $empty_value;
        }

        $form_builder->add('social_worker', 'choice', $c);
    }

    private function getReport($report, $form_data, $download)
    {
        if (in_array($report, ['clients', 'catering_clients', 'homehelp_clients', 'clubvisit_clients'])) {
            return $this->container->get('jcs.reports.clients')->run($form_data, $report, $download);
        }
        if (in_array($report, ['catering_summary_detailed'])) {
            return $this->container->get('jcs.reports.catering')->run($form_data, $report, $download);
        }
        elseif ('casecounts' == $report) {
            return $this->getCasecountsReport($form_data, $download);
        }
        elseif ('catering_orders' == $report) {
            return $this->getCateringOrderReport($form_data, $download);
        }
        elseif (in_array($report, ['catering_summary', 'catering_datacheck'])) {
            return $this->getCateringReport($form_data, $report, $download);
        }
        elseif (in_array($report, ['catering_stats', 'homehelp_stats', 'clubvisit_stats'])) {
            return $this->getStats($form_data, $download);
        }
        elseif (in_array($report, ['catering_cashbook', 'homehelp_cashbook'])) {
            return $this->getCateringCashBookReport($form_data, $download, $report);
        }
        elseif ('ksh' == $report) {
            return $this->container->get('jcs.reports.ksh')->run($form_data, $download);
        }
        elseif ('ksh_gyk' == $report) {
            return $this->container->get('jcs.reports.ksh_gyk')->run($form_data, $download);
        }
        elseif ('homehelp_clients_old' == $report) {
            return $this->getHomehelpClientsReport($form_data, $download);
        }
        elseif (in_array($report, ['homehelp_summary', 'homehelp_visits', 'homehelp_hours'])) {
            return $this->getHomehelpReport($form_data, $report, $download);
        }
        elseif (in_array($report, ['clubvisit_days'])) {
            return $this->container->get('jcs.reports.clubvisit')->run($report, $form_data, $download);
        }

        return false;
    }

    private function getMenu()
    {
        $sec = $this->container->get('security.context');
        $ds  = $this->container->get('jcs.ds');

        // role checks
        $family_help_on    = $ds->companyHas(Client::FH) && $sec->isGranted('ROLE_FAMILY_HELP');
        $child_welfare_on = $ds->companyHas(Client::CW) && $sec->isGranted('ROLE_CHILD_WELFARE');
        $catering_on      = $ds->companyHas(Client::CA) && $sec->isGranted('ROLE_CATERING');

        $menu = [];
        if ($family_help_on) {
            $menu['Családsegítő'] = [
                ['slug' => 'clients', 'label' => 'Ügyfelek'],
                ['slug' => 'casecounts', 'label' => 'Esetszámok'],
                ['slug' => 'ksh', 'label' => 'KSH statisztika'],
            ];
        }
        if ($child_welfare_on) {
            $menu['Gyermekjólét'] = [
                ['slug' => 'clients', 'label' => 'Ügyfelek'],
                ['slug' => 'casecounts', 'label' => 'Esetszámok'],
                ['slug' => 'ksh_gyk', 'label' => 'KSH statisztika'],
            ];
        }
        if ($catering_on) {
            $menu['Étkeztetés'] = [
                ['slug' => 'catering_clients', 'label' => 'Ügyfelek'],
                ['slug' => 'catering_orders', 'label' => 'Heti ebédrendelések'],
                ['slug' => 'catering_cashbook', 'label' => 'Pénztárkönyv'],
                ['slug' => 'catering_summary', 'label' => 'Havi ebédösszesítő'],
                ['slug' => 'catering_summary_detailed', 'label' => 'Részletes ebédösszesítő'],
                ['slug' => 'catering_datacheck', 'label' => 'Adategyeztető'],
                ['slug' => 'catering_stats', 'label' => 'Étkeztetés statisztika'],
            ];
            $menu['Gondozás (Központ)'] = [
                ['slug' => 'homehelp_clients', 'label' => 'Gondozási ügyfelek'],
                ['slug' => 'homehelp_stats', 'label' => 'Gondozás statisztika'],
                ['slug' => 'homehelp_visits', 'label' => 'Gondozási napok'],
                ['slug' => 'homehelp_hours', 'label' => 'Gondozási órák'],
                ['slug' => 'homehelp_clients_old', 'label' => 'Gondozottak'],
                ['slug' => 'homehelp_summary', 'label' => 'Havi gondozás összesítő'],
                ['slug' => 'homehelp_cashbook', 'label' => 'Pénztárkönyv'],
            ];
            $menu['Látogatás (Klubok)'] = [
                ['slug' => 'clubvisit_clients', 'label' => 'Látogatási ügyfelek'],
                ['slug' => 'clubvisit_stats', 'label' => 'Látogatás statisztika'],
                ['slug' => 'clubvisit_days', 'label' => 'Látogatási napok'],
            ];
        }

        return $menu;
    }

    private function getCasecountsReport($form_data)
    {
        $form_fields = [
            'case_admin'  => null,
            'client_type' => null,
        ];
        // make sure we have all required fields
        $form_data   = array_merge($form_fields, $form_data);

        // check for user roles and set the params accordingly
        $em               = $this->getDoctrine();
        $sec              = $this->container->get('security.context');
        $ae               = $this->container->get('jcs.twig.adminextension');
        $client_type_list = $this->ds->getClientTypes();
        $client_type_keys = array_keys($client_type_list);
        $company_id       = $this->ds->getCompanyId();

        // non admins can only see their own clients
        if (!$sec->isGranted('ROLE_ADMIN')) {
            $form_data['case_admin'] = $sec->getToken()->getUser()->getId();
        }
        // make sure the client type is correct
        if (count($client_type_keys) < 2 && !in_array($form_data['client_type'], $client_type_keys)) {
            $form_data['client_type'] = reset($client_type_keys);
        }

        $counts = $em->getRepository('JCSGYKAdminBundle:Client')->getCaseCounts($company_id, $form_data['case_admin'], $form_data['client_type']);

        $data  = [
            'blocks' => [
                'casecount' => $counts,
            ]
        ];
        $template_file = __DIR__ . '/../Resources/public/reports/casecounts.xlsx';
        $output_name   = 'esetszam_kimutatas_' . date('Ymd') . '.xlsx';
        $send          = $this->container->get('jcs.docx')->makeReport($template_file, $data, $output_name);

        return $send;
    }

    private function getCateringOrderReport($form_data, $download)
    {
        $form_fields = [
            'week' => null,
            'club' => null,
        ];
        // make sure we have all required fields
        // 'club' => Club entity or null for all
        $form_data   = array_merge($form_fields, $form_data);

        // check for user roles and set the params accordingly
        $em         = $this->container->get('doctrine')->getManager();
        $sec        = $this->container->get('security.context');
        $ae         = $this->container->get('jcs.twig.adminextension');
        $company_id = $this->ds->getCompanyId();
        $weeks      = $this->getWeeks();

        // non admins not get all clubs
        if (!$sec->isGranted('ROLE_ADMIN') && empty($form_data['club'])) {
            throw new AccessDeniedHttpException();
        }
        // get the period
        if (!isset($weeks[$form_data['week']])) {
            throw new AccessDeniedHttpException();
        }

        $start_date = new \DateTime($form_data['week']);
        $end_date   = clone $start_date;
        $end_date   = $end_date->modify('+ 6 days');

        $menus = $this->ds->getGroup('lunch_types');

        $summary_data = [];
        // get only the first character from the menu names
        foreach ($menus as $m_id => $menu) {
            $new_name     = '';
            $name_parts   = explode(' ', $menu);
            $new_name    .= end($name_parts)[0];
            $menus[$m_id] = $new_name;

            // add the menu to the summary
            $summary_data[$m_id] = [
                'menu'  => $menu,
                1       => 0,
                2       => 0,
                3       => 0,
                4       => 0,
                5       => 0,
                6       => 0,
                7       => 0,
                'total' => 0,
            ];
        }
        // add totals
        $summary_data[] = [
            'menu'  => '',
            1       => '',
            2       => '',
            3       => '',
            4       => '',
            5       => '',
            6       => '',
            7       => '',
            'total' => '',
        ];
        $summary_data['sum1'] = [
            'menu'  => 'Összesen',
            1       => 0,
            2       => 0,
            3       => 0,
            4       => 0,
            5       => 0,
            6       => 0,
            7       => 0,
            'total' => '',
        ];
        $summary_data['sum2'] = [
            'menu'  => '',
            1       => '',
            2       => '',
            3       => '',
            4       => '',
            5       => 0,
            6       => '',
            7       => 0,
            'total' => 0,
        ];

        $sql = "SELECT o, c.id, c.title, c.lastname, c.firstname, c.socialSecurityNumber, c.zipCode, c.city, c.street, c.streetType, c.streetNumber, c.flatNumber"
                . " FROM JCSGYKAdminBundle:ClientOrder o LEFT JOIN o.client c LEFT JOIN c.catering a"
                . " WHERE o.companyId = :company_id AND o.date >= :start_date AND o.date <= :end_date";
        if (!empty($form_data['club'])) {
            $sql .= ' AND a.club = :club';
        }
        $sql .= " ORDER BY c.lastname, c.firstname, o.date";

        $q = $em->createQuery($sql)
                ->setParameter('company_id', $company_id)
                ->setParameter('start_date', $start_date->format('Y-m-d'))
                ->setParameter('end_date', $end_date->format('Y-m-d'));
        if (!empty($form_data['club'])) {
            $q->setParameter('club', $form_data['club']);
        }
        $res = $q->getResult();

        $report_data = [];
        foreach ($res as $rec) {
            // we skip the suspended days
            if ($rec[0]->getOrder()) {
                // create the user row
                if (empty($report_data[$rec['id']])) {
                    $addr = $ae->formatAddress('', '', '', $rec['street'], $rec['streetType'], $rec['streetNumber'], $rec['flatNumber']);
                    $ssn = $ae->formatSSN($rec['socialSecurityNumber'], ' ');
                    $report_data[$rec['id']] = [
                        'ssn'     => !empty($ssn) ? $ssn : '   -   ',
                        'name'    => $ae->formatName($rec['firstname'], $rec['lastname'], $rec['title']),
                        'address' => !empty($addr) ? $addr : ' ',
                        1         => '',
                        2         => '',
                        3         => '',
                        4         => '',
                        5         => '',
                        6         => '',
                        7         => '',
                    ];
                }
                $day_num = $rec[0]->getDate()->format('N');
                $o       = '';

                if ($rec[0]->getCancel()) {
                    $o = '-';
                }
                else {
                    $o = isset($menus[$rec[0]->getMenu()]) ? $menus[$rec[0]->getMenu()] : '?';
                    $summary_data[$rec[0]->getMenu()][$day_num] ++;
                    $summary_data[$rec[0]->getMenu()]['total'] ++;
                    $summary_data['sum1'][$day_num] ++;
                    if ($day_num < 6) {
                        $summary_data['sum2'][5] ++;
                    }
                    else {
                        $summary_data['sum2'][7] ++;
                    }
                    $summary_data['sum2']['total'] ++;
                }

                $report_data[$rec['id']][$day_num] = $o;
            }
        }

//        var_dump($report_data);
//        die;

        $data = [
            'ca.cim'           => sprintf('%s. %s. heti ebéd rendelések', $start_date->format('Y'), $start_date->format('W')),
            'ca.klub'          => empty($form_data['club']) ? '' : sprintf(' (%s)', $form_data['club']->getName()),
            'sp.datum'         => $ae->formatDate(new \DateTime('today')),
            'total.sum'        => $summary_data['sum2']['total'],
            'total.unit_price' => $ae->formatCurrency($this->ds->getMenuCost()),
            'total.amount'     => $ae->formatCurrency($this->ds->getMenuCost() * $summary_data['sum2']['total']),
            'blocks'           => [
                'catering' => $report_data,
                'summary'  => $summary_data,
            ]
        ];

        $template_file = __DIR__ . '/../Resources/public/reports/catering_orders.xlsx';
        $output_name   = $data['ca.cim'] . $data['ca.klub'] . '.xlsx';

        if ($download) {

            return $this->container->get('jcs.docx')->make($template_file, $data, $output_name);
        }
        else {

            return $this->container->get('templating')->render('JCSGYKAdminBundle:Reports:_orders.html.twig', ['data' => $data]);
        }
    }

    private function getCateringReport($form_data, $report, $download)
    {
        $form_fields = [
            'month' => null,
            'club'  => null,
            'only_debts' => false,
        ];
        // make sure we have all required fields
        // 'club' => Club entity or null for all
        $form_data   = array_merge($form_fields, $form_data);

        // check for user roles and set the params accordingly
        $sec        = $this->container->get('security.context');
        $ae         = $this->container->get('jcs.twig.adminextension');
        $company_id = $this->ds->getCompanyId();
        $months     = $this->container->get('jcs.invoice')->getMonths($company_id);

        // non admins not get all clubs
        if (!$sec->isGranted('ROLE_ADMIN') && empty($form_data['club'])) {
            throw new AccessDeniedHttpException();
        }
        // get the period
        if (!isset($months[$form_data['month']])) {
            throw new AccessDeniedHttpException();
        }

        $month = new \DateTime($form_data['month']);

        $report_data = $this->container->get('jcs.invoice')->getCateringReport($company_id, $month, $form_data['club'], $report, $form_data['only_debts']);

        if ('catering_datacheck' == $report) {
            $title = sprintf('%s havi adategyeztető', $ae->formatDate($month, 'ym'));
            $template_file = __DIR__ . '/../Resources/public/reports/catering_datacheck.xlsx';
            $twig_tpl = '_datacheck.html.twig';
        }
        else {
            $title = sprintf('%s havi ebéd összesítő', $ae->formatDate($month, 'ym'));
            $template_file = __DIR__ . '/../Resources/public/reports/catering_summary.xlsx';
            $twig_tpl = '_summary.html.twig';
        }

        $data = [
            'ca.cim'   => $title,
            'ca.klub'  => empty($form_data['club']) ? '' : sprintf(' (%s)', $form_data['club']->getName()),
            'sp.datum' => $ae->formatDate(new \DateTime('today')),
            'blocks'   => [
                'catering' => $report_data,
            ]
        ];

        $output_name   = $data['ca.cim'] . $data['ca.klub'] . '.xlsx';

        if ($download) {

            return $this->container->get('jcs.docx')->make($template_file, $data, $output_name);
        }
        else {

            return $this->container->get('templating')->render('JCSGYKAdminBundle:Reports:' . $twig_tpl, ['data' => $data]);
        }
    }

    private function getCateringCashBookReport($form_data, $download, $report)
    {
        $form_fields = [
            'day'   => null,
            'month' => null,
            'club'  => null,
        ];
        // make sure we have all required fields
        // 'club' => Club entity or null for all
        $form_data   = array_merge($form_fields, $form_data);

        // check for user roles and set the params accordingly
        $sec        = $this->container->get('security.context');
        $ae         = $this->container->get('jcs.twig.adminextension');
        $company_id = $this->ds->getCompanyId();
        $em         = $this->container->get('doctrine')->getManager();

        // non admins not get all clubs
        if (!$sec->isGranted('ROLE_ADMIN') && empty($form_data['club'])) {
            throw new AccessDeniedHttpException();
        }
        // get the period
        if (empty($form_data['day']) && empty($form_data['month'])) {
            throw new AccessDeniedHttpException();
        }

        $date = !empty($form_data['day']) ? $form_data['day']->format('Y-m-d') : $form_data['month'];

        // get the payments for this date
        $invoice_types = 'homehelp_cashbook' == $report ? [Invoice::HOMEHELP] : [Invoice::MONTHLY, Invoice::DAILY];

        $sql = "SELECT i, c, a, h FROM JCSGYKAdminBundle:Invoice i LEFT JOIN i.client c LEFT JOIN c.catering a LEFT JOIN c.homehelp h "
                . "WHERE i.companyId = :company_id AND i.payments LIKE :date AND i.invoicetype IN (:types) ";

        if (!empty($form_data['club'])) {
            $join_table = 'homehelp_cashbook' == $report ? 'h' : 'a';
            $sql .= " AND {$join_table}.club = :club ";
        }
        $sql .=  " ORDER BY c.lastname, c.firstname ";

        $q = $em->createQuery($sql)
            ->setParameter('company_id', $company_id)
            ->setParameter('date', "%$date%")
            ->setParameter('types', $invoice_types)
        ;
        if (!empty($form_data['club'])) {
            $q->setParameter('club', $form_data['club']);
        }
        $res = $q->getResult();

        $sums        = [
            'id'             => '',
            'name'           => 'ÖSSZESEN',
            'address'        => '',
            'month'        => '',
            'invoice_number' => '',
            'amount'         => 0,
        ];
        $report_data = [];
        foreach ($res as $invoice) {
            $client = $invoice->getClient();

            // process items
            $amount = 0;
            $payment_dates = [];

            foreach ($invoice->getPayments() as $payment) {
                // either the payment is on the exact day that we are looking for
                if ($date == $payment[0] ||
                        // or on that month, if only the month is given
                        (empty($form_data['day']) && $date == substr($payment[0], 0, 7))) {

                    $amount += $payment[1];

                    if (empty($payment_dates)) {
                        $payment_dates[] = substr($payment[0], 5);
                    }
                }
            }

            $data_row = [
                'id'             => $client->getCaseLabel(),
                'name'           => $ae->formatClientName($client),
                'address'        => sprintf('(%s)', $ae->formatClientAddress($client)),
                'month'          => !empty($form_data['day']) ? $this->ds->getMonth($invoice->getStartdate()->format('n')) : implode(', ', $payment_dates),
                'invoice_number' => 'SZ-' . $invoice->getId(),
                //'balance'       => $ae->formatCurrency2($catering->getBalance()),
                'amount'         => $ae->formatCurrency2($amount),
            ];

            $report_data[] = $data_row;

            $sums['amount']    += $amount;
        }

        // format the summary
        $sums['amount'] = $ae->formatCurrency2($sums['amount']);
        // add the summary to the end of the report
        $report_data[] = $sums;

        $title_date = !empty($form_data['day']) ? $ae->formatDate($form_data['day']) : $ae->formatDate(new \DateTime($form_data['month']), 'ym');
        $title_type = 'catering_cashbook' == $report ? 'EBÉD' : 'GONDOZÁS';
        $title = sprintf('%s Pénztárkönyv %s', $title_type, $title_date);
        $template_file = __DIR__ . '/../Resources/public/reports/catering_cashbook.xlsx';
        $twig_tpl = '_catering_cashbook.html.twig';

        if (empty($form_data['club']) || $form_data['club'] instanceof Club) {
            $club = $form_data['club'];
        } else {
            $club = $em->getRepository('JCSGYKAdminBundle:Club')->find($form_data['club']);
        }

        $data = [
            'ca.cim'   => $title,
            'ca.klub'  => empty($club) ? '' : sprintf(' (%s)', $club->getName()),
            'sp.datum' => $ae->formatDate(new \DateTime('today')),
            'blocks'   => [
                'catering' => $report_data,
            ]
        ];

        $output_name   = $data['ca.cim'] . $data['ca.klub'] . '.xlsx';

        if ($download) {
            return $this->container->get('jcs.docx')->make($template_file, $data, $output_name);
        }
        else {
            return $this->container->get('templating')->render('JCSGYKAdminBundle:Reports:' . $twig_tpl, ['data' => $data]);
        }
    }

    /**
     * Return the stats by either rendering a twig template, or sending a db stored file
     * @param $form_data
     * @param $download
     * @return Response
     */
    private function getStats($form_data, $download)
    {
        $form_fields = [
            'stat_archive' => null,
            'club'  => null,
        ];
        // make sure we have all required fields
        // 'club' => Club entity or null for all
        $form_data   = array_merge($form_fields, $form_data);

        // check for user roles and set the params accordingly
        $em         = $this->container->get('doctrine')->getManager();
        $sec        = $this->container->get('security.context');

        // non admins should not get all clubs
        if (!$sec->isGranted('ROLE_ADMIN') && empty($form_data['club'])) {
            throw new AccessDeniedHttpException();
        }
        // get the club record
        /** @var StatFile $sf */
        $sf = $em->getRepository('JCSGYKAdminBundle:StatFile')->findOneBy(['statArchive' => $form_data['stat_archive'], 'type' => $form_data['club']]);

        if (empty($sf)) {
            throw new BadRequestHttpException('Invalid Club Id');
        }

        $stat_type = $sf->getStatArchive()->getType();

        $data = $sf->getData();

        if (401 == $stat_type) {
            // catering
            $twig_tpl = '_catering_stats.html.twig';
        } elseif (402 == $stat_type) {
            // homehelp
            $club_id = $sf->getType();
            $club = $em->getRepository('JCSGYKAdminBundle:Club')->find($club_id);
            $club_type = $club->getHomehelptype();

            $twig_tpl = HomeHelp::HELP == $club_type ? '_homehelp_stats.html.twig' : '_clubvisit_stats.html.twig';
        } else {
            $twig_tpl = null;
        }

        $output_name   = $data['ca.cim'] . $data['ca.klub'] . '.xlsx';

        if ($download) {
            return $this->sendDownloadResponse($output_name, stream_get_contents($sf->getFile()), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        }
        else {
            return $this->container->get('templating')->render('JCSGYKAdminBundle:Reports:' . $twig_tpl, ['data' => $data]);
        }
    }

    /**
     * Sent download headers and the file
     * @param string $file_name
     * @param string $file_contents
     * @param string $content_type
     * @return Response
     */
    public function sendDownloadResponse($file_name, $file_contents, $content_type)
    {
        $response = new Response();

        $response->headers->set('Content-Type', $content_type);
        $response->headers->set('Content-Disposition', 'attachment;filename="' . $file_name . '"');

        $response->setContent($file_contents);

        return $response;
    }

    /**
     * Find a value in a range (from-to) and return it's key
     * @param mixed $val
     * @param array $range
     * @return int | false on failure
     */
    private function getRangeKey($val, $range)
    {
        foreach ($range as $k => $d) {
            if ($val >= $d[0] && $val <= $d[1]) {

                return $k;
            }
        }

        return false;
    }

    private function getHomehelpClientsReport($form_data, $download)
    {
        $form_fields = [
            'social_worker' => null,
        ];
        // make sure we have all required fields
        // 'club' => Club entity or null for all
        $form_data   = array_merge($form_fields, $form_data);

        $company_id = $this->ds->getCompanyId();
        $em         = $this->container->get('doctrine')->getManager();
        $ae         = $this->container->get('jcs.twig.adminextension');

        // Get the names of the social workers
        $sw = $this->ds->getSocialWorkers();

        // filter the sw list
        if (!empty($form_data['social_worker']) && isset($sw[$form_data['social_worker']])) {
            $sw = [
                $form_data['social_worker'] => $sw[$form_data['social_worker']]
            ];
        }

        $clients = [];
        foreach ($sw as $sw_id => $worker) {
            // find all the active homehelp clients
            $cli = $em->getRepository('JCSGYKAdminBundle:HomeHelp')->getClientsBySocialWorker($sw_id, $company_id);
            if (!empty($cli)) {
                $tmp = [
                    'sw' => $worker,
                    'cli' => [],
                ];
                // client rows
                foreach ($cli as $client) {
                    $doc_name = '';
                    $doc = $em->getRepository('JCSGYKAdminBundle:Client')->getRelationByType($client->getId(), Relation::DOCTOR);
                    if (!empty($doc)) {
                        $doc_name = $ae->formatClientName($doc->getParent());
                    }

                    $tmp['cli'][] = [
                        'nam' => $ae->formatClientName($client),
                        'adr' => sprintf('(%s)', $ae->formatClientAddress($client)),
                        'doc' => $doc_name,
                        'tel' => $client->getPhone() . ' ' . $client->getMobile(),
                    ];
                }
                $clients[] = $tmp;
                $clients[] = [
                    'sw' => ' ',
                    'cli' => [],
                ];
            }
        }

        $data = [
            'hh.cim'   => 'Gondozottak',
            'sp.datum' => $ae->formatDate(new \DateTime('today')),
            'blocks'   => [
                'clients' => $clients,
            ]
        ];

        $twig_tpl      = '_homehelp_clients_old.html.twig';
        $template_file = __DIR__ . '/../Resources/public/reports/homehelp_clients_old.xlsx';
        $sw_title = !empty($form_data['social_worker']) ? sprintf(' (%s)', $this->ds->get($form_data['social_worker'])) : '';

        $output_name   = $data['hh.cim'] . $sw_title . '.xlsx';

        if ($download) {
            return $this->container->get('jcs.docx')->make($template_file, $data, $output_name);
        }
        else {
            return $this->container->get('templating')->render('JCSGYKAdminBundle:Reports:' . $twig_tpl, ['data' => $data]);
        }
    }

    private function getHomehelpReport($form_data, $report, $download)
    {
        $form_fields = [
            'month' => null,
        ];
        // make sure we have all required fields
        $form_data   = array_merge($form_fields, $form_data);

        // check for user roles and set the params accordingly
        $sec        = $this->container->get('security.context');
        $ae         = $this->container->get('jcs.twig.adminextension');
        $company_id = $this->ds->getCompanyId();
        $months     = $this->container->get('jcs.invoice')->getMonths($company_id, Invoice::HOMEHELP);

        // non admins not get all clubs
        if (!$sec->isGranted('ROLE_ADMIN') && empty($form_data['club'])) {
            throw new AccessDeniedHttpException();
        }
        // get the period
        if (!isset($months[$form_data['month']])) {
            throw new AccessDeniedHttpException();
        }

        $month = new \DateTime($form_data['month']);

        if (in_array($report, ['clubvisit_days'])) {
            $report_data = $this->container->get('jcs.invoice')->getClubvisitReport($company_id, $month, $report);
        } else {
            $report_data = $this->container->get('jcs.invoice')->getHomehelpReport($company_id, $month, $report);
        }

        if ('homehelp_visits' == $report) {
            $title = sprintf('%s havi gondozási napok összesítése', $ae->formatDate($month, 'ym'));
            $template_file = __DIR__ . '/../Resources/public/reports/homehelp_visits.xlsx';
            $twig_tpl = '_homehelp_visits.html.twig';
        }
        elseif ('homehelp_hours' == $report) {
            $title = sprintf('%s havi gondozási órák összesítése', $ae->formatDate($month, 'ym'));
            $template_file = __DIR__ . '/../Resources/public/reports/homehelp_hours.xlsx';
            $twig_tpl = '_homehelp_hours.html.twig';
        }
        else {
            $title = sprintf('%s havi gondozás összesítő', $ae->formatDate($month, 'ym'));
            $template_file = __DIR__ . '/../Resources/public/reports/homehelp_summary.xlsx';
            $twig_tpl = '_homehelp_summary.html.twig';
        }

        $data = [
            'ca.cim'   => $title,
            'ca.klub'  => empty($form_data['club']) ? '' : sprintf(' (%s)', $form_data['club']->getName()),
            'sp.datum' => $ae->formatDate(new \DateTime('today')),
            'blocks'   => [
                'homehelp' => $report_data,
            ]
        ];
        if (in_array($report, ['homehelp_visits', 'homehelp_hours'])) {
            $data['blocks']['months_days'] = range(1, 31);
        }

        $output_name   = $data['ca.cim'] . $data['ca.klub'] . '.xlsx';

        if ($download) {

            return $this->container->get('jcs.docx')->make($template_file, $data, $output_name);
        }
        else {

            return $this->container->get('templating')->render('JCSGYKAdminBundle:Reports:' . $twig_tpl, ['data' => $data]);
        }
    }

}


text:
section .text
  extern _is_empty
  extern _token_wins
  extern _copy_board
  extern _is_empty_space
  extern _is_tie
  extern _other_token
  extern _zero_board
  extern _get_token
  extern _is_valid_space

redpajama_set_name: RedPajamaGithub


text:
<ion-toolbar primary>
  <ion-buttons start>
    <ion-icon name="content"></ion-icon>
  </ion-buttons>

  <ion-title><busstops></busstops></ion-title>
  <ion-title><departures></departures></ion-title>
  <ion-buttons end>
    <ion-icon name="search"></ion-icon>
  </ion-buttons>

</ion-toolbar>

<ion-content>

There is a header above me!

</ion-content>


text:
using Carrotware.CMS.Core;
using Carrotware.CMS.UI.Controls;
using System;
using System.Collections.Generic;

namespace Carrotware.CMS.UI.Admin.c3_admin {

	public partial class ucCommentIndex : AdminBaseUserControl {
		private ContentPageType.PageType pageType = ContentPageType.PageType.BlogEntry;
		public Guid guidRootContentID = Guid.Empty;

		public string LinkingPage { get; set; }

		protected void Page_Load(object sender, EventArgs e) {
			if (!String.IsNullOrEmpty(Request.QueryString["type"])) {
				pageType = ContentPageType.GetTypeByName(Request.QueryString["type"].ToString());
			}

			if (!IsPostBack) {
				ddlSize.SelectedValue = pagedDataGrid.PageSize.ToString();

				GeneralUtilities.BindOptionalYesNoList(ddlActive);
				GeneralUtilities.BindOptionalYesNoList(ddlSpam);
			}

			guidRootContentID = GetGuidIDFromQuery();

			BindData();
		}

		protected void btnApply_Click(object sender, EventArgs e) {
		}

		protected void BindData() {
			int iRecCount = -1;

			bool? active = GeneralUtilities.GetNullableBoolValue(ddlActive);
			bool? spam = GeneralUtilities.GetNullableBoolValue(ddlSpam);
			pagedDataGrid.PageSize = int.Parse(ddlSize.SelectedValue);

			if (guidRootContentID == Guid.Empty) {
				iRecCount = PostComment.GetCommentCountBySiteAndType(SiteData.CurrentSiteID, pageType, active, spam);
			} else {
				iRecCount = PostComment.GetCommentCountByContent(guidRootContentID, active, spam);
			}

			lblPages.Text = String.Format(" {0} ", iRecCount);

			pagedDataGrid.BuildSorting();

			pagedDataGrid.TotalRecords = iRecCount;
			string sSort = pagedDataGrid.SortingBy;
			int iPgNbr = pagedDataGrid.PageNumber - 1;
			int iPageSize = pagedDataGrid.PageSize;

			List<PostComment> lstComments = new List<PostComment>();

			if (guidRootContentID == Guid.Empty) {
				lstComments = PostComment.GetCommentsBySitePageNumber(SiteData.CurrentSiteID, iPgNbr, iPageSize, sSort, pageType, active, spam);
			} else {
				lstComments = PostComment.GetCommentsByContentPageNumber(guidRootContentID, iPgNbr, iPageSize, sSort, active, spam);
			}

			GeneralUtilities.BindDataBoundControl(pagedDataGrid, lstComments);
		}
	}
}


text:
package attached

import (
	"errors"
	"fmt"
	"strings"
	"syscall"

	"github.com/cam72cam/delve/proctl"
)

func Attach(pid int) (*Process, error) {
	dbp, err := proctl.Attach(pid)
	if err != nil {
		return nil, err
	}
	return &Process{dbp: dbp}, nil
}

func Launch(cmd []string) (*Process, error) {
	dbp, err := proctl.Launch(cmd)
	if err != nil {
		return nil, err
	}
	return &Process{dbp: dbp}, nil
}

type Process struct {
	dbp *proctl.DebuggedProcess
}

func (p *Process) PID() int {
	return p.dbp.Pid
}

func (p *Process) Kill() error {
	return p.dbp.Process.Kill()
}
func (p *Process) CurrentThreadPoints() (map[int]Point, error) {
	pts := make(map[int]Point)
	for i, t := range p.dbp.Threads {
		pc, err := t.CurrentPC()
		if err != nil && pc != 0 {
			return nil, err
		}
		pt := Point{Addr: pc}
		pt.fromAddr(p)
		if strings.Contains(pt.File, "pkg/runtime") {
			//	continue
		}
		pts[i] = pt
	}
	return pts, nil
}

func (p *Process) Funcs() []string {
	res := make([]string, 0)
	for _, f := range p.dbp.GoSymTable.Funcs {
		res = append(res, f.Name)
	}
	return res
}
func (p *Process) HasFunc(name string) bool {
	for _, f := range p.dbp.GoSymTable.Funcs {
		if f.Name == name {
			return true
		}
	}
	return false
}

func (p *Process) BreakPoints() map[uint64]Point {
	res := make(map[uint64]Point)
	for addr, _ := range p.dbp.BreakPoints {
		pt := Point{Addr: addr}
		pt.fromAddr(p)
		res[addr] = pt
	}

	return res
}

func (p *Process) Clear(pt Point) (Point, error) {
	if pt.InFile() {
		if err := pt.fromFile(p); err != nil {
			return Point{}, err
		}
	}
	_, err := p.dbp.Clear(pt.Addr)
	return pt, err
}

func (p *Process) Break(pt Point) (Point, error) {
	if pt.InFile() {
		if err := pt.fromFile(p); err != nil {
			return Point{}, err
		}
	} else if pt.Func != "" {
		if err := pt.fromFunc(p); err != nil {
			return Point{}, err
		}
	}
	_, err := p.dbp.Break(uintptr(pt.Addr))
	return pt, err
}

type Point struct {
	Func string
	File string
	Line int
	Addr uint64
}

func (pt *Point) String() string {
	return fmt.Sprintf("0x%x %s (%s:%d)", pt.Addr, pt.Func, pt.File, pt.Line)
}

var ErrAddrNotFound = errors.New("Error Address not found!")
var ErrFuncNotFound = errors.New("Error Func not found!")

func (pt *Point) fromAddr(p *Process) error {
	f, l, fn := p.dbp.GoSymTable.PCToLine(pt.Addr)
	if fn != nil {
		pt.File = f
		pt.Line = l
		pt.Func = fn.Name
		return nil
	}
	return ErrAddrNotFound
}

func (pt *Point) fromFunc(p *Process) error {
	fn := p.dbp.GoSymTable.LookupFunc(pt.Func)
	if fn != nil {
		pt.Addr = fn.Entry
		return pt.fromAddr(p)
	}
	return ErrFuncNotFound
}

func (pt *Point) fromFile(p *Process) error {
	pc, fn, err := p.dbp.GoSymTable.LineToPC(pt.File, pt.Line)
	if err != nil {
		return err
	}
	pt.Addr = pc
	pt.Func = fn.Name
	return nil
}

func (pos Point) InFile() bool {
	return pos.File != ""
}

func (p *Process) CurrentPoint() (pt Point, err error) {
	regs, err := p.dbp.Registers()
	if err != nil {
		return pt, err
	}
	pt = Point{Addr: regs.PC()}
	return pt, pt.fromAddr(p)
}

func (p *Process) Continue() error {
	return p.dbp.Continue()
}

func (p *Process) StepAll() error {
	for _, t := range p.dbp.Threads {
		if err := t.Step(); err != nil {
			return err
		}
	}
	return nil
}
func (p *Process) StepCurrent() error {
	return p.dbp.CurrentThread.Step()
}
func (p *Process) Step(id int) error {
	if t, ok := p.dbp.Threads[id]; ok {
		return t.Step()
	}
	return fmt.Errorf("%d is not a thread", id)
}
func (p *Process) NextAll() error {
	for _, t := range p.dbp.Threads {
		if err := t.Next(); err != nil {
			if _, ok := err.(proctl.TimeoutError); !ok && err != syscall.ESRCH {
				return err
			}
		}
	}
	return nil
}
func (p *Process) NextCurrent() error {
	return p.dbp.CurrentThread.Next()
}
func (p *Process) Next(id int) error {
	if t, ok := p.dbp.Threads[id]; ok {
		return t.Next()
	}
	return fmt.Errorf("%d is not a thread", id)
}


text:
import django
from django.db import models
from django.forms import Textarea

if django.VERSION < (1, 7):
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ["^wagtail\.wagtailcore\.fields\.RichTextField"])

from wagtail.wagtailcore.rich_text import DbWhitelister, expand_db_html

class RichTextArea(Textarea):
    def get_panel(self):
        from wagtail.wagtailadmin.edit_handlers import RichTextFieldPanel
        return RichTextFieldPanel

    def render(self, name, value, attrs=None):
        if value is None:
            translated_value = None
        else:
            translated_value = expand_db_html(value, for_editor=True)
        return super(RichTextArea, self).render(name, translated_value, attrs)

    def value_from_datadict(self, data, files, name):
        original_value = super(RichTextArea, self).value_from_datadict(data, files, name)
        if original_value is None:
            return None
        return DbWhitelister.clean(original_value)

class RichTextField(models.TextField):
    def formfield(self, **kwargs):
        defaults = {'widget': RichTextArea}
        defaults.update(kwargs)
        return super(RichTextField, self).formfield(**defaults)


text:
"""Blocking and non-blocking HTTP client interfaces.

This module defines a common interface shared by two implementations,
`simple_httpclient` and `curl_httpclient`.  Applications may either
instantiate their chosen implementation class directly or use the
`AsyncHTTPClient` class from this module, which selects an implementation
that can be overridden with the `AsyncHTTPClient.configure` method.

The default implementation is `simple_httpclient`, and this is expected
to be suitable for most users' needs.  However, some applications may wish
to switch to `curl_httpclient` for reasons such as the following:

* `curl_httpclient` has some features not found in `simple_httpclient`,
  including support for HTTP proxies and the ability to use a specified
  network interface.

* `curl_httpclient` is more likely to be compatible with sites that are
  not-quite-compliant with the HTTP spec, or sites that use little-exercised
  features of HTTP.

* `simple_httpclient` only supports SSL on Python 2.6 and above.

* `curl_httpclient` is faster

* `curl_httpclient` was the default prior to Tornado 2.0.

Note that if you are using `curl_httpclient`, it is highly recommended that
you use a recent version of ``libcurl`` and ``pycurl``.  Currently the minimum
supported version is 7.18.2, and the recommended version is 7.21.1 or newer.
"""

import calendar
import email.utils
import http.client
import time
import weakref

from tornado.escape import utf8
from tornado import httputil
from tornado.ioloop import IOLoop
from tornado.util import import_object, bytes_type

class HTTPClient(object):
    """A blocking HTTP client.

    This interface is provided for convenience and testing; most applications
    that are running an IOLoop will want to use `AsyncHTTPClient` instead.
    Typical usage looks like this::

        http_client = httpclient.HTTPClient()
        try:
            response = http_client.fetch("http://www.google.com/")
            print response.body
        except httpclient.HTTPError, e:
            print "Error:", e
    """
    def __init__(self, async_client_class=None):
        self._io_loop = IOLoop()
        if async_client_class is None:
            async_client_class = AsyncHTTPClient
        self._async_client = async_client_class(self._io_loop)
        self._response = None
        self._closed = False

    def __del__(self):
        self.close()

    def close(self):
        """Closes the HTTPClient, freeing any resources used."""
        if not self._closed:
            self._async_client.close()
            self._io_loop.close()
            self._closed = True

    def fetch(self, request, **kwargs):
        """Executes a request, returning an `HTTPResponse`.

        The request may be either a string URL or an `HTTPRequest` object.
        If it is a string, we construct an `HTTPRequest` using any additional
        kwargs: ``HTTPRequest(request, **kwargs)``

        If an error occurs during the fetch, we raise an `HTTPError`.
        """
        def callback(response):
            self._response = response
            self._io_loop.stop()
        self._async_client.fetch(request, callback, **kwargs)
        self._io_loop.start()
        response = self._response
        self._response = None
        response.rethrow()
        return response

class AsyncHTTPClient(object):
    """An non-blocking HTTP client.

    Example usage::

        import ioloop

        def handle_request(response):
            if response.error:
                print "Error:", response.error
            else:
                print response.body
            ioloop.IOLoop.instance().stop()

        http_client = httpclient.AsyncHTTPClient()
        http_client.fetch("http://www.google.com/", handle_request)
        ioloop.IOLoop.instance().start()

    The constructor for this class is magic in several respects:  It actually
    creates an instance of an implementation-specific subclass, and instances
    are reused as a kind of pseudo-singleton (one per IOLoop).  The keyword
    argument force_instance=True can be used to suppress this singleton
    behavior.  Constructor arguments other than io_loop and force_instance
    are deprecated.  The implementation subclass as well as arguments to
    its constructor can be set with the static method configure()
    """
    _impl_class = None
    _impl_kwargs = None

    @classmethod
    def _async_clients(cls):
        assert cls is not AsyncHTTPClient, "should only be called on subclasses"
        if not hasattr(cls, '_async_client_dict'):
            cls._async_client_dict = weakref.WeakKeyDictionary()
        return cls._async_client_dict

    def __new__(cls, io_loop=None, max_clients=10, force_instance=False,
                **kwargs):
        io_loop = io_loop or IOLoop.instance()
        if cls is AsyncHTTPClient:
            if cls._impl_class is None:
                from tornado.simple_httpclient import SimpleAsyncHTTPClient
                AsyncHTTPClient._impl_class = SimpleAsyncHTTPClient
            impl = AsyncHTTPClient._impl_class
        else:
            impl = cls
        if io_loop in impl._async_clients() and not force_instance:
            return impl._async_clients()[io_loop]
        else:
            instance = super(AsyncHTTPClient, cls).__new__(impl)
            args = {}
            if cls._impl_kwargs:
                args.update(cls._impl_kwargs)
            args.update(kwargs)
            instance.initialize(io_loop, max_clients, **args)
            if not force_instance:
                impl._async_clients()[io_loop] = instance
            return instance

    def close(self):
        """Destroys this http client, freeing any file descriptors used.
        Not needed in normal use, but may be helpful in unittests that
        create and destroy http clients.  No other methods may be called
        on the AsyncHTTPClient after close().
        """
        if self._async_clients().get(self.io_loop) is self:
            del self._async_clients()[self.io_loop]

    def fetch(self, request, callback, **kwargs):
        """Executes a request, calling callback with an `HTTPResponse`.

        The request may be either a string URL or an `HTTPRequest` object.
        If it is a string, we construct an `HTTPRequest` using any additional
        kwargs: ``HTTPRequest(request, **kwargs)``

        If an error occurs during the fetch, the HTTPResponse given to the
        callback has a non-None error attribute that contains the exception
        encountered during the request. You can call response.rethrow() to
        throw the exception (if any) in the callback.
        """
        raise NotImplementedError()

    @staticmethod
    def configure(impl, **kwargs):
        """Configures the AsyncHTTPClient subclass to use.

        AsyncHTTPClient() actually creates an instance of a subclass.
        This method may be called with either a class object or the
        fully-qualified name of such a class (or None to use the default,
        SimpleAsyncHTTPClient)

        If additional keyword arguments are given, they will be passed
        to the constructor of each subclass instance created.  The
        keyword argument max_clients determines the maximum number of
        simultaneous fetch() operations that can execute in parallel
        on each IOLoop.  Additional arguments may be supported depending
        on the implementation class in use.

        Example::

           AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
        """
        if isinstance(impl, (str, bytes_type)):
            impl = import_object(impl)
        if impl is not None and not issubclass(impl, AsyncHTTPClient):
            raise ValueError("Invalid AsyncHTTPClient implementation")
        AsyncHTTPClient._impl_class = impl
        AsyncHTTPClient._impl_kwargs = kwargs

class HTTPRequest(object):
    """HTTP client request object."""
    def __init__(self, url, method="GET", headers=None, body=None,
                 auth_username=None, auth_password=None,
                 connect_timeout=20.0, request_timeout=20.0,
                 if_modified_since=None, follow_redirects=True,
                 max_redirects=5, user_agent=None, use_gzip=True,
                 network_interface=None, streaming_callback=None,
                 header_callback=None, prepare_curl_callback=None,
                 proxy_host=None, proxy_port=None, proxy_username=None,
                 proxy_password='', allow_nonstandard_methods=False,
                 validate_cert=True, ca_certs=None,
                 allow_ipv6=None,
                 client_key=None, client_cert=None):
        """Creates an `HTTPRequest`.

        All parameters except `url` are optional.

        :arg string url: URL to fetch
        :arg string method: HTTP method, e.g. "GET" or "POST"
        :arg headers: Additional HTTP headers to pass on the request
        :type headers: `~tornado.httputil.HTTPHeaders` or `dict`
        :arg string auth_username: Username for HTTP "Basic" authentication
        :arg string auth_password: Password for HTTP "Basic" authentication
        :arg float connect_timeout: Timeout for initial connection in seconds
        :arg float request_timeout: Timeout for entire request in seconds
        :arg datetime if_modified_since: Timestamp for ``If-Modified-Since``
           header
        :arg bool follow_redirects: Should redirects be followed automatically
           or return the 3xx response?
        :arg int max_redirects: Limit for `follow_redirects`
        :arg string user_agent: String to send as ``User-Agent`` header
        :arg bool use_gzip: Request gzip encoding from the server
        :arg string network_interface: Network interface to use for request
        :arg callable streaming_callback: If set, `streaming_callback` will
           be run with each chunk of data as it is received, and
           `~HTTPResponse.body` and `~HTTPResponse.buffer` will be empty in
           the final response.
        :arg callable header_callback: If set, `header_callback` will
           be run with each header line as it is received, and
           `~HTTPResponse.headers` will be empty in the final response.
        :arg callable prepare_curl_callback: If set, will be called with
           a `pycurl.Curl` object to allow the application to make additional
           `setopt` calls.
        :arg string proxy_host: HTTP proxy hostname.  To use proxies,
           `proxy_host` and `proxy_port` must be set; `proxy_username` and
           `proxy_pass` are optional.  Proxies are currently only support
           with `curl_httpclient`.
        :arg int proxy_port: HTTP proxy port
        :arg string proxy_username: HTTP proxy username
        :arg string proxy_password: HTTP proxy password
        :arg bool allow_nonstandard_methods: Allow unknown values for `method`
           argument?
        :arg bool validate_cert: For HTTPS requests, validate the server's
           certificate?
        :arg string ca_certs: filename of CA certificates in PEM format,
           or None to use defaults.  Note that in `curl_httpclient`, if
           any request uses a custom `ca_certs` file, they all must (they
           don't have to all use the same `ca_certs`, but it's not possible
           to mix requests with ca_certs and requests that use the defaults.
        :arg bool allow_ipv6: Use IPv6 when available?  Default is false in
           `simple_httpclient` and true in `curl_httpclient`
        :arg string client_key: Filename for client SSL key, if any
        :arg string client_cert: Filename for client SSL certificate, if any
        """
        if headers is None:
            headers = httputil.HTTPHeaders()
        if if_modified_since:
            timestamp = calendar.timegm(if_modified_since.utctimetuple())
            headers["If-Modified-Since"] = email.utils.formatdate(
                timestamp, localtime=False, usegmt=True)
        self.proxy_host = proxy_host
        self.proxy_port = proxy_port
        self.proxy_username = proxy_username
        self.proxy_password = proxy_password
        self.url = url
        self.method = method
        self.headers = headers
        self.body = utf8(body)
        self.auth_username = auth_username
        self.auth_password = auth_password
        self.connect_timeout = connect_timeout
        self.request_timeout = request_timeout
        self.follow_redirects = follow_redirects
        self.max_redirects = max_redirects
        self.user_agent = user_agent
        self.use_gzip = use_gzip
        self.network_interface = network_interface
        self.streaming_callback = streaming_callback
        self.header_callback = header_callback
        self.prepare_curl_callback = prepare_curl_callback
        self.allow_nonstandard_methods = allow_nonstandard_methods
        self.validate_cert = validate_cert
        self.ca_certs = ca_certs
        self.allow_ipv6 = allow_ipv6
        self.client_key = client_key
        self.client_cert = client_cert
        self.start_time = time.time()

class HTTPResponse(object):
    """HTTP Response object.

    Attributes:

    * request: HTTPRequest object

    * code: numeric HTTP status code, e.g. 200 or 404

    * headers: httputil.HTTPHeaders object

    * buffer: cStringIO object for response body

    * body: respose body as string (created on demand from self.buffer)

    * error: Exception object, if any

    * request_time: seconds from request start to finish

    * time_info: dictionary of diagnostic timing information from the request.
        Available data are subject to change, but currently uses timings
        available from http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html,
        plus 'queue', which is the delay (if any) introduced by waiting for
        a slot under AsyncHTTPClient's max_clients setting.
    """
    def __init__(self, request, code, headers={}, buffer=None,
                 effective_url=None, error=None, request_time=None,
                 time_info={}):
        self.request = request
        self.code = code
        self.headers = headers
        self.buffer = buffer
        self._body = None
        if effective_url is None:
            self.effective_url = request.url
        else:
            self.effective_url = effective_url
        if error is None:
            if self.code < 200 or self.code >= 300:
                self.error = HTTPError(self.code, response=self)
            else:
                self.error = None
        else:
            self.error = error
        self.request_time = request_time
        self.time_info = time_info

    def _get_body(self):
        if self.buffer is None:
            return None
        elif self._body is None:
            self._body = self.buffer.getvalue()

        return self._body

    body = property(_get_body)

    def rethrow(self):
        """If there was an error on the request, raise an `HTTPError`."""
        if self.error:
            raise self.error

    def __repr__(self):
        args = ",".join("%s=%r" % i for i in self.__dict__.items())
        return "%s(%s)" % (self.__class__.__name__, args)

class HTTPError(Exception):
    """Exception thrown for an unsuccessful HTTP request.

    Attributes:

    code - HTTP error integer error code, e.g. 404.  Error code 599 is
           used when no HTTP response was received, e.g. for a timeout.

    response - HTTPResponse object, if any.

    Note that if follow_redirects is False, redirects become HTTPErrors,
    and you can look at error.response.headers['Location'] to see the
    destination of the redirect.
    """
    def __init__(self, code, message=None, response=None):
        self.code = code
        message = message or http.client.responses.get(code, "Unknown")
        self.response = response
        Exception.__init__(self, "HTTP %d: %s" % (self.code, message))

def main():
    from tornado.options import define, options, parse_command_line
    define("print_headers", type=bool, default=False)
    define("print_body", type=bool, default=True)
    define("follow_redirects", type=bool, default=True)
    define("validate_cert", type=bool, default=True)
    args = parse_command_line()
    client = HTTPClient()
    for arg in args:
        try:
            response = client.fetch(arg,
                                    follow_redirects=options.follow_redirects,
                                    validate_cert=options.validate_cert,
                                    )
        except HTTPError as e:
            if e.response is not None:
                response = e.response
            else:
                raise
        if options.print_headers:
            print(response.headers)
        if options.print_body:
            print(response.body)
    client.close()

if __name__ == "__main__":
    main()


text:
<?php

namespace Assistant\Module\Common\Controller;

use Assistant\Module\Common\Extension\Config;
use Cocur\BackgroundProcess\BackgroundProcess;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

final class TaskController
{
    private string $baseDir;

    public function __construct(Config $config)
    {
        $this->baseDir = $config->get('base_dir');
    }

    public function calculateAudioData(Request $request, Response $response): Response
    {
        $pathname = $request->getParsedBody()['pathname'] ?? null;
        $command = sprintf('php %s/bin/console.php track:calculate-audio-data -w "%s"', $this->baseDir, $pathname);

        $backgroundProcess = new BackgroundProcess($command);
        $backgroundProcess->run();

        $response->getBody()->write(json_encode([
            'command' => $command,
            'pid' => $backgroundProcess->getPid(),
        ]));

        return $response->withHeader('Content-Type', 'application/json');
    }

    public function move(Request $request, Response $response): Response
    {
        $post = $request->getParsedBody();

        $response->getBody()->write(json_encode([
            'message' => 'not-implemented :-(',
            'post' => $post,
        ]));

        return $response
            ->withStatus(418)
            ->withHeader('Content-Type', 'application/json');
    }
}


text:
angular.module("SidebarBtn",[])
.directive("sidebarBtn", function() {
	return {
		scope: {
			btn: "=",
		},
		templateUrl: "/templates/sidebarBtn.html",
		replace: true,
		controller: "sidebarBtnCtrl",
		controllerAs: "ctrl"
	};
})
.controller("sidebarBtnCtrl", function($scope, $rootScope, pageService) {
});


text:
function openNav() {
    document.getElementById("mySidenav").style.width = "20%";
}
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>Regulations Governing of Criteria for the Label, Promotion and Advertisement of Foods and Food Products Identified as False, Exaggerated, Misleading or Having Medical Efficacy</英文法規名稱>
<中文法規名稱>食品及相關產品標示宣傳廣告涉及不實誇張易生誤解或醫療效能認定準則</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=L0040140</法規網址>
<最新英文異動日期>20210524</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件>
  <檔案>
    <檔案名稱><![CDATA[Appendix 1.pdf]]></檔案名稱>
    <下載網址>https://law.moj.gov.tw/Eng/LawClass/LawGetFile.ashx?FileId=0000006678</下載網址>
  </檔案>
  <檔案>
    <檔案名稱><![CDATA[Appendix 2.pdf]]></檔案名稱>
    <下載網址>https://law.moj.gov.tw/Eng/LawClass/LawGetFile.ashx?FileId=0000006679</下載網址>
  </檔案>
</附件>
<沿革內容><![CDATA[1.Full text including 6 articles adopted and promulgated by the Ministry of Health and Welfare per Order Bu-Shou-Shi-Zi No. 1081201549 on June 12 2019.
2.Amendment to Article 4 and 6, Promulgated by the Ministry of Health and Welfare, Order Bu-Shou-Shi-Zi No. 1091202203 on August 4 2020.
3.Amendment to issued Annex 2 to Article 4, Promulgated by the Ministry of Health and Welfare, Order Bu-Shou-Shi-Zi No. 1101201216 on May 24 2021.
]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[The Regulations are prescribed in accordance with the provisions of Paragraph 4, Article 28 of the Act Governing Food Safety and Sanitation (hereinafter referred to as "the Act").]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[The "foods" and "food products" referred in the Regulations are defined as foods, food additives, food cleansers and food utensils, food containers or packaging designated by the central competent authority in the public announcement.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[The determining standards of the false, exaggerated or misleading labeling, promotion or advertisement referred to in Paragraph 1, Article 28 and medical efficacy referred to in Paragraph 2 in the Act shall be comprehensively judged by the overall presentation of the name, description, image, symbol, visual, audio or other messages conveyed to consumers of the product.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[The labeling, promotion or advertisement of foods and food products referred to in Paragraph 1, Article 28 of the Act is identified as false, exaggerated or misleading if involving any of the following condition:
(i)The description does not conform to facts.
(ii)The description has no evidence or insufficient evidence to support it.
(iii) The description involves maintaining or altering the physiology, appearance or function of human organs and tissue.
(iv) The content description refers to any number of official letters or any word or sentence with similar meanings; however, the use of approved official letter number complied with the laws and regulations are not subject to the limit.
If the word "health" as part of the food product name, it is identified as misleading. However, this regulation shall not apply to food product issued with a health food permit.
The phrases in Appendix 1 and the physiological functional description of the nutrients and specified components as in the Appendix 2 can be used for the labeling, promotion or advertisement of food products. The above descriptions are considered not false, exaggerated, or misleading.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[The labeling , promotion or advertisement of the foods referred to in Paragraph 2, Article 28 in the Act shall be identified as having medical efficacy if involving any of the following statement:
(i) The description is related to prevention, improvement, mitigation,diagnosis or treatment of any diseases, syndromes or symptoms.
(ii) The description is related to alleviation or reduction of any substances in human body caused by diseases.
(iii) The description is related to the efficacy of raw materials in traditional Chinese medicine.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[The Regulations shall be implemented upon promulgation.
Articles 4 of these Regulations, amended and promulgated on 4 Auguest 2020, shall take force from 1 July 2022.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * MODULE NOTES:
 * @update  gess 4/1/98
 *
 * This class is defines the basic interface between the
 * parser and the content sink. The parser will iterate
 * over the collection of tokens that it sees from the
 * tokenizer, coverting each related "group" into one of
 * these. This object gets passed to the sink, and is
 * then immediately reused.
 *
 * If you want to hang onto one of these, you should
 * make your own copy.
 *
 */

#ifndef NS_IPARSERNODE__
#define NS_IPARSERNODE__

#include "nsISupports.h"
#include "prtypes.h"
#include "nsStringGlue.h"
#include "nsDebug.h"

//#define HEAP_ALLOCATED_NODES
//#define DEBUG_TRACK_NODES

class nsIAtom;
class CToken;

// 6e59f160-2717-11d2-9246-00805f8a7ab6
#define NS_IPARSER_NODE_IID      \
  {0x6e59f160, 0x2717,  0x11d1,  \
  {0x92, 0x46, 0x00,    0x80, 0x5f, 0x8a, 0x7a, 0xb6}}

/**
 *  Parser nodes are the unit of exchange between the
 *  parser and the content sink. Nodes offer access to
 *  the current token, its attributes, and its skipped-
 *  content if applicable.
 *
 *  @update  gess 3/25/98
 */
class nsIParserNode { // XXX Should be nsAParserNode

  public:

    /**
     * Retrieve the name of the node
     * @update	gess5/11/98
     * @return  string containing node name
     */
    virtual const nsAString& GetTagName() const = 0;  //to get name of tag

    /**
     * Retrieve the text from the given node
     * @update	gess5/11/98
     * @return  string containing node text
     */
    virtual const nsAString& GetText() const = 0;  //get plain text if available

    /**
     * Retrieve the type of the parser node.
     * @update	gess5/11/98
     * @return  node type.
     */
    virtual PRInt32 GetNodeType()  const =0;

    /**
     * Retrieve token type of parser node
     * @update	gess5/11/98
     * @return  token type
     */
    virtual PRInt32 GetTokenType()  const =0;

    /**
     * Retrieve the number of attributes in this node.
     * @update	gess5/11/98
     * @return  count of attributes (may be 0)
     */
    virtual PRInt32 GetAttributeCount(bool askToken=false) const =0;

    /**
     * Retrieve the key (of key/value pair) at given index
     * @update	gess5/11/98
     * @param   anIndex is the index of the key you want
     * @return  string containing key.
     */
    virtual const nsAString& GetKeyAt(PRUint32 anIndex) const = 0;

    /**
     * Retrieve the value (of key/value pair) at given index
     * @update	gess5/11/98
     * @param   anIndex is the index of the value you want
     * @return  string containing value.
     */
    virtual const nsAString& GetValueAt(PRUint32 anIndex) const = 0;

    /**
     * NOTE: When the node is an entity, this will translate the entity
     *       to it's unicode value, and store it in aString.
     * @update	gess5/11/98
     * @param   aString will contain the resulting unicode string value
     * @return  int (unicode char or unicode index from table)
     */
    virtual PRInt32 TranslateToUnicodeStr(nsString& aString) const = 0;

    virtual void AddAttribute(CToken* aToken)=0;

    /**
     * This getter retrieves the line number from the input source where
     * the token occurred. Lines are interpreted as occurring between \n characters.
     * @update	gess7/24/98
     * @return  int containing the line number the token was found on
     */
    virtual PRInt32 GetSourceLineNumber(void) const =0;

    /**
     * This pair of methods allows us to set a generic bit (for arbitrary use)
     * on each node stored in the context.
     * @update	gess 11May2000
     */
    virtual bool    GetGenericState(void) const =0;
    virtual void    SetGenericState(bool aState) =0;

    /** Retrieve a string containing the tag and its attributes in "source" form
     * @update	rickg 06June2000
     * @return  void
     */
    virtual void GetSource(nsString& aString) const = 0;

    /** Release all the objects you're holding
     * @update	harishd 08/02/00
     * @return  void
     */
    virtual nsresult ReleaseAll()=0;
};

#endif


text:
package com.liangmayong.base.basic.expands.list;

import android.view.View;
import android.widget.ListView;

import com.liangmayong.base.R;
import com.liangmayong.base.basic.flow.FlowBaseFragment;

/**
 * Created by LiangMaYong on 2017/3/1.
 */
public abstract class FlowListFragment extends FlowBaseFragment {
    // listView
    private ListView listView = null;

    @Override
    protected final void initViews(View containerView) {
        listView = (ListView) containerView.findViewById(R.id.base_default_listview);
        initListViews(listView);
    }

    @Override
    protected int getContaierLayoutId() {
        return R.layout.base_default_fragment_list;
    }

    /**
     * initListViews
     *
     * @param listView listView
     */
    protected abstract void initListViews(ListView listView);

    /**
     * getListView
     *
     * @return listView
     */
    public ListView getListView() {
        return listView;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: Member List</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

Alphabetical List

Class List

Class Hierarchy

Class Members

Stats::InfoAccess Member List
This is the complete list of members for Stats::InfoAccess, including all inherited members.

check() const 	Stats::InfoAccess	 [inline]

info()	Stats::InfoAccess	 [protected]

info() const 	Stats::InfoAccess	 [protected]

reset()	Stats::InfoAccess	 [inline]

setInfo(Info *info)	Stats::InfoAccess	 [protected]

setInit()	Stats::InfoAccess	 [protected]

setParams(const StorageParams *params)	Stats::InfoAccess	 [protected]

zero() const 	Stats::InfoAccess	 [inline]

<address style="align: right;">
Generated on Fri Apr 17 12:41:44 2015 for gem5 by  doxygen 1.4.7</address>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
# ***************************************************************************************************
# * Copyright (c) 2007 IBM Corporation and others.
# * All rights reserved. This program and the accompanying materials
# * are made available under the terms of the Eclipse Public License v1.0
# * which accompanies this distribution, and is available at
# * http://www.eclipse.org/legal/epl-v10.html
# *
# * Contributors:
# *     IBM Corporation - initial API and implementation
# ********************************************************************************************** -->
<!--
# /*******************************************************************************************************
# * Key Format:
# *
# * 	 For level 1 data, the key is the ISO3166-2 code. An ISO3166-2 code is composed as follows:
# * a two letter country code followed by up to three alphanumeric characters for the level 1 administration.
# *
# * 	 For level 2 data, the key is the ISO3166-2 code followed by six digits. The leftmost two digits indicate
# * the level 1 container of a level 2 administration (i.e. California is a level 1 container for Orange County
# * which is a level 2 administration).  The two digits were taken from a lexicographic sorting of all the
# * level 1 administrations within a country. Similarly, the four leftmost digits indicate the level 2 administration.
# * Again, these four digits are an index into the lexicographic sorting of all level 2 administrations within
# * a level 1 administration.
# *************************************************************************************************** -->

<Map xmlns:gml="http://www.opengis.net/gml" xmlns:georss="http://www.georss.org/georss">
<title>SQR Level 0 Map</title>
<subTitle>Administrative Boundaries</subTitle>
<updated>Tue Nov 07 16:57:55 PST 2006 </updated>
<entry>
<georss:where><gml:Polygon gml:id="SQR">
<gml:outerBoundaryIs>
<gml:LinearRing>
<gml:posList>
0 0 0 1 1 1 1 0
</gml:posList>
</gml:LinearRing>
</gml:outerBoundaryIs>
</gml:Polygon>
</georss:where>
</entry>
</Map>