/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_LIST_TO_CONS_07172005_1041)
#define FUSION_LIST_TO_CONS_07172005_1041

#include <boost/fusion/support/config.hpp>
#include <boost/fusion/container/list/cons.hpp>
#include <boost/fusion/container/list/detail/cpp03/limits.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_shifted_params.hpp>
#include <boost/preprocessor/arithmetic/dec.hpp>

#define FUSION_VOID(z, n, _) void_

namespace boost { namespace fusion
{
    struct nil_;
    struct void_;
}}

#if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES)
#include <boost/fusion/container/list/detail/cpp03/preprocessed/list_to_cons.hpp>
#else
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/list_to_cons" FUSION_MAX_LIST_SIZE_STR ".hpp")
#endif

/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

    This is an auto-generated file. Do not edit!
==============================================================================*/

#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif

namespace boost { namespace fusion { namespace detail
{
    template <BOOST_PP_ENUM_PARAMS(FUSION_MAX_LIST_SIZE, typename T)>
    struct list_to_cons
    {
        typedef T0 head_type;
        typedef list_to_cons<
            BOOST_PP_ENUM_SHIFTED_PARAMS(FUSION_MAX_LIST_SIZE, T), void_>
        tail_list_to_cons;
        typedef typename tail_list_to_cons::type tail_type;

        typedef cons<head_type, tail_type> type;

        #include <boost/fusion/container/list/detail/cpp03/list_to_cons_call.hpp>
    };

    template <>
    struct list_to_cons<BOOST_PP_ENUM(FUSION_MAX_LIST_SIZE, FUSION_VOID, _)>
    {
        typedef nil_ type;
    };
}}}

#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif

#endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES

#undef FUSION_VOID
#endif

{'repo_name': 'FantasticLBP/Hotels', 'stars': '312', 'repo_language': 'Objective-C', 'file_name': 'IQKeyboardManager.strings', 'mime_type': 'text/plain', 'hash': 6290616093546277721, 'source_dataset': 'data'}


# created by tools/tclZIC.tcl - do not edit

set TZData(:Africa/Libreville) {
    {-9223372036854775808 2268 0 LMT}
    {-1830386268 3600 0 WAT}
}

{'repo_name': 'koto/mosquito', 'stars': '144', 'repo_language': 'Tcl', 'file_name': 'pt.msg', 'mime_type': 'text/plain', 'hash': -6690503759500371038, 'source_dataset': 'data'}


<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

/* load MX core classes */
require_once dirname(__FILE__).'/Lang.php';
require_once dirname(__FILE__).'/Config.php';

/**
 * Modular Extensions - HMVC
 *
 * Adapted from the CodeIgniter Core Classes
 * @link	http://codeigniter.com
 *
 * Description:
 * This library extends the CodeIgniter CI_Controller class and creates an application
 * object allowing use of the HMVC design pattern.
 *
 * Install this file as application/third_party/MX/Base.php
 *
 * @copyright	Copyright (c) 2011 Wiredesignz
 * @version 	5.4
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/
class CI extends CI_Controller
{
	public static $APP;

	public function __construct() {

		/* assign the application instance */
		self::$APP = $this;

		global $LANG, $CFG;

		/* re-assign language and config for modules */
		if ( ! is_a($LANG, 'MX_Lang')) $LANG = new MX_Lang;
		if ( ! is_a($CFG, 'MX_Config')) $CFG = new MX_Config;

		parent::__construct();
	}
}

/* create the application object */
new CI;

{'repo_name': 'matdryhurst/Saga', 'stars': '122', 'repo_language': 'PHP', 'file_name': 'xinha_conf.js', 'mime_type': 'text/plain', 'hash': -2250840154971265467, 'source_dataset': 'data'}


/*
     File: CADebugMacros.cpp
 Abstract:  CADebugMacros.h
  Version: 1.01

 Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple
 Inc. ("Apple") in consideration of your agreement to the following
 terms, and your use, installation, modification or redistribution of
 this Apple software constitutes acceptance of these terms.  If you do
 not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.

 In consideration of your agreement to abide by the following terms, and
 subject to these terms, Apple grants you a personal, non-exclusive
 license, under Apple's copyrights in this original Apple software (the
 "Apple Software"), to use, reproduce, modify and redistribute the Apple
 Software, with or without modifications, in source and/or binary forms;
 provided that if you redistribute the Apple Software in its entirety and
 without modifications, you must retain this notice and the following
 text and disclaimers in all such redistributions of the Apple Software.
 Neither the name, trademarks, service marks or logos of Apple Inc. may
 be used to endorse or promote products derived from the Apple Software
 without specific prior written permission from Apple.  Except as
 expressly stated in this notice, no other rights or licenses, express or
 implied, are granted by Apple herein, including but not limited to any
 patent rights that may be infringed by your derivative works or by other
 works in which the Apple Software may be incorporated.

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.

 Copyright (C) 2012 Apple Inc. All Rights Reserved.

*/
#include "CADebugMacros.h"
#include <stdio.h>
#include <stdarg.h>
#if TARGET_API_MAC_OSX
	#include <syslog.h>
#endif

#if DEBUG
#include <stdio.h>

void	DebugPrint(const char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
	vprintf(fmt, args);
	va_end(args);
}
#endif // DEBUG

#if TARGET_API_MAC_OSX
void	LogError(const char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
#if DEBUG
	vprintf(fmt, args);
#endif
	vsyslog(LOG_ERR, fmt, args);
	va_end(args);
}

void	LogWarning(const char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
#if DEBUG
	vprintf(fmt, args);
#endif
	vsyslog(LOG_WARNING, fmt, args);
	va_end(args);
}
#endif

{'repo_name': 'grame-cncm/faust', 'stars': '1178', 'repo_language': 'C++', 'file_name': 'faustgen-wrapper-poly.maxpat', 'mime_type': 'text/plain', 'hash': 4319036806925816899, 'source_dataset': 'data'}


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SitemapMenuViewModel.cs" company="Devbridge Group LLC">
//
// Copyright (C) 2015,2016 Devbridge Group LLC
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
// </copyright>
//
// <summary>
// Better CMS is a publishing focused and developer friendly .NET open source CMS.
//
// Website: https://www.bettercms.com
// GitHub: https://github.com/devbridge/bettercms
// Email: info@bettercms.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System.Collections.Generic;

namespace BetterCms.Sandbox.Mvc4.Models
{
    public class SitemapMenuViewModel
    {
        public string LanguageCode { get; set; }

        public bool RenderIFrame { get; set; }

        public List<MenuItemViewModel> ObsoleteMenuItems { get; set; }

        public List<MenuItemViewModel> MenuItems { get; set; }

        public List<string> LanguageCodes { get; set; }
    }
}

{'repo_name': 'devbridge/BetterCMS', 'stars': '383', 'repo_language': 'C#', 'file_name': 'SlowCheetah.Transforms.targets', 'mime_type': 'text/xml', 'hash': -1744850160287650441, 'source_dataset': 'data'}


class ServiceGatewayNetValueAddToSubscriptionsReport < ActiveRecord::Migration
  def up
    execute <<-SQL

    DROP VIEW subscription_monthly_report_for_project_owners;
    CREATE OR REPLACE VIEW subscription_monthly_report_for_project_owners AS
    SELECT s.project_id,
      u.name,
      u.public_name,
      u.email,
        replace(round((((s.data ->> 'amount'::text))::numeric / (100)::numeric), 2)::text, '.', ',') AS amount,
        replace(round(((s.data->>'amount'::text)::numeric * proj.service_fee - (s.gateway_general_data->>'gateway_cost'::text)::numeric) / 100, 2)::text, '.', ',')   as service_fee,
        replace(round((s.gateway_general_data->>'gateway_cost'::text)::numeric / 100, 2)::text, '.', ',')   as payment_method_fee,
        replace(round(((s.data->>'amount'::text)::numeric - (s.data->>'amount'::text)::numeric * proj.service_fee) / 100, 2)::text, '.', ',')  as net_value,
      r.title,
      r.description,
      (s.data ->> 'payment_method'::text) AS payment_method,
      zone_timestamp(s.created_at) AS created_at,
      zone_timestamp(pst.created_at) AS paid_at,
      'Confirmado'::text AS confirmed,
      u.id AS user_id,
          CASE
              WHEN COALESCE(((sub.checkout_data ->> 'anonymous'::text) = 'true'::text), ((s.data ->> 'anonymous'::text) = 'true'::text)) THEN 'sim'::text
              ELSE 'não'::text
          END AS anonymous,
      (((s.data -> 'customer'::text) -> 'address'::text) ->> 'street'::text) AS street,
      (((s.data -> 'customer'::text) -> 'address'::text) ->> 'complementary'::text) AS complement,
      (((s.data -> 'customer'::text) -> 'address'::text) ->> 'street_number'::text) AS number,
      (((s.data -> 'customer'::text) -> 'address'::text) ->> 'neighborhood'::text) AS neighborhood,
      (((s.data -> 'customer'::text) -> 'address'::text) ->> 'city'::text) AS city,
      (((s.data -> 'customer'::text) -> 'address'::text) ->> 'state'::text) AS state,
      (((s.data -> 'customer'::text) -> 'address'::text) ->> 'zipcode'::text) AS zipcode,
      u.cpf
    FROM ((((common_schema.catalog_payments s
      JOIN users u ON ((u.common_id = s.user_id)))
      LEFT JOIN rewards r ON ((r.common_id = s.reward_id)))
      JOIN common_schema.payment_status_transitions pst ON (((pst.catalog_payment_id = s.id) AND (pst.to_status = 'paid'::payment_service.payment_status))))
      LEFT JOIN common_schema.subscriptions sub ON ((sub.id = s.subscription_id)))
      LEFT JOIN projects proj ON sub.project_id = proj.common_id
    WHERE (s.status = 'paid'::payment_service.payment_status)
    GROUP BY proj.id, s.gateway_general_data, s.project_id, u.name, u.public_name, u.email, s.data, r.title, r.description, s.created_at, s.updated_at, u.id, pst.created_at, sub.checkout_data;

    grant select on subscription_monthly_report_for_project_owners to admin, web_user;

    SQL
  end

  def down
    execute <<-SQL

      DROP VIEW "subscription_monthly_report_for_project_owners";
      CREATE OR REPLACE VIEW "public"."subscription_monthly_report_for_project_owners" AS
      SELECT s.project_id,
          u.name,
          u.public_name,
          u.email,
          (((s.data ->> 'amount'::text))::numeric / (100)::numeric) AS amount,
          r.title,
          r.description,
          (s.data ->> 'payment_method'::text) AS payment_method,
          zone_timestamp(s.created_at) AS created_at,
          zone_timestamp(pst.created_at) AS paid_at,
          'Confirmado'::text AS confirmed,
          u.id AS user_id,
              CASE
                  WHEN COALESCE(((sub.checkout_data ->> 'anonymous'::text) = 'true'::text), ((s.data ->> 'anonymous'::text) = 'true'::text)) THEN 'sim'::text
                  ELSE 'não'::text
              END AS anonymous,
          (((s.data -> 'customer'::text) -> 'address'::text) ->> 'street'::text) AS street,
          (((s.data -> 'customer'::text) -> 'address'::text) ->> 'complementary'::text) AS complement,
          (((s.data -> 'customer'::text) -> 'address'::text) ->> 'street_number'::text) AS number,
          (((s.data -> 'customer'::text) -> 'address'::text) ->> 'neighborhood'::text) AS neighborhood,
          (((s.data -> 'customer'::text) -> 'address'::text) ->> 'city'::text) AS city,
          (((s.data -> 'customer'::text) -> 'address'::text) ->> 'state'::text) AS state,
          (((s.data -> 'customer'::text) -> 'address'::text) ->> 'zipcode'::text) AS zipcode,
          u.cpf
        FROM ((((common_schema.catalog_payments s
          JOIN users u ON ((u.common_id = s.user_id)))
          LEFT JOIN rewards r ON ((r.common_id = s.reward_id)))
          JOIN common_schema.payment_status_transitions pst ON (((pst.catalog_payment_id = s.id) AND (pst.to_status = 'paid'::payment_service.payment_status))))
          LEFT JOIN common_schema.subscriptions sub ON ((sub.id = s.subscription_id)))
        WHERE (s.status = 'paid'::payment_service.payment_status)
        GROUP BY s.project_id, u.name, u.public_name, u.email, s.data, r.title, r.description, s.created_at, s.updated_at, u.id, pst.created_at, sub.checkout_data;

      grant select on subscription_monthly_report_for_project_owners to admin, web_user;
    SQL
  end
end

{'repo_name': 'catarse/catarse', 'stars': '1533', 'repo_language': 'Ruby', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -1798810335538309510, 'source_dataset': 'data'}


// Copyright 2016-2019 DutchSec (https://dutchsec.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ftp

// FTP status codes, defined in RFC 959
const (
	StatusInitiating    = 100
	StatusRestartMarker = 110
	StatusReadyMinute   = 120
	StatusAlreadyOpen   = 125
	StatusAboutToSend   = 150

	StatusCommandOK             = 200
	StatusCommandNotImplemented = 202
	StatusSystem                = 211
	StatusDirectory             = 212
	StatusFile                  = 213
	StatusHelp                  = 214
	StatusName                  = 215
	StatusReady                 = 220
	StatusClosing               = 221
	StatusDataConnectionOpen    = 225
	StatusClosingDataConnection = 226
	StatusPassiveMode           = 227
	StatusLongPassiveMode       = 228
	StatusExtendedPassiveMode   = 229
	StatusLoggedIn              = 230
	StatusLoggedOut             = 231
	StatusLogoutAck             = 232
	StatusRequestedFileActionOK = 250
	StatusPathCreated           = 257

	StatusUserOK             = 331
	StatusLoginNeedAccount   = 332
	StatusRequestFilePending = 350

	StatusNotAvailable             = 421
	StatusCanNotOpenDataConnection = 425
	StatusTransfertAborted         = 426
	StatusInvalidCredentials       = 430
	StatusHostUnavailable          = 434
	StatusFileActionIgnored        = 450
	StatusActionAborted            = 451
	Status452                      = 452

	StatusBadCommand              = 500
	StatusBadArguments            = 501
	StatusNotImplemented          = 502
	StatusBadSequence             = 503
	StatusNotImplementedParameter = 504
	StatusNotLoggedIn             = 530
	StatusStorNeedAccount         = 532
	StatusFileUnavailable         = 550
	StatusPageTypeUnknown         = 551
	StatusExceededStorage         = 552
	StatusBadFileName             = 553
)

var statusText = map[int]string{
	// 200
	StatusCommandOK:             "OK.",
	StatusCommandNotImplemented: "Command not implemented, obsolete.",
	StatusSystem:                "System status, or system help reply.",
	StatusDirectory:             "Directory status.",
	StatusFile:                  "File status.",
	StatusHelp:                  "Help message.",
	StatusName:                  "",
	StatusReady:                 "Service ready for new user.",
	StatusClosing:               "Service closing control connection.",
	StatusDataConnectionOpen:    "Data connection open; no transfer in progress.",
	StatusClosingDataConnection: "Closing data connection. Requested file action successful.",
	StatusPassiveMode:           "Entering Passive Mode.",
	StatusLongPassiveMode:       "Entering Long Passive Mode.",
	StatusExtendedPassiveMode:   "Entering Extended Passive Mode.",
	StatusLoggedIn:              "User logged in, proceed.",
	StatusLoggedOut:             "User logged out; service terminated.",
	StatusLogoutAck:             "Logout command noted, will complete when transfer done.",
	StatusRequestedFileActionOK: "Requested file action okay, completed.",
	StatusPathCreated:           "Path created.",

	// 300
	StatusUserOK:             "User name OK, need password.",
	StatusLoginNeedAccount:   "Need account for login.",
	StatusRequestFilePending: "Requested file action pending further information.",

	// 400
	StatusNotAvailable:             "Service not available, closing control connection.",
	StatusCanNotOpenDataConnection: "Can't open data connection.",
	StatusTransfertAborted:         "Connection closed; transfer aborted.",
	StatusInvalidCredentials:       "Invalid username or password.",
	StatusHostUnavailable:          "Requested host unavailable.",
	StatusFileActionIgnored:        "Requested file action not taken.",
	StatusActionAborted:            "Requested action aborted. Local error in processing.",
	Status452:                      "Insufficient storage space in system.",

	// 500
	StatusBadCommand:              "Command not found.",
	StatusBadArguments:            "Syntax error in parameters or arguments.",
	StatusNotImplemented:          "Command not implemented.",
	StatusBadSequence:             "Bad sequence of commands.",
	StatusNotImplementedParameter: "Command not implemented for that parameter.",
	StatusNotLoggedIn:             "Not logged in.",
	StatusStorNeedAccount:         "Need account for storing files.",
	StatusFileUnavailable:         "File unavailable.",
	StatusPageTypeUnknown:         "Page type unknown.",
	StatusExceededStorage:         "Exceeded storage allocation.",
	StatusBadFileName:             "File name not allowed.",
}

{'repo_name': 'honeytrap/honeytrap', 'stars': '741', 'repo_language': 'Go', 'file_name': 'profiler.go', 'mime_type': 'text/plain', 'hash': -5583020566417286180, 'source_dataset': 'data'}


#include <QApplication>
#include <QAction>
#include <QMainWindow>
#include <QStringList>

#include "Scene_surface_mesh_item.h"
#include "Scene_textured_surface_mesh_item.h"
#include "Scene_polyhedron_selection_item.h"
#include "SMesh_type.h"
#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>
#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>
#include <CGAL/Three/Three.h>
#include "Scene.h"
#include <QElapsedTimer>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QPen>
#include <QDockWidget>
#include <Messages_interface.h>
#include <CGAL/Polygon_mesh_processing/border.h>
#include <CGAL/Polygon_mesh_processing/measure.h>
#include <CGAL/property_map.h>

#include <CGAL/boost/graph/Seam_mesh.h>
#include <CGAL/boost/graph/graph_traits_Seam_mesh.h>

#include <CGAL/Surface_mesh_parameterization/ARAP_parameterizer_3.h>
#include <CGAL/Surface_mesh_parameterization/Barycentric_mapping_parameterizer_3.h>
#include <CGAL/Surface_mesh_parameterization/Discrete_authalic_parameterizer_3.h>
#include <CGAL/Surface_mesh_parameterization/Discrete_conformal_map_parameterizer_3.h>
#include <CGAL/Surface_mesh_parameterization/Error_code.h>
#include <CGAL/Surface_mesh_parameterization/LSCM_parameterizer_3.h>
#include <CGAL/Surface_mesh_parameterization/Two_vertices_parameterizer_3.h>
#include <CGAL/Surface_mesh_parameterization/internal/orbifold_cone_helper.h>
#include <CGAL/Surface_mesh_parameterization/Orbifold_Tutte_parameterizer_3.h>
#include <CGAL/Surface_mesh_parameterization/parameterize.h>

#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include <boost/container/flat_map.hpp>

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

#include <CGAL/boost/graph/properties.h>
#include <CGAL/Qt/GraphicsViewNavigation.h>

#include "ui_Parameterization_widget.h"
#include "ui_OTE_dialog.h"

typedef Scene_surface_mesh_item Scene_facegraph_item;
typedef Scene_textured_surface_mesh_item Scene_textured_facegraph_item;
typedef SMesh Textured_face_graph;
typedef SMesh Base_face_graph;
typedef SMesh Face_graph;
typedef EPICK Traits;

namespace SMP = CGAL::Surface_mesh_parameterization;

typedef boost::unordered_set<boost::graph_traits<Base_face_graph>::face_descriptor> Component;
typedef std::vector<Component> Components;

struct Is_selected_property_map{
  typedef boost::graph_traits<Base_face_graph>::edge_descriptor edge_descriptor;
  typedef boost::property_map<Base_face_graph, boost::halfedge_index_t>::type HIndexMap;
  std::vector<bool>* is_selected_ptr;
  Base_face_graph* graph;
  HIndexMap idmap;
  Is_selected_property_map()
    : is_selected_ptr(NULL), graph(NULL) {}
  Is_selected_property_map(std::vector<bool>& is_selected,
                           Base_face_graph* graph)
    : is_selected_ptr( &is_selected), graph(graph)
  {
    idmap = get(boost::halfedge_index, *graph);
  }

  std::size_t id(edge_descriptor ed) { return get(idmap, halfedge(ed, *graph))/2; }

  friend bool get(Is_selected_property_map map, edge_descriptor ed)
  {
    CGAL_assertion(map.is_selected_ptr!=NULL);
    return (*map.is_selected_ptr)[map.id(ed)];
  }

  friend void put(Is_selected_property_map map, edge_descriptor ed, bool b)
  {
    CGAL_assertion(map.is_selected_ptr!=NULL);
    (*map.is_selected_ptr)[map.id(ed)]=b;
  }
};

class Navigation : public CGAL::Qt::GraphicsViewNavigation
{
public:
  Navigation()
    :CGAL::Qt::GraphicsViewNavigation(),
      prev_pos(QPoint(0,0))
  { }

protected:
  bool eventFilter(QObject *obj, QEvent *ev)
  {
    QGraphicsView* v = qobject_cast<QGraphicsView*>(obj);
    if(v == NULL) {
      QWidget* viewport = qobject_cast<QWidget*>(obj);
      if(viewport == NULL) {
        return false;
      }
      v = qobject_cast<QGraphicsView*>(viewport->parent());
      if(v == NULL) {
        return false;
      }
    }
    switch(ev->type())
    {
    case QEvent::MouseMove: {
      QMouseEvent* me = static_cast<QMouseEvent*>(ev);
      if(is_dragging)
      {
        qreal dir[2] = {v->mapToScene(me->pos()).x() - prev_pos.x(),
                        v->mapToScene(me->pos()).y() - prev_pos.y()};

        v->translate(dir[0],dir[1]);
        v->update();
      }
      prev_pos = v->mapToScene(me->pos());
      break;
    }

    case QEvent::MouseButtonPress: {
      is_dragging = true;
      break;
    }
    case QEvent::MouseButtonRelease: {
      is_dragging = false;
      break;
    }
    case QEvent::Wheel: {
      QWheelEvent* event = static_cast<QWheelEvent*>(ev);
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
      QPoint pos = event->pos();
#else
      QPointF pos = event->position();
#endif
      QPointF old_pos = v->mapToScene(pos.x(), pos.y());
      if(event->angleDelta().y() <0)
        v->scale(1.2, 1.2);
      else
        v->scale(0.8, 0.8);
      QPointF new_pos = v->mapToScene(pos.x(), pos.y());
      QPointF delta = new_pos - old_pos;
      v->translate(delta.x(), delta.y());
      v->update();
      break;
    }

    case QEvent::MouseButtonDblClick: {
      v->fitInView(v->scene()->itemsBoundingRect(), Qt::KeepAspectRatio);
      break;
    }
    default:
      CGAL::Qt::GraphicsViewNavigation::eventFilter(obj, ev);
    }
    return false;
  }
private:
  bool is_dragging;
  QPointF prev_pos;
};

namespace SMP = CGAL::Surface_mesh_parameterization;

typedef Traits::FT                                                  FT;
typedef boost::graph_traits<Face_graph>::vertex_descriptor          P_vertex_descriptor;
typedef Traits::Point_2                                             Point_2;
typedef boost::graph_traits<Face_graph>::edge_descriptor            P_edge_descriptor;
typedef boost::graph_traits<Face_graph>::halfedge_descriptor        P_halfedge_descriptor;

// Textured polyhedron
typedef boost::graph_traits<Base_face_graph>::
                                         edge_descriptor            T_edge_descriptor;
typedef boost::graph_traits<Base_face_graph>::
                                         halfedge_descriptor        T_halfedge_descriptor;
typedef boost::graph_traits<Base_face_graph>::
                                         vertex_descriptor          T_vertex_descriptor;

// Seam
typedef CGAL::Unique_hash_map<T_halfedge_descriptor,Point_2>        UV_uhm;
typedef CGAL::Unique_hash_map<T_edge_descriptor,bool>               Seam_edge_uhm;
typedef CGAL::Unique_hash_map<T_vertex_descriptor,bool>             Seam_vertex_uhm;

typedef boost::associative_property_map<UV_uhm>                     UV_pmap;
typedef boost::associative_property_map<Seam_edge_uhm>              Seam_edge_pmap;
typedef boost::associative_property_map<Seam_vertex_uhm>            Seam_vertex_pmap;

typedef CGAL::Seam_mesh<Base_face_graph,
                        Seam_edge_pmap, Seam_vertex_pmap>           Seam_mesh;

typedef boost::graph_traits<Seam_mesh>::vertex_descriptor           s_vertex_descriptor;
typedef boost::graph_traits<Seam_mesh>::halfedge_descriptor         s_halfedge_descriptor;
typedef boost::graph_traits<Seam_mesh>::face_descriptor             s_face_descriptor;

typedef boost::graph_traits<Seam_mesh>::edges_size_type             s_edges_size_type;

typedef boost::unordered_set<boost::graph_traits<Base_face_graph>::
face_descriptor>                                                    Component;
typedef std::vector<Component>                                      Components;

typedef boost::unordered_set<s_face_descriptor>                       SComponent;
typedef std::vector<SComponent>                                     SComponents;

class UVItem : public QGraphicsItem
{
public :
  UVItem(Components* components,
         Base_face_graph* graph,
         std::vector<std::vector<float> >uv_borders,
         QRectF brect)
    :
      QGraphicsItem(),
      bounding_rect(brect),
      components(components),
      graph(graph),
      m_borders(uv_borders),
      m_concatenated_borders(),
      m_current_component(0)
  {
    std::size_t total_border_size = 0;
    for(std::size_t i=0; i<m_borders.size(); ++i)
      total_border_size += m_borders[i].size();

    m_concatenated_borders.resize(total_border_size);
    for(std::size_t i=0; i<m_borders.size(); ++i)
    {
      const std::vector<float>& ith_border = m_borders[i];
      m_concatenated_borders.insert(m_concatenated_borders.end(),
                                    ith_border.begin(), ith_border.end());
    }
  }

  ~UVItem()
  {
    delete components;
  }

  const std::vector<std::vector<float> >& borders() const { return m_borders; }
  const std::vector<float>& concatenated_borders() const { return m_concatenated_borders; }

  QRectF boundingRect() const
  {
    return bounding_rect;
  }

  QString item_name()const{ return texMesh_name; }
  void set_item_name(QString s){ texMesh_name = s;}

  void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
  {
    QPen pen;
    QBrush brush;
    brush.setColor(QColor(100, 100, 255));
    brush.setStyle(Qt::SolidPattern);
    pen.setColor(Qt::black);
    pen.setWidth(0);
    painter->setPen(pen);
    painter->setBrush(brush);
    SMesh::Property_map<halfedge_descriptor,float> u,v;

    u = graph->add_property_map<halfedge_descriptor,float>("h:u", 0.0f).first;
    v = graph->add_property_map<halfedge_descriptor,float>("h:v", 0.0f).first;

    for( Component::iterator
         fi = components->at(m_current_component).begin();
         fi != components->at(m_current_component).end();
         ++fi)
    {
      boost::graph_traits<Base_face_graph>::face_descriptor f(*fi);

      QPointF points[3];
      boost::graph_traits<Base_face_graph>::halfedge_descriptor h = halfedge(f, *graph);;
      points[0] = QPointF(get(u, h), get(v, h));
      h = next(halfedge(f, *graph), *graph);
      points[1] = QPointF(get(u, h), get(v, h));
      h = next(next(halfedge(f, *graph), *graph), *graph);
      points[2] = QPointF(get(u, h), get(v, h));
      painter->drawPolygon(points,3);
    }
  }

  int number_of_components()const{return static_cast<int>(components->size());}
  int current_component()const{return m_current_component;}
  void set_current_component(int n){m_current_component = n;}

private:
  QString texMesh_name;
  QRectF bounding_rect;
  Components* components;
  Base_face_graph* graph;
  std::vector<std::vector<float> > m_borders;
  std::vector<float> m_concatenated_borders;
  int m_current_component;
};

using namespace CGAL::Three;

class Polyhedron_demo_parameterization_plugin :
    public QObject,
    public Polyhedron_demo_plugin_helper
{
  Q_OBJECT
  Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)
  Q_PLUGIN_METADATA(IID "com.geometryfactory.PolyhedronDemo.PluginInterface/1.0")

public:
  // used by Polyhedron_demo_plugin_helper
  QList<QAction*> actions() const
  {
    return _actions;
  }

  ~Polyhedron_demo_parameterization_plugin()
  {
    delete navigation;
  }
  void init(QMainWindow* mainWindow,
            Scene_interface* scene_interface,
            Messages_interface* msg)
  {
    mw = mainWindow;
    scene = scene_interface;
    messages = msg;
    Scene* true_scene = static_cast<Scene*>(scene);
    connect(true_scene, SIGNAL(itemAboutToBeDestroyed(CGAL::Three::Scene_item*)),
            this, SLOT(destroyPolyline(CGAL::Three::Scene_item*)));
    QAction* actionMVC = new QAction("Mean Value Coordinates", mw);
    QAction* actionDCP = new QAction ("Discrete Conformal Map", mw);
    QAction* actionLSC = new QAction("Least Square Conformal Map", mw);
    QAction* actionDAP = new QAction("Discrete Authalic", mw);
    QAction* actionARAP = new QAction("As Rigid As Possible", mw);
    QAction* actionOTE = new QAction("Orbifold Tutte Embedding", mw);
    QAction* actionBTP = new QAction("Tutte Barycentric", mw);
    actionMVC->setObjectName("actionMVC");
    actionDCP->setObjectName("actionDCP");
    actionLSC->setObjectName("actionLSC");
    actionDAP->setObjectName("actionDAP");
    actionARAP->setObjectName("actionARAP");
    actionOTE->setObjectName("actionOTE");
    actionBTP->setObjectName("actionBTP");

    _actions << actionARAP
             << actionBTP
             << actionDAP
             << actionDCP
             << actionLSC
             << actionMVC
             << actionOTE;
    autoConnectActions();
    Q_FOREACH(QAction *action, _actions)
      action->setProperty("subMenuName",
                          "Triangulated Surface Mesh Parameterization"
                          );
    dock_widget = new QDockWidget(
          "UVMapping "
          , mw);
    ui_widget.setupUi(dock_widget);
    dock_widget->setWindowTitle(tr(
                                  "UVMapping "
                                  ));
    graphics_scene = new QGraphicsScene(dock_widget);
    ui_widget.graphicsView->setScene(graphics_scene);
    ui_widget.graphicsView->setRenderHints(QPainter::Antialiasing);
    navigation = new Navigation();
    ui_widget.graphicsView->installEventFilter(navigation);
    ui_widget.graphicsView->viewport()->installEventFilter(navigation);
    ui_widget.component_numberLabel->setText("Component : 1");
    connect(ui_widget.prevButton, &QPushButton::clicked, this, &Polyhedron_demo_parameterization_plugin::on_prevButton_pressed);
    connect(ui_widget.nextButton, &QPushButton::clicked, this, &Polyhedron_demo_parameterization_plugin::on_nextButton_pressed);
    addDockWidget(dock_widget);
    dock_widget->setVisible(false);
    current_uv_item = NULL;
  }

  bool applicable(QAction*) const
  {
    if (scene->selectionIndices().size() == 1)
    {
    return qobject_cast<Scene_facegraph_item*>(scene->item(scene->mainSelectionIndex()))
        || qobject_cast<Scene_polyhedron_selection_item*>(scene->item(scene->mainSelectionIndex()));
    }

    Q_FOREACH(CGAL::Three::Scene_interface::Item_id id, scene->selectionIndices())
    {
      //if one facegraph is found in the selection, it's fine
      if (qobject_cast<Scene_facegraph_item*>(scene->item(id)))
        return true;
    }
    return false;
  }

  void closure()
  {
    dock_widget->hide();
  }

public Q_SLOTS:
  void on_actionMVC_triggered();
  void on_actionDCP_triggered();
  void on_actionLSC_triggered();
  void on_actionDAP_triggered();
  void on_actionARAP_triggered();
  void on_actionOTE_triggered();
  void on_actionBTP_triggered();
  void on_prevButton_pressed();
  void on_nextButton_pressed();

  void replacePolyline()
  {
    if(current_uv_item){
      Scene_textured_facegraph_item* t_item =
          qobject_cast<Scene_textured_facegraph_item*>(projections.key(current_uv_item));
     t_item->add_border_edges(std::vector<float>(0));
    }

    int id = scene->mainSelectionIndex();

    Q_FOREACH(UVItem* pl, projections)
    {
      if(pl==NULL || pl != projections[scene->item(id)])
        continue;
      current_uv_item = pl;
      break;
    }

    if(!current_uv_item)
    {
      dock_widget->setWindowTitle(tr("UVMapping"));
      ui_widget.component_numberLabel->setText(QString("Component :"));
    }
    else
    {
      if(!graphics_scene->items().empty())
        graphics_scene->removeItem(graphics_scene->items().first());

      graphics_scene->addItem(current_uv_item);
      ui_widget.graphicsView->fitInView(current_uv_item->boundingRect(),
                                        Qt::KeepAspectRatio);
      ui_widget.component_numberLabel->setText(
            QString("Component : %1/%2").arg(current_uv_item->current_component()+1)
            .arg(current_uv_item->number_of_components()));
      dock_widget->setWindowTitle(tr("UVMapping for %1")
                                  .arg(current_uv_item->item_name()));
      Scene_textured_facegraph_item* t_item =
          qobject_cast<Scene_textured_facegraph_item*>(projections.key(current_uv_item));
     t_item->add_border_edges(
            current_uv_item->concatenated_borders());
    }
  }

  void destroyPolyline(CGAL::Three::Scene_item* item)
  {
    Q_FOREACH(UVItem* pli, projections)
    {
      if(projections.key(pli) != item)
        continue;
      graphics_scene->removeItem(pli);
      delete pli;
      projections.remove(item);
      break;
    }

    if(projections.empty() || projections.first() == NULL)
    {
      current_uv_item = NULL;
      dock_widget->setWindowTitle(tr("UVMapping"));
      ui_widget.component_numberLabel->setText(QString("Component :"));
    }
    else
      current_uv_item = projections.first();
  }

protected:
  enum Parameterization_method { PARAM_MVC, PARAM_DCP, PARAM_LSC,
                                 PARAM_DAP, PARAM_ARAP, PARAM_OTE, PARAM_BTP};
  void parameterize(Parameterization_method method);

private:
  Messages_interface *messages;
  QList<QAction*> _actions;
  QDockWidget* dock_widget;
  Ui::Parameterization ui_widget;
  QGraphicsScene *graphics_scene;
  Navigation* navigation;
  QMap<Scene_item*, UVItem*> projections;
  UVItem* current_uv_item;
}; // end Polyhedron_demo_parameterization_plugin

void Polyhedron_demo_parameterization_plugin::on_prevButton_pressed()
{
  int id = scene->mainSelectionIndex();
  Q_FOREACH(UVItem* pl, projections)
  {
    if(pl==NULL
       || pl != projections[scene->item(id)])
      continue;

    current_uv_item = pl;
    break;
  }
  if(current_uv_item == NULL)
    return;
  current_uv_item->set_current_component((std::max)(0,current_uv_item->current_component()-1));
  replacePolyline();
}

void Polyhedron_demo_parameterization_plugin::on_nextButton_pressed()
{
  int id = scene->mainSelectionIndex();
  Q_FOREACH(UVItem* pl, projections)
  {
    if(pl==NULL
       || pl != projections[scene->item(id)])
      continue;

    current_uv_item = pl;
    break;
  }
  if(current_uv_item == NULL)
    return;
  current_uv_item->set_current_component((std::min)(current_uv_item->number_of_components()-1,current_uv_item->current_component()+1));
  ui_widget.component_numberLabel->setText(QString("Component : %1/%2").arg(current_uv_item->current_component()+1).arg(current_uv_item->number_of_components()));
  replacePolyline();
}

void Polyhedron_demo_parameterization_plugin::parameterize(const Parameterization_method method)
{
  // get active polyhedron
  Scene_facegraph_item* poly_item = NULL;
  CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();
  Q_FOREACH(CGAL::Three::Scene_interface::Item_id id, scene->selectionIndices())
  {
    poly_item = qobject_cast<Scene_facegraph_item*>(scene->item(id));
    if(!poly_item)
    {
      continue;
    }
    else
    {
      index = id;
      break;
    }
  }

  if(!poly_item)
  {
    CGAL::Three::Three::error("Selected item is not of the right type.");
    return;
  }

  Face_graph* pMesh = poly_item->face_graph();
  if(!pMesh)
  {
    CGAL::Three::Three::error("Selected item has no valid polyhedron.");
    return;
  }
  Scene_polyhedron_selection_item* sel_item = NULL;
  bool is_seamed = false;
  Q_FOREACH(CGAL::Three::Scene_interface::Item_id id, scene->selectionIndices())
  {
    sel_item = qobject_cast<Scene_polyhedron_selection_item*>(scene->item(id));
    if(!sel_item)
      continue;
    if(sel_item->selected_edges.empty())
      continue;
    if(method == PARAM_OTE && sel_item->selected_vertices.empty())
       continue;
    is_seamed = true;
  }

  if(method == PARAM_OTE &&
     (sel_item == NULL || sel_item->selected_vertices.empty())) {
    std::cerr << "\nError: no cones/seam selected; Aborting parameterization." << std::endl;
    return;
  }

  // Two property maps to store the seam edges and vertices
  Seam_edge_uhm seam_edge_uhm(false);
  Seam_edge_pmap seam_edge_pm(seam_edge_uhm);

  Seam_vertex_uhm seam_vertex_uhm(false);
  Seam_vertex_pmap seam_vertex_pm(seam_vertex_uhm);

  if(!is_seamed && is_closed(*pMesh))
  {
    CGAL::Three::Three::error("The selected mesh has no (real or virtual) border.");
    return;
  }

  QApplication::setOverrideCursor(Qt::WaitCursor);

  ///////////////////////////////////
  ////////// PARAMETERIZE ///////////
  ///////////////////////////////////

  QElapsedTimer time;
  time.start();
  // add textured polyhedon to the scene

  // \todo for surface_mesh
  Base_face_graph tMesh = *pMesh;
  std::vector<bool> mark(num_halfedges(tMesh)/2,false);
  std::vector<T_edge_descriptor> seam_edges;
  typedef boost::property_map<Base_face_graph, boost::vertex_index_t>::type VIDMap;
  VIDMap vidmap = get(boost::vertex_index, tMesh);
  if(is_seamed)
  {
    //create a textured_polyhedron edges selection from the ids of the corresponding vertices
    typedef boost::property_map<Base_face_graph, boost::halfedge_index_t>::type HIDMap;
    HIDMap hidmap = get(boost::halfedge_index, tMesh);
    for(P_edge_descriptor ed : sel_item->selected_edges)
    {
      boost::graph_traits<Face_graph>::vertex_descriptor a(source(ed, *pMesh)), b(target(ed, *pMesh));

      for(boost::graph_traits<Textured_face_graph>::edge_iterator it =
          edges(tMesh).begin(); it != edges(tMesh).end();
          ++it)
      {
        boost::graph_traits<Textured_face_graph>::vertex_descriptor ta(source(*it, tMesh)), tb(target(*it, tMesh));

        if((get(vidmap, ta) == get(vidmap, a) && get(vidmap,tb) == get(vidmap,b))
           ||
           (get(vidmap,ta) == get(vidmap,b) && get(vidmap,tb) == get(vidmap,a)))
        {
          T_edge_descriptor ted(*it);
          seam_edges.push_back(ted);
          break;
        }
      }

    }
    qDebug() << sel_item->selected_edges.size() << ", " << seam_edges.size();
    //fill seam mesh pmaps
    for(T_edge_descriptor ed : seam_edges)
    {
      T_halfedge_descriptor hd = halfedge(ed, tMesh);
      T_vertex_descriptor svd(source(hd, tMesh)), tvd(target(hd, tMesh));
      if(!is_border(ed, tMesh))
      {
        put(seam_edge_pm, ed, true);
        put(seam_vertex_pm, svd, true);
        put(seam_vertex_pm, tvd, true);
        mark[get(hidmap, hd)/2] = true;
      }
    }
  }

  // map the cones from the selection plugin to the textured polyhedron
  boost::unordered_set<T_vertex_descriptor> unordered_cones;
  if(method == PARAM_OTE) {
    for(P_vertex_descriptor vd : sel_item->selected_vertices) {
      boost::graph_traits<Face_graph>::vertex_descriptor pvd(vd);
      boost::graph_traits<Textured_face_graph>::vertex_iterator it = vertices(tMesh).begin(),
          end = vertices(tMesh).end();
      for(; it!=end; ++it) {
        boost::graph_traits<Textured_face_graph>::vertex_descriptor tvd(*it);
        if(get(vidmap, *it) == get(vidmap, pvd)) {
          unordered_cones.insert(tvd);
        }
      }
    }
  }
  Seam_mesh sMesh(tMesh, seam_edge_pm, seam_vertex_pm);
  sMesh.set_seam_edges_number(static_cast<s_edges_size_type>(seam_edges.size()));

  // The parameterized values
  UV_uhm uv_uhm;
  UV_pmap uv_pm(uv_uhm);

  QString new_item_name;
  //determine the different connected_components
  boost::container::flat_map<boost::graph_traits<Base_face_graph>::face_descriptor, int> face_component_map;
  boost::associative_property_map< boost::container::flat_map<s_face_descriptor, int> >
      fccmap(face_component_map);

  Is_selected_property_map edge_pmap(mark, &tMesh);

  int number_of_components =
      CGAL::Polygon_mesh_processing::connected_components(
        tMesh,
        fccmap,
        CGAL::Polygon_mesh_processing::parameters::edge_is_constrained_map(
          edge_pmap));

  // Next is the gathering of the border halfedges of the connected component.
  // It is wrong to pass the underlying mesh tMesh: a sphere split in half does
  // not have any border if border_halfedges() is run with tMesh.
  //
  // The proper way would be to completely redesign the plugin to use Seam meshes
  // everywhere. But that's not worth it. Instead, we abuse the fact that faces
  // are the same in tMesh and sMesh.

  // the SEAM MESH faces of each connected component
  SComponents s_components(number_of_components);

  for(boost::graph_traits<Base_face_graph>::face_iterator fit = faces(tMesh).begin();
      fit != faces(tMesh).end(); ++fit) {
    s_components.at(fccmap[*fit]).insert(s_face_descriptor(*fit));
  }

  // once per component
  std::vector<std::vector<float> >uv_borders;
  uv_borders.resize(number_of_components);

  // to track whether the components are successfully parameterized
  SMP::Error_code status = SMP::OK;

  for(int current_component=0; current_component<number_of_components; ++current_component)
  {
    std::vector<s_halfedge_descriptor> border;
    PMP::border_halfedges(s_components.at(current_component),
                          sMesh, std::back_inserter(border));

    std::cout << sMesh.number_of_seam_edges() << " seams" << std::endl;
    std::cout << (s_components.at(current_component)).size() << " faces" << std::endl;
    std::cout << border.size() << " border halfedges" << std::endl;

    // find longest border in the connected component
    s_halfedge_descriptor bhd; // a halfedge on the (possibly virtual) border
    boost::unordered_set<s_halfedge_descriptor> visited;
    FT result_len = 0;
    for(s_halfedge_descriptor hd : border)
    {
      assert(is_border(hd, sMesh));

      if(visited.find(hd) == visited.end())
      {
        FT len = 0;
        for(s_halfedge_descriptor haf : halfedges_around_face(hd, sMesh))
        {
          len += PMP::edge_length(haf, sMesh);
          visited.insert(haf);
        }

        if(result_len < len)
        {
          result_len = len;
          bhd = hd;
        }
      }
    }
    CGAL_postcondition(bhd != s_halfedge_descriptor());
    CGAL_postcondition(is_border(bhd, sMesh));
    typedef boost::property_map<Base_face_graph, boost::vertex_point_t>::type VPMap;
    VPMap vpmap =get(boost::vertex_point, tMesh);

    // collect the border edges for that connected component
    for(s_halfedge_descriptor haf : halfedges_around_face(bhd, sMesh))
    {
        uv_borders[current_component].push_back(get(vpmap, source(haf, tMesh)).x());
        uv_borders[current_component].push_back(get(vpmap, source(haf, tMesh)).y());
        uv_borders[current_component].push_back(get(vpmap, source(haf, tMesh)).z());

        uv_borders[current_component].push_back(get(vpmap, target(haf, tMesh)).x());
        uv_borders[current_component].push_back(get(vpmap, target(haf, tMesh)).y());
        uv_borders[current_component].push_back(get(vpmap, target(haf, tMesh)).z());
    }

    switch(method)
    {
    case PARAM_MVC:
    {
      std::cout << "Parameterize (MVC)..." << std::endl;
      new_item_name = tr("%1 (parameterized (MVC))").arg(poly_item->name());
      typedef SMP::Mean_value_coordinates_parameterizer_3<Seam_mesh> Parameterizer;
      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);
      break;
    }
    case PARAM_DCP:
    {
      new_item_name = tr("%1 (parameterized (DCP))").arg(poly_item->name());
      std::cout << "Parameterize (DCP)..." << std::endl;
      typedef SMP::Discrete_conformal_map_parameterizer_3<Seam_mesh> Parameterizer;
      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);
      break;
    }
    case PARAM_LSC:
    {
      new_item_name = tr("%1 (parameterized (LSC))").arg(poly_item->name());
      std::cout << "Parameterize (LSC)..." << std::endl;
      typedef SMP::LSCM_parameterizer_3<Seam_mesh> Parameterizer;
      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);
      break;
    }
    case PARAM_DAP:
    {
      new_item_name = tr("%1 (parameterized (DAP))").arg(poly_item->name());
      std::cout << "Parameterize (DAP)..." << std::endl;
      typedef SMP::Discrete_authalic_parameterizer_3<Seam_mesh> Parameterizer;
      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);
      break;
    }
    case PARAM_ARAP:
    {
      new_item_name = tr("%1 (parameterized (ARAP))").arg(poly_item->name());
      std::cout << "Parameterize (ARAP)..." << std::endl;
      FT lambda = 10000; // a big value to ensure the parameterization is ARAP (and not ASAP)
      typedef SMP::ARAP_parameterizer_3<Seam_mesh> Parameterizer;
      status = SMP::parameterize(sMesh, Parameterizer(lambda), bhd, uv_pm);
      break;
    }
    case PARAM_OTE:
    {
      new_item_name = tr("%1 (parameterized (OTE))").arg(poly_item->name());
      std::cout << "Parameterize (OTE)..." << std::endl;

      // OTE cannot handle multiple connected components right now
      // @todo (need to remove the assertions such as cones.size() == 4
      //        and check where and when cones are used (passed by ID, for ex.?))
      if(number_of_components != 1) {
        std::cerr << "Orbifold Tutte Embedding can only handle one connected component" << std::endl;
        status = SMP::ERROR_NO_TOPOLOGICAL_BALL;
        break;
      }

      typedef SMP::Orbifold_Tutte_parameterizer_3<Seam_mesh> Parameterizer;

      // Get orbifold type
      QDialog dialog(mw);
      Ui::OTE_dialog ui;
      ui.setupUi(&dialog);
      connect(ui.buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
      connect(ui.buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));

      QApplication::restoreOverrideCursor();

      int i = dialog.exec();
      if (i == QDialog::Rejected)
      {
        std::cout << "Aborting parameterization" << std::endl;
        QApplication::restoreOverrideCursor();
        return;
      }

      SMP::Orbifold_type orb = static_cast<SMP::Orbifold_type>(ui.OrbComboBox->currentIndex());
      std::cout << "Selected orbifold type: " << ui.OrbComboBox->currentText().toStdString() << std::endl;

      if((unordered_cones.size() != 3 && unordered_cones.size() != 4) ||
         (unordered_cones.size() == 3 && orb == SMP::Parallelogram ) ||
         (unordered_cones.size() == 4 && orb != SMP::Parallelogram)) {
        std::cerr << "Error: incompatible orbifold type and number of cones" << std::endl;
        std::cerr << "Types I, II & III require 3 selected vertices" << std::endl;
        std::cerr << "Type IV requires 4 selected vertices" << std::endl;
        QApplication::restoreOverrideCursor();
        return;
      }

      // Now, parameterize
      Parameterizer parameterizer(orb);

      // Mark cones in the seam mesh
      boost::unordered_map<s_vertex_descriptor, SMP::Cone_type> cmap;
      if(!SMP::locate_unordered_cones(sMesh, unordered_cones.begin(), unordered_cones.end(), cmap))
      {
        std::cerr << "Error: invalid cone or seam selection" << std::endl;
        QApplication::restoreOverrideCursor();
        return;
      }

      QApplication::setOverrideCursor(Qt::WaitCursor);

      // Fill the index property map
      typedef boost::unordered_map<s_vertex_descriptor, int> Indices;
      Indices indices;
      CGAL::Polygon_mesh_processing::connected_component(
             face(opposite(bhd, sMesh), sMesh),
             sMesh,
             boost::make_function_output_iterator(
             SMP::internal::Index_map_filler<Seam_mesh, Indices>(sMesh, indices)));
      boost::associative_property_map<Indices> vimap(indices);

      // Call to parameterizer
      status = parameterizer.parameterize(sMesh, bhd, cmap, uv_pm, vimap);
      break;
    }
    case PARAM_BTP:
    {
      std::cout << "Parameterize (BTP)..." << std::endl;
      new_item_name = tr("%1 (parameterized (BTP))").arg(poly_item->name());
      typedef SMP::Barycentric_mapping_parameterizer_3<Seam_mesh> Parameterizer;
      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);
      break;
    }
    } //end switch

    std::cout << "Connected component " << current_component << ": ";
    if(status == SMP::OK) {
      std::cout << "success (in " << time.elapsed() << " ms)" << std::endl;
    } else {
      std::cerr << "failure: " << SMP::get_error_message(status) << std::endl;
      QApplication::restoreOverrideCursor();
      return;
    }

    if(status != SMP::OK)
      break;

  } //end for each component

  QApplication::restoreOverrideCursor();
  QPointF pmin(FLT_MAX, FLT_MAX), pmax(-FLT_MAX, -FLT_MAX);

  SMesh::Property_map<halfedge_descriptor, float> umap;
  SMesh::Property_map<halfedge_descriptor, float> vmap;

  umap = tMesh.add_property_map<halfedge_descriptor, float>("h:u", 0.0f).first;
  vmap = tMesh.add_property_map<halfedge_descriptor, float>("h:v", 0.0f).first;

  tMesh.property_stats(std::cerr);
  Base_face_graph::Halfedge_iterator it;
  for(it = tMesh.halfedges_begin();
      it != tMesh.halfedges_end();
      ++it)
  {
    Seam_mesh::halfedge_descriptor hd(*it);
    FT u = uv_pm[target(hd, sMesh)].x();
    FT v = uv_pm[target(hd, sMesh)].y();
    put(umap, *it, static_cast<float>(u));
    put(vmap, *it, static_cast<float>(v));
    if(u<pmin.x())
      pmin.setX(u);
    if(u>pmax.x())
      pmax.setX(u);
    if(v<pmin.y())
      pmin.setY(v);
    if(v>pmax.y())
      pmax.setY(v);
  }

  Components* components = new Components(0);
  components->resize(number_of_components);
  boost::graph_traits<Base_face_graph>::face_iterator bfit;

  for(bfit = faces(tMesh).begin();
      bfit != faces(tMesh).end();
      ++bfit)
  {
    components->at(fccmap[*bfit]).insert(*bfit);
  }

  Scene_textured_facegraph_item* new_item = new Scene_textured_facegraph_item(tMesh);
  UVItem *projection = new UVItem(components,new_item->textured_face_graph(), uv_borders, QRectF(pmin, pmax));
  projection->set_item_name(new_item_name);

  new_item->setName(new_item_name);
  new_item->setColor(Qt::white);
  new_item->setRenderingMode(poly_item->renderingMode());
  connect( new_item, SIGNAL(selectionChanged()),
           this, SLOT(replacePolyline()) );
  poly_item->setVisible(false);
  scene->itemChanged(index);
  scene->addItem(new_item);
  if(!graphics_scene->items().empty())
    graphics_scene->removeItem(graphics_scene->items().first());
  graphics_scene->addItem(projection);
  projections[new_item] = projection;
  if(current_uv_item){
    Scene_textured_facegraph_item* t_item =
        qobject_cast<Scene_textured_facegraph_item*>(projections.key(current_uv_item));
   t_item->add_border_edges(std::vector<float>(0));
  }
  current_uv_item = projection;
  Scene_textured_facegraph_item* t_item =
      qobject_cast<Scene_textured_facegraph_item*>(projections.key(current_uv_item));
  t_item->add_border_edges(
        current_uv_item->concatenated_borders());
  if(dock_widget->isHidden()){
    dock_widget->setVisible(true);
    dock_widget->raise();
  }
  dock_widget->setWindowTitle(tr("UVMapping for %1").arg(new_item->name()));
  ui_widget.component_numberLabel->setText(QString("Component : %1/%2").arg(current_uv_item->current_component()+1).arg(current_uv_item->number_of_components()));
  ui_widget.graphicsView->fitInView(projection->boundingRect(), Qt::KeepAspectRatio);

  QApplication::restoreOverrideCursor();

}

void Polyhedron_demo_parameterization_plugin::on_actionMVC_triggered()
{
  std::cerr << "MVC...";
  parameterize(PARAM_MVC);
}

void Polyhedron_demo_parameterization_plugin::on_actionDCP_triggered()
{
  std::cerr << "DCP...";
  parameterize(PARAM_DCP);
}

void Polyhedron_demo_parameterization_plugin::on_actionLSC_triggered()
{
  std::cerr << "LSC...";
  parameterize(PARAM_LSC);
}

void Polyhedron_demo_parameterization_plugin::on_actionDAP_triggered()
{
  std::cerr << "DAP...";
  parameterize(PARAM_DAP);
}

void Polyhedron_demo_parameterization_plugin::on_actionARAP_triggered()
{
  std::cerr << "ARAP...";
  parameterize(PARAM_ARAP);
}

void Polyhedron_demo_parameterization_plugin::on_actionOTE_triggered()
{
  std::cerr << "OTE...";
  parameterize(PARAM_OTE);
}

void Polyhedron_demo_parameterization_plugin::on_actionBTP_triggered()
{
  std::cerr << "BTP...";
  parameterize(PARAM_BTP);
}

#include "Parameterization_plugin.moc"

{'repo_name': 'CGAL/cgal', 'stars': '1973', 'repo_language': 'C++', 'file_name': 'license.txt', 'mime_type': 'text/plain', 'hash': -4944092119108067501, 'source_dataset': 'data'}


class Icon
{
   public var height:Int;
   public var path:String;
   public var size:Int;
   public var width:Int;

   public function new(path:String, size:Int = 0)
   {
      this.path = path;
      this.size = height = width = size;
   }

   public function clone():Icon
   {
      var icon = new Icon(path);
      icon.size = size;
      icon.width = width;
      icon.height = height;

      return icon;
   }
}

{'repo_name': 'haxenme/nme', 'stars': '413', 'repo_language': 'C', 'file_name': 'build.nmml', 'mime_type': 'text/xml', 'hash': 2266525818899488901, 'source_dataset': 'data'}


-module(mzb_pipeline).

-behaviour(gen_server).

-export([
    start_link/3,
    call/2,
    call/3,
    cast/2,
    stop/1,
    reply/2,
    error/2,
    init/1,
    handle_call/3,
    handle_cast/2,
    handle_info/2,
    terminate/2,
    code_change/3
]).

-record(state, {stage       = undefined :: undefined | {pid(), atom(), atom()},
                module      = undefined :: undefined | module(),
                ref         = undefined :: undefined | reference(),
                prefinal    = false :: boolean(),
                user_state  = undefined :: term(),
                active      = true :: boolean()}).

-callback init(Args :: term()) ->
    {ok, State :: term()} | {ok, State :: term(), timeout() | hibernate} |
    {stop, Reason :: term()} | ignore.
-callback workflow_config(State :: term()) ->
    [{pipeline | finalize, [Stage :: atom()]}].
-callback handle_stage(Pipeline :: atom(), Stage :: atom(), State :: term()) ->
    fun ((State :: term()) ->  NewState :: term()) | ok.
-callback handle_pipeline_status(Status :: term(), State :: term()) ->
    NewState :: term().
-callback handle_call(Request :: term(), From :: {pid(), Tag :: term()},
                      State :: term()) ->
    {reply, Reply :: term(), NewState :: term()} |
    {reply, Reply :: term(), NewState :: term(), timeout() | hibernate} |
    {noreply, NewState :: term()} |
    {noreply, NewState :: term(), timeout() | hibernate} |
    {stop, Reason :: term(), Reply :: term(), NewState :: term()} |
    {stop, Reason :: term(), NewState :: term()}.
-callback handle_cast(Request :: term(), State :: term()) ->
    {noreply, NewState :: term()} |
    {noreply, NewState :: term(), timeout() | hibernate} |
    {stop, Reason :: term(), NewState :: term()}.
-callback handle_info(Info :: timeout() | term(), State :: term()) ->
    {noreply, NewState :: term()} |
    {noreply, NewState :: term(), timeout() | hibernate} |
    {stop, Reason :: term(), NewState :: term()}.
-callback terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
                    State :: term()) ->
    term().

start_link(Module, Args, Options) ->
    gen_server:start_link(?MODULE, [Module, Args], Options).

call(ServerRef, Request) ->
    gen_server:call(ServerRef, {user_call, Request}).

call(ServerRef, Request, Timeout) ->
    gen_server:call(ServerRef, {user_call, Request}, Timeout).

cast(ServerRef, Msg) ->
    gen_server:cast(ServerRef, {user_cast, Msg}).

stop(ServerRef) ->
    gen_server:call(ServerRef, {workflow, stop}).

reply(Client, Reply) ->
    gen_server:reply(Client, Reply).

init([Module, UserArgs]) ->
    Ref = make_ref(),
    case Module:init(UserArgs) of
        {ok, UserState} ->
            ok = gen_server:cast(self(), {workflow, start_phase, pipeline, Ref}),
            {ok, #state{module = Module, user_state = UserState, ref = Ref}};
        {ok, UserState, Timeout} ->
            ok = gen_server:cast(self(), {workflow, start_phase, pipeline, Ref}),
            {ok, #state{module = Module, user_state = UserState, ref = Ref}, Timeout};
        {stop, Reason} -> {stop, Reason};
        ignore -> ignore
    end.

-spec error(Reason :: term(), Fun :: undefined | fun()) -> no_return().
error(Reason, Fun) ->
    erlang:error({exception, Reason, Fun}).

handle_call({workflow, stop}, _From, State = #state{active = false}) ->
    {reply, ok, State};

handle_call({workflow, stop}, _From, State = #state{stage = Stage, module = Module,
            user_state = UserState, ref = OldRef}) ->
    PreFinal = case Stage of
        {Pid, pipeline, S} ->
            case lists:member(S, proplists:get_value(unstoppable, Module:workflow_config(UserState), [])) of
                false -> unlink(Pid),
                         exit(Pid, kill),
                         false;
                true -> true
            end;
        _ -> false
    end,
    NewRef = case PreFinal of
        false -> TRef = make_ref(),
                 gen_server:cast(self(), {workflow, start_phase, finalize, TRef}),
                 TRef;
        true -> OldRef
    end,
    NewState = change_pipeline_status({final, stopped}, State),
    {reply, ok, NewState#state{ref = NewRef, prefinal = PreFinal}};

handle_call({user_call, Msg}, From, #state{module = Module, user_state = UserState} = State) ->
    apply_user_state(Module:handle_call(Msg, From, UserState), State);

handle_call(_Unhandled, _From, State) ->
    {noreply, State}.

handle_cast({workflow, exception, Phase = finalize, Stage, Ref, {_C, E, ST, Fn} }, State = #state{ref = Ref}) ->
    NewState0 = migrate_state(Fn, State),
    gen_server:cast(self(), {workflow, next, finalize, Stage, Ref}),
    NewState1 = change_pipeline_status({exception, Phase, Stage, E, ST}, NewState0),
    {noreply, NewState1#state{stage = undefined}};

handle_cast({workflow, exception, Phase = pipeline, Stage, Ref, {_C, E, ST, Fn} }, State = #state{ref = Ref}) ->
    NewState0 = migrate_state(Fn, State),
    gen_server:cast(self(), {workflow, start_phase, finalize, Ref}),
    NewState1 = change_pipeline_status({exception, Phase, Stage, E, ST}, NewState0),
    NewState2 = change_pipeline_status({final, failed}, NewState1),
    {noreply, NewState2#state{stage = undefined}};

handle_cast({workflow, complete, _Phase, _Stage, Ref, Fn},
            State = #state{prefinal = true, ref = Ref}) ->
    NewState = migrate_state(Fn, State),
    gen_server:cast(self(), {workflow, start_phase, finalize, Ref}),
    {noreply, NewState#state{prefinal = false}};

handle_cast({workflow, complete, Phase, Stage, Ref, Fn}, State = #state{ref = Ref}) ->
    NewState0 = migrate_state(Fn, State),
    NewState1 = change_pipeline_status({complete, Phase, Stage}, NewState0),

    gen_server:cast(self(), {workflow, next, Phase, Stage, Ref}),
    NewState2 = case is_last_stage(Phase, Stage, NewState1) of
        true when Phase == pipeline ->
            change_pipeline_status({final, complete}, NewState1);
        _ -> NewState1
    end,
    NewState3 = NewState2#state{stage = undefined},

    {noreply, NewState3};

handle_cast({workflow, start_phase, Phase, Ref}, State = #state{ref = Ref}) ->
    handle_cast({workflow, next, Phase, undefined, Ref}, State);

handle_cast({workflow, next, PrevPhase, PrevStage, Ref}, State = #state{ref = Ref}) ->
    case next_stage(PrevPhase, PrevStage, State) of
        none ->
            {stop, normal, State};
        {ok, NextPhase, NextStage} ->
            gen_server:cast(self(), {workflow, start, NextPhase, NextStage, Ref}),
            {noreply, State}
    end;

handle_cast({workflow, start, Phase, Stage, Ref}, State = #state{ref = Ref, module = Module, user_state = UserState}) ->
    Self = self(),
    Pid = spawn_link(
        fun () ->
            try
                StageResult = Module:handle_stage(Phase, Stage, UserState),
                gen_server:cast(Self, {workflow, complete, Phase, Stage, Ref, StageResult})
            catch
                C:{exception, E, Fn} ->
                    ST = erlang:get_stacktrace(),
                    gen_server:cast(Self, {workflow, exception, Phase, Stage, Ref, {C, E, ST, Fn}});
                C:E ->
                    ST = erlang:get_stacktrace(),
                    gen_server:cast(Self, {workflow, exception, Phase, Stage, Ref, {C, E, ST, undefined}})
            end
        end),
    NewState = change_pipeline_status({start, Phase, Stage}, State),
    {noreply, NewState#state{stage = {Pid, Phase, Stage}}};

handle_cast({user_cast, Msg}, #state{module = Module, user_state = UserState} = State) ->
    apply_user_state(Module:handle_cast(Msg, UserState), State);

handle_cast(_Unhandled, State) ->
    {noreply, State}.

handle_info(Msg, #state{module = Module, user_state = UserState} = State) ->
    apply_user_state(Module:handle_info(Msg, UserState), State).

terminate(Reason, #state{module = Module, user_state = UserState}) ->
    Module:terminate(Reason, UserState).

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%%%===================================================================
%%% Internal functions
%%%===================================================================

change_pipeline_status(Status, #state{module = Module, user_state = UserState} = State) ->
    NewState = case Status of
                   {_, pipeline, _} -> State;
                   _ -> State#state{active = false}
               end,
    NewUserState = Module:handle_pipeline_status(Status, UserState),
    NewState#state{user_state = NewUserState}.

apply_user_state({reply, Reply, UserState}, State) -> {reply, Reply, State#state{user_state = UserState}};
apply_user_state({reply, Reply, UserState, Timeout}, State) -> {reply, Reply, State#state{user_state = UserState}, Timeout};
apply_user_state({noreply, UserState}, State) -> {noreply, State#state{user_state = UserState}};
apply_user_state({noreply, UserState, Timeout}, State) -> {noreply, State#state{user_state = UserState}, Timeout};
apply_user_state({stop, Reason, Reply, UserState}, State) -> {stop, Reason, Reply, State#state{user_state = UserState}};
apply_user_state({stop, Reason, UserState}, State) -> {stop, Reason, State#state{user_state = UserState}}.

next_stage(Phase, undefined, #state{module = Module, user_state = UserState} = State) ->
    Stages = proplists:get_value(Phase, Module:workflow_config(UserState), []),
    pick_stage(Phase, Stages, State);
next_stage(Phase, CurrentStage, #state{module = Module, user_state = UserState} = State) when CurrentStage /= undefined ->
    Stages = proplists:get_value(Phase, Module:workflow_config(UserState), []),
    [CurrentStage | RemainStages] = lists:dropwhile(fun(S) -> (S /= CurrentStage) end, Stages),
    pick_stage(Phase, RemainStages, State).

is_last_stage(Phase, Stage, #state{module = Module, user_state = UserState}) ->
    Stages = proplists:get_value(Phase, Module:workflow_config(UserState), []),
    case lists:reverse(Stages) of
        [Stage | _Rest] -> true;
        _ -> false
    end.

pick_stage(finalize, [], _) -> none;
pick_stage(pipeline, [], State) -> next_stage(finalize, undefined, State);
pick_stage(Phase, [NextStage | _Rest], _) -> {ok, Phase, NextStage}.

migrate_state(Fn, #state{user_state = UserState} = State) when is_function(Fn) ->
    State#state{user_state = Fn(UserState)};
migrate_state(_, State) -> State.

{'repo_name': 'satori-com/mzbench', 'stars': '234', 'repo_language': 'Erlang', 'file_name': 'mzb_api_auth_tests.erl', 'mime_type': 'text/plain', 'hash': 5131370437211608997, 'source_dataset': 'data'}


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

#import <AppKit/NSVisualEffectView.h>

@interface TDefaultVibrancyVisualEffectView : NSVisualEffectView
{
}

- (BOOL)allowsVibrancy;

@end

{'repo_name': 'w0lfschild/macOS_headers', 'stars': '304', 'repo_language': 'None', 'file_name': 'NSTextFinderBarContainer-Protocol.h', 'mime_type': 'text/x-objective-c', 'hash': 505643639102218365, 'source_dataset': 'data'}


/*
    ChibiOS/RT - Copyright (C) 2006-2013 Giovanni Di Sirio

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

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

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

/**
 * TMP75 is most simple I2C device in our case. It is already useful with
 * default settings after powerup.
 * You only must read 2 sequential bytes from it.
 */

#include <stdlib.h>

#include "ch.h"
#include "hal.h"

#include "tmp75.h"

/* input buffer */
static uint8_t tmp75_rx_data[TMP75_RX_DEPTH];

/* temperature value */
static int16_t temperature = 0;

static i2cflags_t errors = 0;

#define tmp75_addr 0b1001000

/* This is main function. */
void request_temperature(void){
  int16_t t_int = 0, t_frac = 0;
  msg_t status = RDY_OK;
  systime_t tmo = MS2ST(4);

  i2cAcquireBus(&I2CD1);
  status = i2cMasterReceiveTimeout(&I2CD1, tmp75_addr, tmp75_rx_data, 2, tmo);
  i2cReleaseBus(&I2CD1);

  if (status != RDY_OK){
    errors = i2cGetErrors(&I2CD1);
  }

  t_int = tmp75_rx_data[0] * 100;
  t_frac = (tmp75_rx_data[1] * 100) >> 8;
  temperature = t_int + t_frac;
}

{'repo_name': 'sharebrained/portapack-hackrf', 'stars': '446', 'repo_language': 'C', 'file_name': 'portapack_h1_cpld.svf', 'mime_type': 'text/plain', 'hash': -1762319706199252339, 'source_dataset': 'data'}


/*
 * Copyright (C) 2011-2012 Sansar Choinyambuu, Andreas Steffen
 * HSR Hochschule fuer Technik Rapperswil
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 */

/**
 * @defgroup pts_comp_func_name pts_comp_func_name
 * @{ @ingroup pts
 */

#ifndef PTS_FUNC_COMP_NAME_H_
#define PTS_FUNC_COMP_NAME_H_

typedef struct pts_comp_func_name_t pts_comp_func_name_t;

#include <library.h>

#define PTS_QUALIFIER_UNKNOWN		0x00
#define PTS_QUALIFIER_WILDCARD		0x3F

/**
 * PTS Component Functional Name object
 */
struct pts_comp_func_name_t {

	/**
	 * Get the PTS Component Functional Name Vendor ID
	 *
	 * @return				PTS Component Functional Name Vendor ID
	 */
	uint32_t (*get_vendor_id)(pts_comp_func_name_t *this);

	/**
	 * Get the PTS Component Functional Name
	 *
	 * @return				PTS Component Functional Name
	 */
	uint32_t (*get_name)(pts_comp_func_name_t *this);

	/**
	 * Get the PTS Component Functional Name Qualifier
	 *
	 * @return				PTS Component Functional Name Qualifier
	 */
	uint8_t (*get_qualifier)(pts_comp_func_name_t *this);

	/**
	 * Set the PTS Component Functional Name Qualifier
	 *
	 * @param qualifier		PTS Component Functional Name Qualifier to be set
	 */
	void (*set_qualifier)(pts_comp_func_name_t *this, uint8_t qualifier);

	/**
	 * Check to PTS Component Functional Names for equality
	 *
	 * @param other			Other PTS Component Functional Name
	 * @return				TRUE if equal
	 */
	bool (*equals)(pts_comp_func_name_t *this, pts_comp_func_name_t *other);

	/**
	 * Clone a PTS Component Functional Name
	 *
	 * @return				Cloned PTS Component Functional Name
	 */
	pts_comp_func_name_t* (*clone)(pts_comp_func_name_t *this);

	/**
	 * Write PTS Component Functional Name information to the standard logfile
	 *
	 * @param label			Label added to log output
	 */
	void (*log)(pts_comp_func_name_t *this, char *label);

	/**
	 * Destroys a pts_component_t object.
	 */
	void (*destroy)(pts_comp_func_name_t *this);

};

/**
 * Create a PTS Component Functional Name object
 *
 * @param vid				PTS Component Functional Name Vendor ID
 * @param name				PTS Component Functional Name
 * @param qualifier			PTS Component Functional Name Qualifier
 */
pts_comp_func_name_t* pts_comp_func_name_create(uint32_t vid, uint32_t name,
												uint8_t qualifier);

#endif /** PTS_FUNC_COMP_NAME_H_ @}*/

{'repo_name': 'strongswan/strongswan', 'stars': '973', 'repo_language': 'C', 'file_name': 'rfc5996.txt', 'mime_type': 'text/plain', 'hash': 7267139643630401385, 'source_dataset': 'data'}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.ignite.internal.processors.cache.distributed.near;

import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.locks.Lock;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.events.Event;
import org.apache.ignite.internal.util.typedef.P1;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteFuture;
import org.apache.ignite.testframework.MvccFeatureChecker;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.events.EventType.EVT_NODE_FAILED;
import static org.apache.ignite.events.EventType.EVT_NODE_LEFT;

/**
 * Tests for node failure in transactions.
 */
public class GridCachePartitionedExplicitLockNodeFailureSelfTest extends GridCommonAbstractTest {
    /** */
    public static final int GRID_CNT = 4;

    /** {@inheritDoc} */
    @Override public void beforeTest() throws Exception {
        MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.ENTRY_LOCK);
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration c = super.getConfiguration(igniteInstanceName);

        c.getTransactionConfiguration().setTxSerializableEnabled(true);

        CacheConfiguration cc = defaultCacheConfiguration();

        cc.setCacheMode(PARTITIONED);
        cc.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
        cc.setBackups(GRID_CNT - 1);
        cc.setAtomicityMode(TRANSACTIONAL);
        cc.setNearConfiguration(new NearCacheConfiguration());

        c.setCacheConfiguration(cc);

        return c;
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        super.afterTest();

        stopAllGrids();
    }

    /** @throws Exception If check failed. */
    @SuppressWarnings("ErrorNotRethrown")
    @Test
    public void testLockFromNearOrBackup() throws Exception {
        startGrids(GRID_CNT);

        awaitPartitionMapExchange();

        int idx = 0;

        info("Grid will be stopped: " + idx);

        Integer key = 0;

        while (grid(idx).affinity(DEFAULT_CACHE_NAME).mapKeyToNode(key).id().equals(grid(0).localNode().id()))
            key++;

        ClusterNode node = grid(idx).affinity(DEFAULT_CACHE_NAME).mapKeyToNode(key);

        info("Primary node for key [id=" + node.id() + ", order=" + node.order() + ", key=" + key + ']');

        IgniteCache<Integer, String> cache = jcache(idx);

        cache.put(key, "val");

        Lock lock = cache.lock(key);

        assert lock.tryLock();

        for (int checkIdx = 1; checkIdx < GRID_CNT; checkIdx++) {
            info("Check grid index: " + checkIdx);

            IgniteCache<Integer, String> checkCache = jcache(checkIdx);

            assert !checkCache.lock(key).tryLock();
        }

        Collection<IgniteFuture<?>> futs = new LinkedList<>();

        for (int i = 1; i < GRID_CNT; i++) {
            futs.add(
                waitForLocalEvent(grid(i).events(), new P1<Event>() {
                    @Override public boolean apply(Event e) {
                        info("Received grid event: " + e);

                        return true;
                    }
                }, EVT_NODE_LEFT, EVT_NODE_FAILED));
        }

        stopGrid(idx);

        for (IgniteFuture<?> fut : futs)
            fut.get();

        for (int i = 0; i < 3; i++) {
            try {
                for (int checkIdx = 1; checkIdx < GRID_CNT; checkIdx++) {
                    info("Check grid index: " + checkIdx);

                    IgniteCache<Integer, String> checkCache = jcache(checkIdx);

                    assert !checkCache.isLocalLocked(key, false);
                }
            }
            catch (AssertionError e) {
                if (i == 2)
                    throw e;

                U.warn(log, "Check failed (will retry in 1000 ms): " + e.getMessage());

                U.sleep(1000);

                continue;
            }

            // Check passed on all grids.
            break;
        }
    }
}

{'repo_name': 'apache/ignite', 'stars': '3329', 'repo_language': 'Java', 'file_name': 'checkstyle.xml', 'mime_type': 'text/xml', 'hash': -6617278983471122056, 'source_dataset': 'data'}


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

// +build !windows,!nacl,!plan9

package log

import (
	"fmt"
	"log/syslog"
	"os"

	"github.com/sirupsen/logrus"
)

var _ logrus.Formatter = (*syslogger)(nil)

func init() {
	setSyslogFormatter = func(l logger, appname, local string) error {
		if appname == "" {
			return fmt.Errorf("missing appname parameter")
		}
		if local == "" {
			return fmt.Errorf("missing local parameter")
		}

		fmter, err := newSyslogger(appname, local, l.entry.Logger.Formatter)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error creating syslog formatter: %v\n", err)
			l.entry.Errorf("can't connect logger to syslog: %v", err)
			return err
		}
		l.entry.Logger.Formatter = fmter
		return nil
	}
}

var prefixTag []byte

type syslogger struct {
	wrap logrus.Formatter
	out  *syslog.Writer
}

func newSyslogger(appname string, facility string, fmter logrus.Formatter) (*syslogger, error) {
	priority, err := getFacility(facility)
	if err != nil {
		return nil, err
	}
	out, err := syslog.New(priority, appname)
	_, isJSON := fmter.(*logrus.JSONFormatter)
	if isJSON {
		// add cee tag to json formatted syslogs
		prefixTag = []byte("@cee:")
	}
	return &syslogger{
		out:  out,
		wrap: fmter,
	}, err
}

func getFacility(facility string) (syslog.Priority, error) {
	switch facility {
	case "0":
		return syslog.LOG_LOCAL0, nil
	case "1":
		return syslog.LOG_LOCAL1, nil
	case "2":
		return syslog.LOG_LOCAL2, nil
	case "3":
		return syslog.LOG_LOCAL3, nil
	case "4":
		return syslog.LOG_LOCAL4, nil
	case "5":
		return syslog.LOG_LOCAL5, nil
	case "6":
		return syslog.LOG_LOCAL6, nil
	case "7":
		return syslog.LOG_LOCAL7, nil
	}
	return syslog.LOG_LOCAL0, fmt.Errorf("invalid local(%s) for syslog", facility)
}

func (s *syslogger) Format(e *logrus.Entry) ([]byte, error) {
	data, err := s.wrap.Format(e)
	if err != nil {
		fmt.Fprintf(os.Stderr, "syslogger: can't format entry: %v\n", err)
		return data, err
	}
	// only append tag to data sent to syslog (line), not to what
	// is returned
	line := string(append(prefixTag, data...))

	switch e.Level {
	case logrus.PanicLevel:
		err = s.out.Crit(line)
	case logrus.FatalLevel:
		err = s.out.Crit(line)
	case logrus.ErrorLevel:
		err = s.out.Err(line)
	case logrus.WarnLevel:
		err = s.out.Warning(line)
	case logrus.InfoLevel:
		err = s.out.Info(line)
	case logrus.DebugLevel:
		err = s.out.Debug(line)
	default:
		err = s.out.Notice(line)
	}

	if err != nil {
		fmt.Fprintf(os.Stderr, "syslogger: can't send log to syslog: %v\n", err)
	}

	return data, err
}

{'repo_name': 'nmnellis/vistio', 'stars': '341', 'repo_language': 'JavaScript', 'file_name': 'trace_go16.go', 'mime_type': 'text/plain', 'hash': -2438413850128153327, 'source_dataset': 'data'}


Flask==0.10.1
Flask-HTTPAuth==2.2.1
Flask-Admin==1.0.7
Flask-SQLAlchemy==1.0
Jinja2==2.7.2
MarkupSafe==0.19
SQLAlchemy==0.9.4
WTForms==1.0.5
Werkzeug==0.9.4
itsdangerous==0.24
wsgiref==0.1.2
click==0.7
sphinx-rtd-theme==0.1.6

{'repo_name': 'jeffknupp/sandman', 'stars': '2322', 'repo_language': 'Python', 'file_name': 'CreateSqlite.bat', 'mime_type': 'text/x-msdos-batch', 'hash': 1082000599621434071, 'source_dataset': 'data'}


/*
*

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

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

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

package railo.runtime.img.filter;import java.awt.Rectangle;
import java.awt.image.BufferedImage;

import railo.runtime.engine.ThreadLocalPageContext;
import railo.runtime.exp.FunctionException;
import railo.runtime.exp.PageException;
import railo.runtime.img.ImageUtil;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.Struct;
import railo.runtime.type.util.CollectionUtil;

/**
 * A filter which uses Floyd-Steinberg error diffusion dithering to halftone an image.
 */
public class DiffusionFilter extends WholeImageFilter  implements DynFiltering {

	private final static int[] diffusionMatrix = {
	 	 0, 0, 0,
	 	 0, 0, 7,
	 	 3, 5, 1,
	};

	private int[] matrix;
	private int sum = 3+5+7+1;
	private boolean serpentine = true;
	private boolean colorDither = true;
	private int levels = 6;

	/**
	 * Construct a DiffusionFilter.
	 */
	public DiffusionFilter() {
		setMatrix(diffusionMatrix);
	}

	/**
	 * Set whether to use a serpentine pattern for return or not. This can reduce 'avalanche' artifacts in the output.
	 * @param serpentine true to use serpentine pattern
     * @see #getSerpentine
	 */
	public void setSerpentine(boolean serpentine) {
		this.serpentine = serpentine;
	}

	/**
	 * Return the serpentine setting.
	 * @return the current setting
     * @see #setSerpentine
	 */
	public boolean getSerpentine() {
		return serpentine;
	}

	/**
	 * Set whether to use a color dither.
	 * @param colorDither true to use a color dither
     * @see #getColorDither
	 */
	public void setColorDither(boolean colorDither) {
		this.colorDither = colorDither;
	}

	/**
	 * Get whether to use a color dither.
	 * @return true to use a color dither
     * @see #setColorDither
	 */
	public boolean getColorDither() {
		return colorDither;
	}

	/**
	 * Set the dither matrix.
	 * @param matrix the dither matrix
     * @see #getMatrix
	 */
	public void setMatrix(int[] matrix) {
		this.matrix = matrix;
		sum = 0;
		for (int i = 0; i < matrix.length; i++)
			sum += matrix[i];
	}

	/**
	 * Get the dither matrix.
	 * @return the dither matrix
     * @see #setMatrix
	 */
	public int[] getMatrix() {
		return matrix;
	}

	/**
	 * Set the number of dither levels.
	 * @param levels the number of levels
     * @see #getLevels
	 */
	public void setLevels(int levels) {
		this.levels = levels;
	}

	/**
	 * Get the number of dither levels.
	 * @return the number of levels
     * @see #setLevels
	 */
	public int getLevels() {
		return levels;
	}

	protected int[] filterPixels( int width, int height, int[] inPixels, Rectangle transformedSpace ) {
		int[] outPixels = new int[width * height];

		int index = 0;
		int[] map = new int[levels];
		for (int i = 0; i < levels; i++) {
			int v = 255 * i / (levels-1);
			map[i] = v;
		}
		int[] div = new int[256];
		for (int i = 0; i < 256; i++)
			div[i] = levels*i / 256;

		for (int y = 0; y < height; y++) {
			boolean reverse = serpentine && (y & 1) == 1;
			int direction;
			if (reverse) {
				index = y*width+width-1;
				direction = -1;
			} else {
				index = y*width;
				direction = 1;
			}
			for (int x = 0; x < width; x++) {
				int rgb1 = inPixels[index];

				int r1 = (rgb1 >> 16) & 0xff;
				int g1 = (rgb1 >> 8) & 0xff;
				int b1 = rgb1 & 0xff;

				if (!colorDither)
					r1 = g1 = b1 = (r1+g1+b1) / 3;

				int r2 = map[div[r1]];
				int g2 = map[div[g1]];
				int b2 = map[div[b1]];

				outPixels[index] = 0xff000000 | (r2 << 16) | (g2 << 8) | b2;

				int er = r1-r2;
				int eg = g1-g2;
				int eb = b1-b2;

				for (int i = -1; i <= 1; i++) {
					int iy = i+y;
					if (0 <= iy && iy < height) {
						for (int j = -1; j <= 1; j++) {
							int jx = j+x;
							if (0 <= jx && jx < width) {
								int w;
								if (reverse)
									w = matrix[(i+1)*3-j+1];
								else
									w = matrix[(i+1)*3+j+1];
								if (w != 0) {
									int k = reverse ? index - j : index + j;
									rgb1 = inPixels[k];
									r1 = (rgb1 >> 16) & 0xff;
									g1 = (rgb1 >> 8) & 0xff;
									b1 = rgb1 & 0xff;
									r1 += er * w/sum;
									g1 += eg * w/sum;
									b1 += eb * w/sum;
									inPixels[k] = (PixelUtils.clamp(r1) << 16) | (PixelUtils.clamp(g1) << 8) | PixelUtils.clamp(b1);
								}
							}
						}
					}
				}
				index += direction;
			}
		}

		return outPixels;
	}

	public String toString() {
		return "Colors/Diffusion Dither...";
	}

	public BufferedImage filter(BufferedImage src, Struct parameters) throws PageException {BufferedImage dst=ImageUtil.createBufferedImage(src);
		Object o;
		if((o=parameters.removeEL(KeyImpl.init("Levels")))!=null)setLevels(ImageFilterUtil.toIntValue(o,"Levels"));
		if((o=parameters.removeEL(KeyImpl.init("Matrix")))!=null)setMatrix(ImageFilterUtil.toAInt(o,"Matrix"));
		if((o=parameters.removeEL(KeyImpl.init("Serpentine")))!=null)setSerpentine(ImageFilterUtil.toBooleanValue(o,"Serpentine"));
		if((o=parameters.removeEL(KeyImpl.init("ColorDither")))!=null)setColorDither(ImageFilterUtil.toBooleanValue(o,"ColorDither"));

		// check for arguments not supported
		if(parameters.size()>0) {
			throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "the parameter"+(parameters.size()>1?"s":"")+" ["+CollectionUtil.getKeyList(parameters,", ")+"] "+(parameters.size()>1?"are":"is")+" not allowed, only the following parameters are supported [Levels, Matrix, Serpentine, ColorDither]");
		}

		return filter(src, dst);
	}
}

{'repo_name': 'getrailo/railo', 'stars': '247', 'repo_language': 'Java', 'file_name': 'JiraXXXX.cfc', 'mime_type': 'text/plain', 'hash': -6690887794608988348, 'source_dataset': 'data'}


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun  9 2015 22:53:21).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//

#import <AppKit/NSBox.h>

#import "NSDraggingDestination-Protocol.h"

@class NSCollectionView, NSString, TTagsPrefTableView;

@interface TFavoritesBox : NSBox <NSDraggingDestination>
{
    TTagsPrefTableView *_tagsTableView;
    NSCollectionView *_favoritesView;
    long long _currentProposedIndex;
}

@property(nonatomic) long long currentProposedIndex; // @synthesize currentProposedIndex=_currentProposedIndex;
- (unsigned long long)draggingUpdated:(id)arg1;
- (void)concludeDragOperation:(id)arg1;
- (BOOL)performDragOperation:(id)arg1;
- (unsigned long long)draggingEntered:(id)arg1;
- (void)draggingExited:(id)arg1;
- (void)setFavoritesView:(id)arg1;
- (void)setTagsTableView:(id)arg1;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end

{'repo_name': 'w0lfschild/macOS_headers', 'stars': '304', 'repo_language': 'None', 'file_name': 'NSTextFinderBarContainer-Protocol.h', 'mime_type': 'text/x-objective-c', 'hash': -8018564915093566329, 'source_dataset': 'data'}


#!/bin/bash

# Copyright 2019 Kyoto University (Hirofumi Inaguma)
#  Apache 2.0  (http://www.apache.org/licenses/LICENSE-2.0)

model=
model1=
model2=
model3=
model_bwd=
gpu=
stdout=false

### path to save preproecssed data
data=/n/work1/inaguma/corpus/tedlium2

unit=
metric=edit_distance
batch_size=1
beam_width=5
min_len_ratio=0.0
max_len_ratio=0.4  ###
length_penalty=0.0
length_norm=true  ###
coverage_penalty=0.0
coverage_threshold=0.0
gnmt_decoding=false
eos_threshold=1.0
lm=
lm_second=
lm_bwd=
lm_weight=0.3
lm_second_weight=0.3
wordlm=false
ctc_weight=0.0  # 1.0 for joint CTC-attention means decoding with CTC
resolving_unk=false
fwd_bwd_attention=false
bwd_attention=false
reverse_lm_rescoring=false
asr_state_carry_over=false
lm_state_carry_over=true
chunk_sync=true  # for MoChA
n_average=1  # for Transformer
oracle=false

# for streaming
blank_threshold=40
spike_threshold=0.1
n_accum_frames=800

. ./cmd.sh
. ./path.sh
. utils/parse_options.sh

set -e
set -u
set -o pipefail

if [ -z ${gpu} ]; then
    n_gpus=0
else
    n_gpus=$(echo ${gpu} | tr "," "\n" | wc -l)
fi

for set in dev_streaming test_streaming; do
    recog_dir=$(dirname ${model})/decode_${set}_beam${beam_width}_lp${length_penalty}_cp${coverage_penalty}_${min_len_ratio}_${max_len_ratio}
    if [ ! -z ${unit} ]; then
        recog_dir=${recog_dir}_${unit}
    fi
    if [ ${length_norm} = true ]; then
        recog_dir=${recog_dir}_norm
    fi
    if [ ${metric} != 'edit_distance' ]; then
        recog_dir=${recog_dir}_${metric}
    fi
    if [ ! -z ${lm} ] && [ ${lm_weight} != 0 ]; then
        recog_dir=${recog_dir}_lm${lm_weight}
        if [ ${wordlm} = true ]; then
            recog_dir=${recog_dir}_wordlm
        fi
    fi
    if [ ! -z ${lm_second} ] && [ ${lm_second_weight} != 0 ]; then
        recog_dir=${recog_dir}_rescore${lm_second_weight}
    fi
    if [ ${ctc_weight} != 0.0 ]; then
        recog_dir=${recog_dir}_ctc${ctc_weight}
    fi
    if [ ${gnmt_decoding} = true ]; then
        recog_dir=${recog_dir}_gnmt
    fi
    if [ ${resolving_unk} = true ]; then
        recog_dir=${recog_dir}_resolvingOOV
    fi
    if [ ${fwd_bwd_attention} = true ]; then
        recog_dir=${recog_dir}_fwdbwd
    fi
    if [ ${bwd_attention} = true ]; then
        recog_dir=${recog_dir}_bwd
    fi
    if [ ${reverse_lm_rescoring} = true ]; then
        recog_dir=${recog_dir}_revLM
    fi
    if [ ${asr_state_carry_over} = true ]; then
        recog_dir=${recog_dir}_ASRcarryover
    fi
    if [ ${chunk_sync} = true ]; then
        recog_dir=${recog_dir}_chunksync
    fi
    if [ ${n_average} != 1 ]; then
        recog_dir=${recog_dir}_average${n_average}
    fi
    if [ ! -z ${lm} ] && [ ${lm_weight} != 0 ] && [ ${lm_state_carry_over} = true ]; then
        recog_dir=${recog_dir}_LMcarryover
    fi
    if [ ${oracle} = true ]; then
        recog_dir=${recog_dir}_oracle
    fi
    if [ ! -z ${model3} ]; then
        recog_dir=${recog_dir}_ensemble4
    elif [ ! -z ${model2} ]; then
        recog_dir=${recog_dir}_ensemble3
    elif [ ! -z ${model1} ]; then
        recog_dir=${recog_dir}_ensemble2
    fi
    recog_dir=${recog_dir}_blank${blank_threshold}_spike${spike_threshold}_accum${n_accum_frames}
    mkdir -p ${recog_dir}

    if [ $(echo ${model} | grep 'train_sp') ]; then
        recog_set=${data}/dataset/${set}_sp_wpbpe10000.tsv
    else
        recog_set=${data}/dataset/${set}_wpbpe10000.tsv
    fi

    CUDA_VISIBLE_DEVICES=${gpu} ${NEURALSP_ROOT}/neural_sp/bin/asr/eval.py \
        --recog_n_gpus ${n_gpus} \
        --recog_sets ${recog_set} \
        --recog_dir ${recog_dir} \
        --recog_unit ${unit} \
        --recog_metric ${metric} \
        --recog_model ${model} ${model1} ${model2} ${model3} \
        --recog_model_bwd ${model_bwd} \
        --recog_batch_size ${batch_size} \
        --recog_beam_width ${beam_width} \
        --recog_max_len_ratio ${max_len_ratio} \
        --recog_min_len_ratio ${min_len_ratio} \
        --recog_length_penalty ${length_penalty} \
        --recog_length_norm ${length_norm} \
        --recog_coverage_penalty ${coverage_penalty} \
        --recog_coverage_threshold ${coverage_threshold} \
        --recog_gnmt_decoding ${gnmt_decoding} \
        --recog_eos_threshold ${eos_threshold} \
        --recog_lm ${lm} \
        --recog_lm_second ${lm_second} \
        --recog_lm_bwd ${lm_bwd} \
        --recog_lm_weight ${lm_weight} \
        --recog_lm_second_weight ${lm_second_weight} \
        --recog_wordlm ${wordlm} \
        --recog_ctc_weight ${ctc_weight} \
        --recog_resolving_unk ${resolving_unk} \
        --recog_fwd_bwd_attention ${fwd_bwd_attention} \
        --recog_bwd_attention ${bwd_attention} \
        --recog_reverse_lm_rescoring ${reverse_lm_rescoring} \
        --recog_asr_state_carry_over ${asr_state_carry_over} \
        --recog_lm_state_carry_over ${lm_state_carry_over} \
        --recog_n_average ${n_average} \
        --recog_oracle ${oracle} \
        --recog_streaming true \
        --recog_chunk_sync ${chunk_sync} \
        --recog_ctc_vad true \
        --recog_ctc_vad_blank_threshold ${blank_threshold} \
        --recog_ctc_vad_spike_threshold ${spike_threshold} \
        --recog_ctc_vad_n_accum_frames ${n_accum_frames} \
        --recog_stdout ${stdout} || exit 1;

    # remove <unk>
    cat ${recog_dir}/ref.trn | sed 's:<unk>::g' | sed 's:<eos>::g' > ${recog_dir}/ref.trn.filt
    cat ${recog_dir}/hyp.trn | sed 's:<unk>::g' | sed 's:<eos>::g' > ${recog_dir}/hyp.trn.filt

    if [ ${metric} = 'edit_distance' ]; then
        echo ${set}
        sclite -r ${recog_dir}/ref.trn.filt trn -h ${recog_dir}/hyp.trn.filt trn -i rm -o all stdout > ${recog_dir}/result.txt
        grep -e Avg -e SPKR -m 2 ${recog_dir}/result.txt > ${recog_dir}/RESULTS
        cat ${recog_dir}/RESULTS
    fi
done

{'repo_name': 'hirofumi0810/neural_sp', 'stars': '234', 'repo_language': 'Python', 'file_name': 'resolving_unk.py', 'mime_type': 'text/plain', 'hash': -5823587173413031758, 'source_dataset': 'data'}