text:
/*************************************************************************************************/

#ifndef BOOST_GIL_EXTENSION_IO_READ_AND_CONVERT_VIEW_HPP_INCLUDED
#define BOOST_GIL_EXTENSION_IO_READ_AND_CONVERT_VIEW_HPP_INCLUDED

////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief
/// \author Christian Henning, Andreas Pokorny, Lubomir Bourdev \n
///
/// \date   2007-2008 \n
///
////////////////////////////////////////////////////////////////////////////////////////

#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/mpl/and.hpp>
#include <boost/utility/enable_if.hpp>

#include "base.hpp"
#include "io_device.hpp"
#include "path_spec.hpp"
#include "conversion_policies.hpp"

namespace boost{ namespace gil {

/// \ingroup IO

/// \brief Reads and color-converts an image view. No memory is allocated.
/// \param file      It's a device. Must satisfy is_input_device metafunction.
/// \param view      The image view in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \param cc        Color converter function object.
/// \throw std::ios_base::failure
template< typename Device
        , typename View
        , typename ColorConverter
        , typename FormatTag
        >
inline
void read_and_convert_view( Device&                                 file
                          , const View&                             view
                          , const image_read_settings< FormatTag >& settings
                          , const ColorConverter&                   cc
                          , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                         , detail::is_input_device< Device >
                                                         >
                                              >::type* /* ptr */ = 0
                          )
{
    typedef detail::read_and_convert< ColorConverter > reader_color_convert;

    detail::reader< Device
                  , FormatTag
                  , reader_color_convert
                  > reader( file
                          , cc
                          , settings
                          );

    reader.init_view( view
                    , reader.get_info()
                    );

    reader.apply( view );
}

/// \brief Reads and color-converts an image view. No memory is allocated.
/// \param file      It's a device. Must satisfy is_adaptable_input_device metafunction.
/// \param view      The image view in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \param cc        Color converter function object.
/// \throw std::ios_base::failure
template< typename Device
        , typename View
        , typename ColorConverter
        , typename FormatTag
        >
inline
void read_and_convert_view( Device&                                 file
                          , const View&                             view
                          , const image_read_settings< FormatTag >& settings
                          , const ColorConverter&                   cc
                          , typename enable_if< mpl::and_< detail::is_adaptable_input_device< FormatTag
                                                                                , Device
                                                                                >
                                                         , is_format_tag< FormatTag >
                                                         >
                                              >::type* /* ptr */ = 0
                          )
{
    typedef typename detail::is_adaptable_input_device< FormatTag
                                                      , Device
                                                      >::device_type device_type;

    device_type dev( file );

    read_and_convert_view( dev
                         , view
                         , settings
                         , cc
                         );
}

/// \brief Reads and color-converts an image view. No memory is allocated.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param view      The image view in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \param cc        Color converter function object.
/// \throw std::ios_base::failure
template < typename String
         , typename View
         , typename ColorConverter
         , typename FormatTag
         >
inline
void read_and_convert_view( const String&                           file_name
                          , const View&                             view
                          , const image_read_settings< FormatTag >& settings
                          , const ColorConverter&                   cc
                          , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                         , detail::is_supported_path_spec< String >
                                                         >
                                            >::type* /* ptr */ = 0
                          )
{
    detail::file_stream_device< FormatTag > device( detail::convert_to_string( file_name )
                                                  , typename detail::file_stream_device< FormatTag >::read_tag()
                                                  );

    read_and_convert_view( device
                         , view
                         , settings
                         , cc
                         );
}

/// \brief Reads and color-converts an image view. No memory is allocated.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param view      The image view in which the data is read into.
/// \param cc        Color converter function object.
/// \param tag       Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename String
         , typename View
         , typename ColorConverter
         , typename FormatTag
         >
inline
void read_and_convert_view( const String&         file_name
                          , const View&           view
                          , const ColorConverter& cc
                          , const FormatTag&
                          , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                         , detail::is_supported_path_spec< String >
                                                         >
                                            >::type* /* ptr */ = 0
                          )
{
    read_and_convert_view( file_name
                         , view
                         , image_read_settings< FormatTag >()
                         , cc
                         );
}

/// \brief Reads and color-converts an image view. No memory is allocated.
/// \param file It's a device. Must satisfy is_input_device metafunction or is_adaptable_input_device.
/// \param view The image view in which the data is read into.
/// \param cc   Color converter function object.
/// \param tag  Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename Device
         , typename View
         , typename ColorConverter
         , typename FormatTag
         >
inline
void read_and_convert_view( Device&               device
                          , const View&           view
                          , const ColorConverter& cc
                          , const FormatTag&
                          , typename enable_if< mpl::and_< mpl::or_< detail::is_input_device< Device >
                                                                   , detail::is_adaptable_input_device< FormatTag
                                                                                , Device
                                                                                >
                                                                   >
                                                         , is_format_tag< FormatTag >
                                                         >
                                               >::type* /* ptr */ = 0
                          )
{
    read_and_convert_view( device
                         , view
                         , image_read_settings< FormatTag >()
                         , cc
                         );
}

/// \brief Reads and color-converts an image view. No memory is allocated.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param view      The image view in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \throw std::ios_base::failure
template < typename String
         , typename View
         , typename FormatTag
         >
inline
void read_and_convert_view( const String&                           file_name
                          , const View&                             view
                          , const image_read_settings< FormatTag >& settings
                          , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                         , detail::is_supported_path_spec< String >
                                                         >
                                            >::type* /* ptr */ = 0
                          )
{
   read_and_convert_view( file_name
                        , view
                        , settings
                        , default_color_converter()
                        );
}

/// \brief Reads and color-converts an image view. No memory is allocated.
/// \param file      It's a device. Must satisfy is_input_device metafunction or is_adaptable_input_device.
/// \param view      The image view in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \throw std::ios_base::failure
template < typename Device
         , typename View
         , typename FormatTag
         >
inline
void read_and_convert_view( Device&                                 device
                          , const View&                             view
                          , const image_read_settings< FormatTag >& settings
                          , typename enable_if< mpl::and_< mpl::or_< detail::is_input_device< Device >
                                                                   , detail::is_adaptable_input_device< FormatTag
                                                                                , Device
                                                                                >
                                                                    >
                                                         , is_format_tag< FormatTag >
                                                         >
                                               >::type* /* ptr */ = 0
                          )
{
   read_and_convert_view( device
                        , view
                        , settings
                        , default_color_converter()
                        );
}

/// \brief Reads and color-converts an image view. No memory is allocated.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param view      The image view in which the data is read into.
/// \param tag       Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename String
         , typename View
         , typename FormatTag
         >
inline
void read_and_convert_view( const String&    file_name
                          , const View&      view
                          , const FormatTag&
                          , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                         , detail::is_supported_path_spec< String >
                                                         >
                                              >::type* /* ptr */ = 0
                          )
{
   read_and_convert_view( file_name
                        , view
                        , image_read_settings< FormatTag >()
                        , default_color_converter()
                        );
}

/// \brief Reads and color-converts an image view. No memory is allocated.
/// \param file It's a device. Must satisfy is_input_device metafunction or is_adaptable_input_device.
/// \param view The image view in which the data is read into.
/// \param tag  Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename Device
         , typename View
         , typename FormatTag
         >
inline
void read_and_convert_view( Device&          device
                          , const View&      view
                          , const FormatTag&
                          , typename enable_if< mpl::and_< mpl::or_< detail::is_input_device< Device >
                                                                   , detail::is_adaptable_input_device< FormatTag
                                                                                , Device
                                                                                >
                                                                   >
                                                         , is_format_tag< FormatTag >
                                                         >
                                               >::type* /* ptr */ = 0
                          )
{
   read_and_convert_view( device
                        , view
                        , image_read_settings< FormatTag >()
                        , default_color_converter()
                        );
}

} // namespace gil
} // namespace boost

#endif // BOOST_GIL_EXTENSION_IO_READ_AND_CONVERT_VIEW_HPP_INCLUDED


text:
<?php
// +----------------------------------------------------------------------+
// | PHP version 5                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2006 James Heinrich, Allan Hansen                 |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2 of the GPL license,         |
// | that is bundled with this package in the file license.txt and is     |
// | available through the world-wide-web at the following url:           |
// | http://www.gnu.org/copyleft/gpl.html                                 |
// +----------------------------------------------------------------------+
// | getID3() - http://getid3.sourceforge.net or http://www.getid3.org    |
// +----------------------------------------------------------------------+
// | Authors: James Heinrich <infoØgetid3*org>                            |
// |          Allan Hansen <ahØartemis*dk>                                |
// +----------------------------------------------------------------------+
// | module.audio.aac_adts.php                                            |
// | Module for analyzing AAC files with ADTS header.                     |
// | dependencies: NONE                                                   |
// +----------------------------------------------------------------------+
//
// $Id: module.audio.aac_adts.php,v 1.4 2006/11/02 10:48:01 ah Exp $

class getid3_aac_adts extends getid3_handler
{

    public $option_max_frames_to_scan   = 1000000;
    public $option_return_extended_info = false;

    private $decbin_cache;
    private $bitrate_cache;

    public function __construct(getID3 $getid3) {

        parent::__construct($getid3);

        // Populate bindec_cache
        for ($i = 0; $i < 256; $i++) {
                $this->decbin_cache[chr($i)] = str_pad(decbin($i), 8, '0', STR_PAD_LEFT);
        }

        // Init cache
        $this->bitrate_cache = array ();

        // Fast scanning?
        if (!$getid3->option_accurate_results) {
            $this->option_max_frames_to_scan = 200;
            $getid3->warning('option_accurate_results set to false - bitrate and playing time are not accurate.');
        }
    }

    public function Analyze() {

        $getid3 = $this->getid3;

        // based loosely on code from AACfile by Jurgen Faul  <jfaulØgmx.de>
        // http://jfaul.de/atl  or  http://j-faul.virtualave.net/atl/atl.html

        // http://faac.sourceforge.net/wiki/index.php?page=ADTS

        // * ADTS Fixed Header: these don't change from frame to frame
        // syncword                                       12    always: '111111111111'
        // ID                                              1    0: MPEG-4, 1: MPEG-2
        // layer                                           2    always: '00'
        // protection_absent                               1
        // profile                                         2
        // sampling_frequency_index                        4
        // private_bit                                     1
        // channel_configuration                           3
        // original/copy                                   1
        // home                                            1
        // emphasis                                        2    only if ID == 0 (ie MPEG-4)

        // * ADTS Variable Header: these can change from frame to frame
        // copyright_identification_bit                    1
        // copyright_identification_start                  1
        // aac_frame_length                               13    length of the frame including header (in bytes)
        // adts_buffer_fullness                           11    0x7FF indicates VBR
        // no_raw_data_blocks_in_frame                     2

        // * ADTS Error check
        // crc_check                                      16    only if protection_absent == 0

        $getid3->info['aac']['header'] = array () ;
        $info_aac        = &$getid3->info['aac'];
        $info_aac_header = & $info_aac['header'];

        $byte_offset  = $frame_number = 0;

        while (true) {

            // Breaks out when end-of-file encountered, or invalid data found,
            // or MaxFramesToScan frames have been scanned

            fseek($getid3->fp, $byte_offset, SEEK_SET);

            // First get substring
            $sub_string = fread($getid3->fp, 10);
            $sub_string_length = strlen($sub_string);
            if ($sub_string_length != 10) {
                throw new getid3_exception('Failed to read 10 bytes at offset '.(ftell($getid3->fp) - $sub_string_length).' (only read '.$sub_string_length.' bytes)');
            }

            // Initialise $aac_header_bitstream
            $aac_header_bitstream = '';

            // Loop thru substring chars
            for ($i = 0; $i < 10; $i++) {
                $aac_header_bitstream .= $this->decbin_cache[$sub_string[$i]];
            }

            $sync_test  = bindec(substr($aac_header_bitstream, 0, 12));
            $bit_offset = 12;

            if ($sync_test != 0x0FFF) {
                throw new getid3_exception('Synch pattern (0x0FFF) not found at offset '.(ftell($getid3->fp) - 10).' (found 0x0'.strtoupper(dechex($sync_test)).' instead)');
            }

            // Only gather info once - this takes time to do 1000 times!
            if ($frame_number > 0) {

                // MPEG-4: 20,  // MPEG-2: 18
                $bit_offset += $aac_header_bitstream[$bit_offset] ? 18 : 20;
            }

            // Gather info for first frame only - this takes time to do 1000 times!
            else {

                $info_aac['header_type']             = 'ADTS';
                $info_aac_header['synch']            = $sync_test;
                $getid3->info['fileformat']          = 'aac';
                $getid3->info['audio']['dataformat'] = 'aac';

                $info_aac_header['mpeg_version']     = $aac_header_bitstream{$bit_offset++} == '0' ? 4 : 2;
                $info_aac_header['layer']            = bindec(substr($aac_header_bitstream, $bit_offset, 2));
                $bit_offset += 2;

                if ($info_aac_header['layer'] != 0) {
                    throw new getid3_exception('Layer error - expected 0x00, found 0x'.dechex($info_aac_header['layer']).' instead');
                }

                $info_aac_header['crc_present'] = $aac_header_bitstream{$bit_offset++} == '0' ? true : false;

                $info_aac_header['profile_id'] = bindec(substr($aac_header_bitstream, $bit_offset, 2));
                $bit_offset += 2;

                $info_aac_header['profile_text'] = getid3_aac_adts::AACprofileLookup($info_aac_header['profile_id'], $info_aac_header['mpeg_version']);

                $info_aac_header['sample_frequency_index'] = bindec(substr($aac_header_bitstream, $bit_offset, 4));
                $bit_offset += 4;

                $info_aac_header['sample_frequency'] = getid3_aac_adts::AACsampleRateLookup($info_aac_header['sample_frequency_index']);

                $getid3->info['audio']['sample_rate'] = $info_aac_header['sample_frequency'];

                $info_aac_header['private'] = $aac_header_bitstream{$bit_offset++} == 1;

                $info_aac_header['channel_configuration'] = $getid3->info['audio']['channels'] = bindec(substr($aac_header_bitstream, $bit_offset, 3));
                $bit_offset += 3;

                $info_aac_header['original'] = $aac_header_bitstream{$bit_offset++} == 1;
                $info_aac_header['home']     = $aac_header_bitstream{$bit_offset++} == 1;

                if ($info_aac_header['mpeg_version'] == 4) {
                    $info_aac_header['emphasis']  = bindec(substr($aac_header_bitstream, $bit_offset, 2));
                    $bit_offset += 2;
                }

                if ($this->option_return_extended_info) {

                    $info_aac[$frame_number]['copyright_id_bit']   = $aac_header_bitstream{$bit_offset++} == 1;
                    $info_aac[$frame_number]['copyright_id_start'] = $aac_header_bitstream{$bit_offset++} == 1;

                }  else {
                    $bit_offset += 2;
                }
            }

            $frame_length = bindec(substr($aac_header_bitstream, $bit_offset, 13));

            if (!isset($this->bitrate_cache[$frame_length])) {
                $this->bitrate_cache[$frame_length] = ($info_aac_header['sample_frequency'] / 1024) * $frame_length * 8;
            }
            @$info_aac['bitrate_distribution'][$this->bitrate_cache[$frame_length]]++;

            $info_aac[$frame_number]['aac_frame_length']     = $frame_length;
            $bit_offset += 13;

            $info_aac[$frame_number]['adts_buffer_fullness'] = bindec(substr($aac_header_bitstream, $bit_offset, 11));
            $bit_offset += 11;

            $getid3->info['audio']['bitrate_mode'] = ($info_aac[$frame_number]['adts_buffer_fullness'] == 0x07FF) ? 'vbr' : 'cbr';

            $info_aac[$frame_number]['num_raw_data_blocks']  = bindec(substr($aac_header_bitstream, $bit_offset, 2));
            $bit_offset += 2;

            if ($info_aac_header['crc_present']) {
                $bit_offset += 16;
            }

            if (!$this->option_return_extended_info) {
                unset($info_aac[$frame_number]);
            }

            $byte_offset += $frame_length;
            if ((++$frame_number < $this->option_max_frames_to_scan) && (($byte_offset + 10) < $getid3->info['avdataend'])) {

                // keep scanning

            } else {

                $info_aac['frames']    = $frame_number;
                $getid3->info['playtime_seconds'] = ($getid3->info['avdataend'] / $byte_offset) * (($frame_number * 1024) / $info_aac_header['sample_frequency']);  // (1 / % of file scanned) * (samples / (samples/sec)) = seconds
                $getid3->info['audio']['bitrate'] = (($getid3->info['avdataend'] - $getid3->info['avdataoffset']) * 8) / $getid3->info['playtime_seconds'];
                ksort($info_aac['bitrate_distribution']);

                $getid3->info['audio']['encoder_options'] = $info_aac['header_type'].' '.$info_aac_header['profile_text'];

                return true;
            }
        }
    }

    public static function AACsampleRateLookup($samplerate_id) {

        static $lookup = array (
            0  => 96000,
            1  => 88200,
            2  => 64000,
            3  => 48000,
            4  => 44100,
            5  => 32000,
            6  => 24000,
            7  => 22050,
            8  => 16000,
            9  => 12000,
            10 => 11025,
            11 => 8000,
            12 => 0,
            13 => 0,
            14 => 0,
            15 => 0
        );
        return (isset($lookup[$samplerate_id]) ? $lookup[$samplerate_id] : 'invalid');
    }

    public static function AACprofileLookup($profile_id, $mpeg_version) {

        static $lookup = array (
            2 => array (
                0 => 'Main profile',
                1 => 'Low Complexity profile (LC)',
                2 => 'Scalable Sample Rate profile (SSR)',
                3 => '(reserved)'
            ),
            4 => array (
                0 => 'AAC_MAIN',
                1 => 'AAC_LC',
                2 => 'AAC_SSR',
                3 => 'AAC_LTP'
            )
        );
        return (isset($lookup[$mpeg_version][$profile_id]) ? $lookup[$mpeg_version][$profile_id] : 'invalid');
    }

}

?>

redpajama_set_name: RedPajamaGithub


text:
<?php
$privilegiosPagina = 1;
include("seguridad.php");
include_once("clases/Cita.php");
include_once("clases/Receta.php");
include_once("clases/tipoEx.php");
include_once("clases/exLab.php");
include_once("clases/Foto.php");
/* Declaro como indice del array los distintos identificadores de seccion que ya habia declarado como valor en la configuracion del archivo JS.
Como valores declaro otro array que contiene el nombre de la tabla donde tiene que buscar los datos de la seccion (por ejemplo tabs_tabla_1), el nombre de la columna
que actua como ID, el valor que debe contener ese ID y tambien la columna en donde esta el string de la seccion.
Para mas claridad por favor revisen la estructura de las tablas adjuntas en el .sql. */

/*$secciones=array(
'seccion1'=>array('tabs_tabla_1', 'id', '1', 'datos'),
'seccion2'=>array('tabs_tabla_1', 'id', '2', 'datos'),
'seccion3'=>array('tabs_tabla_2', 'id', '1', 'datos')
);*/

$seccion = $_POST['seccion'];
$idCita = $_POST['idCita'];
$idPaciente = $_POST['idPaciente'];
if ($seccion == 'diagnostico')
{
$cita = Cita::obtenerPorId($idCita);
?>
	<form method="post" action="ingresarDiagnostico.php" name="ingresarDiagnostico" id="ingresarDiagnostico">
	<input name="idCita" id="idCita" type="hidden" value="<?php echo $idCita; ?>">
	<textarea name='diagnostico' id="diagnostico" style="width:500; height:200"><?php echo $cita->DiagnosticoCita; ?></textarea>

	<input type='button' value='guardar' onclick="guardarDiagnostico();">
	</form>
<?php
}
else if ($seccion == 'prescripcion')
{
?>

Ingresar Medicamento

		    	<form method="post" action="ingresarPrescripcion.php" name="ingresarPrescripcion" id="ingresarPrescripcion">
				<input name="idCita" id="idCita" type="hidden" value="<?php echo $idCita; ?>"><input name="idReceta" id="idReceta" type="hidden" value="0">

<textarea name='indicaciones' id="indicaciones" cols='3' rows='3' onkeyup="inputFilling(event, this);" onblur="setInput(this, document.getElementById('lista'))"></textarea>
				<input type='button' value='guardar' onclick="guardarPrescripcion();" /> <input name="btnCancelar" id="btnCancelar" type='button' value='cancelar' onclick="cancelarEdicion();" style="display:none"/>

		  		</form>

				PRESCRIPCIONES

				<form id="formImprimirPrescripcion" name="formImprimirPrescripcion" method="post" action="prescripcion.php" target="_blank">
				<input name="idCita" id="idCita" type="hidden" value="<?php echo $idCita; ?>">

				<?php
				$recetas = Receta::obtenerRecetaPorIdcita($idCita);
				foreach($recetas as $receta)
				{
					echo "

";
					echo "<input type='button' value='borrar' onclick='borrarPrescripcion($idCita,$receta->IdReceta)'>";
					echo " <input type='button' value='editar' onclick='editarPrescripcion($receta->IdReceta, \"" . urlencode($receta->Indicaciones) . "\")'>";
					echo "<input type='checkbox' name='prescripciones[]' value='$receta->IdReceta' checked='checked'/>

";
					echo "
";
					echo "<input name='idReceta' id='idReceta' type='hidden' value='$receta->IdReceta'>";
					//echo $receta->Medicamento . " - " . $receta->Indicaciones . "";
					echo "
$receta->Indicaciones
";
					echo "
";
				}
				?>

	<input type="submit" name="enviar" value="Imprimir" />
	</form>

<?php
}
else if ($seccion == 'examenes')
{
	$estado = "activo";

?>
	EXAMENES A REALIZAR

	<form  method="post" name="ingresarExamen" id="ingresarExamen">

		<?php
	$descripciones = TipoEx::listarDescripciones("activo");
	$cantExamenes = 0;
	$contadorDescripciones = 0;
	foreach($descripciones as $descripcion)
	{
		$contadorDescripciones++;
		?>

				<?php echo $descripcion->Descripcion; ?>

			<?php
			$examenes = TipoEx::listarPorEstadoDescripcion("activo", $descripcion->Descripcion);
			foreach($examenes as $examen)
			{
				echo "
";
				echo $examen->Nombre;
				echo "	";
				$examenLab = new exLab($idCita, $examen->IdTipo, "");
				echo "<input name='examen' type='checkbox' value='$examen->IdTipo' ";
				if ($examenLab->comprobarExamenGuardado())
				{
					echo "checked='checked'";
				}
				echo "/>
";
				$cantExamenes++;
			}
			?>

			<?php
			if($contadorDescripciones == 3 || $contadorDescripciones == 7)
			{
			?>

			<?php
			}
		}
	echo "
";
?>

<input name="idCita" id="idCita" type="hidden" value="<?php echo $idCita; ?>" />

<input name="cantExamenes" type="hidden" value="<?php echo $cantExamenes; ?>" />
<input type='button' value='Guardar e Imprimir' onclick="guardarExamen();">

</form>
<form id="formImprimirExamenes" name="formImprimirExamenes" method="post" action="imprimirExamenes.php" target="_blank">
	<input name="idCita" id="idCita" type="hidden" value="<?php echo $idCita; ?>">
</form>

<?php
}
else if ($seccion == 'historial')
{
	$citas = Cita::listarPorEstadoyPaciente(3,$idPaciente);
	$i=0;
	echo "<object width=\"500px\">

";
	if(count($citas)<1)
	{
		echo "Sin Historial";
	}
	else
	{
		foreach($citas as $cita)
		{
			list($ano,$mes,$resto)=split("-",$cita->FechaCita);
			list($dia,$rest)=split(" ",$resto);

			echo "

					FECHA CITA:$dia/$mes/$ano IdCita' onClick='return targetopener(this, false, false, $cita->IdCita)'> Ver IdCita);'>Eliminar

";
			echo "

					Diagnostico

IdCita\">";
			if ($cita->DiagnosticoCita=="") echo "No hay diagnostico";
			else echo nl2br($cita->DiagnosticoCita);

			echo "

";
			echo "

					Receta

";
			$recetas = Receta::obtenerRecetaPorIdcita($cita->IdCita);
			foreach($recetas as $receta)
			{
				echo "
";
				echo nl2br($receta->Indicaciones);
				echo "
";
			}
			echo "

";

			$i++;
		}
	}
	echo "

	      </object>";
}
else if ($seccion == 'foto')
{
?>

			<form method="post" action="ingresarFotografia.php" name="ingresarFotografia" id="ingresarFotografia" enctype="multipart/form-data">

<input name="idCita" id="idCita" type="hidden" value="<?php echo $idCita; ?>">Ingresar fotografía:

<input name='uploadFile' type="file" id="uploadFile" class="inputNormal" style="border:#000000 thin;" />

Descripción:

<textarea name='descripcion' id="descripcion" cols='5' rows='5'></textarea>

			<input type='submit' value='guardar'>
			</form>

		Fotografías anteriores:

	<input name="idCita" id="idCita" type="hidden" value="<?php echo $idCita; ?>">

	<?php

		$fotos = Foto::obtenerFotosPorIdcita($idCita);
		foreach($fotos as $foto)
		{
			echo "
";
			echo "<input type='button' value='borrar' onclick='borrarFotografia($idCita,$foto->IdFoto)'>";
			echo "
";
			echo "
";
			echo "<input name='idFoto' id='idFoto' type='hidden' value='$foto->IdFoto'>";
			echo "Imagen' target='_blank'>Miniatura' />" . "
" . $foto->Descripcion;
			echo "
";
			echo "
";
			echo "
";
		}
		echo "
";

	?>

<?php
}

/*echo "\n

Diagnostico

Foto

Prescripcion

Ex. Laboratorio

Prueba Parche

";*/

/*
echo "

                      DIAGNOSTICO
                      FOTO
                      PRESCRIPCION
                      EXAMEN LABORATORIO
                      PRUEBA PARCHE

";

$consulta=$resultado=NULL;
if(isset($secciones[$seccion]))
{
	include 'conexion.php';
	conectar();

	$consulta=mysql_query("SELECT {$secciones[$seccion][3]} FROM {$secciones[$seccion][0]} WHERE {$secciones[$seccion][1]}={$secciones[$seccion][2]}") or
	die (mysql_error());

	desconectar();
	$resultado=mysql_fetch_array($consulta);
	echo utf8_encode($resultado[0]);
}*/
?>


text:
<input type="checkbox" name="id" value="">

        Close.io (Sample Lead)
         Steli Efti

        <button class="email btn btn-small" target="_blank" rel="tooltip" title="" data-original-title="Email Steli Efti">

        </button>

        Welcome to Close.io!
        Hi! My name is Steli and I'm a co-founder of Close.io. I'm here to get your team set up and help with anything you may need as you evaluate our platform. Please don't hesitate to reach out with any qu

        <time rel="tooltip" datetime="2016-05-09T19:28:38.168000+00:00" title="" data-original-title="Monday, May 9 2016 4:28 PM ART">May 9</time>


text:
scala-twitter-api
=================

Scala Twitter Library


text:
package org.caleydo.view.dvi;

import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

/**
 * Input dialog for naming table perspectives. The dialog provides the option that the default name will be used in the
 * future.
 *
 * @author Marc Streit
 */
public class TablePerspectiveNameInputDialog
	extends InputDialog {

	Button alwaysUseDefaultNameButton;

	public TablePerspectiveNameInputDialog(Shell parentShell, String dialogTitle,
			String dialogMessage, String initialValue, IInputValidator validator) {
		super(parentShell, dialogTitle, dialogMessage, initialValue, validator);
	}

	@Override
	protected Control createDialogArea(Composite parent) {

		Control control = super.createDialogArea(parent);

		alwaysUseDefaultNameButton = new Button(parent, SWT.CHECK);
		alwaysUseDefaultNameButton
				.setText("Do not ask again and generate default name from now on.");

		return control;
	}

	@Override
	protected void okPressed() {
		MyPreferences.setIsAwaysUseTablePerspectiveDefaultName(alwaysUseDefaultNameButton.getSelection());
		super.okPressed();
	}
}


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Dalam codelab ini, Anda akan mempelajari cara menambahkan pemberitahuan push ke aplikasi web.

{# wf_updated_on: 2016-11-21T15:42:20Z #}
{# wf_published_on: 2016-01-01 #}

# Menambahkan Pemberitahuan Push ke Aplikasi Web {: .page-title }

{% include "web/_shared/contributors/mattgaunt.html" %}

## Ringkasan

Perpesanan push menyediakan cara yang sederhana dan efektif untuk terhubung-kembali dengan pengguna dan di code lab ini Anda akan mempelajari cara menambahkan pemberitahuan push ke aplikasi web.

### Apa yang akan Anda pelajari

* Cara berlangganan dan berhenti berlangganan perpesanan push untuk pengguna
* Cara menangani pesan push masuk
* Cara menampilkan notifikasi
* Cara merespons klik notifikasi

### Apa yang Anda butuhkan

* Chrome 52 atau di atasnya
*  [Web Server for Chrome](https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb), atau server web pilihan Anda
* Editor teks
* Pengetahuan dasar tentang HTML, CSS, JavaScript, dan Chrome DevTools
* Kode contoh, lihat Persiapan

## Persiapan

### Unduh kode contoh

Anda bisa mendapatkan kode contoh untuk kode ini dengan mengunduh file zip di sini:

[Tautan](https://github.com/googlechrome/push-notifications/archive/master.zip)

atau dengan mengkloning git repo ini:

    git clone https://github.com/GoogleChrome/push-notifications.git

Jika Anda mengunduh sumber sebagai zip, mengekstraknya akan memberikan Anda folder root `push-notifications-master`.

### Memasang dan memverifikasi server web

Meskipun Anda bebas menggunakan server web sendiri, codelab ini dirancang untuk bekerja dengan baik bersama Server Web Chrome. Jika Anda belum memasang aplikasi tersebut, Anda bisa memasangnya dari Toko Web Chrome.

[Tautan](https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb)

Setelah memasang aplikasi Web Server for Chrome, klik pada pintasan Apps di bilah bookmark:

![a80b29d5e878df22.png](img/a80b29d5e878df22.png)

Pada jendela berikutnya, klik ikon Web Server:

![dc07bbc9fcfe7c5b.png](img/dc07bbc9fcfe7c5b.png)

Berikutnya, Anda akan melihat dialog ini, yang memungkinkan Anda mengonfigurasi server web lokal:

![433870360ad308d4.png](img/433870360ad308d4.png)

Klik tombol __choose folder__, dan pilih folder aplikasi. Ini memungkinkan Anda untuk menyajikan pekerjaan yang sedang berlangsung melalui URL yang disorot dalam dialog server web (di bagian __Web Server URL(s)__).

Di bawah Options, centang kotak di sebelah "Automatically show index.html", seperti yang ditampilkan di bawah ini:

![39b4e0371e9703e6.png](img/39b4e0371e9703e6.png)

Kemudian berhenti dan restart server dengan menggeser toggle yang berlabel "Web Server: STARTED" ke kiri dan kemudian kembali ke kanan.

![daefd30e8a290df5.png](img/daefd30e8a290df5.png)

Sekarang kunjungi situs dalam browser web Anda (dengan mengeklik Web Server URL yang disorot) dan Anda akan melihat laman yang terlihat seperti ini:

![49b343a07e2c92d.png](img/49b343a07e2c92d.png)

### Selalu memperbarui service worker

Selama development, ada baiknya memastikan service worker Anda selalu up to date dan memiliki perubahan terbaru.

Untuk menyetel ini di Chrome, buka DevTools (Klik kanan> Inspect) dan masuk ke panel __Application__, klik tab __Service Workers__ kemudian klik kotak centang __Update on Reload__. Ketika kotak centang ini diaktifkan, service worker dengan paksa diperbarui setiap kali laman dimuat ulang.

![d670cb813f3a7575.png](img/d670cb813f3a7575.png)

## Mendaftarkan Service Worker

Dalam direktori `app`, perhatikan bahwa Anda memiliki file kosong bernama `sw.js`. File ini akan menjadi service worker Anda, saat ini file itu kosong dan nanti kita akan menambahkan kode ke situ.

Pertama kita harus mendaftarkan file ini sebagai Service Worker.

Laman `app/index.html` memuat `scripts/main.js` dan itu terdapat dalam file JavaScript yang akan kita daftarkan service worker-nya.

Tambahkan kode berikut ke `scripts/main.js`:

```
if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

  navigator.serviceWorker.register('sw.js')
  .then(function(swReg) {
    console.log('Service Worker is registered', swReg);

    swRegistration = swReg;
  })
  .catch(function(error) {
    console.error('Service Worker Error', error);
  });
} else {
  console.warn('Push messaging is not supported');
  pushButton.textContent = 'Push Not Supported';
}
```

Kode ini memeriksa bila service worker dan perpesanan push didukung oleh browser saat ini dan jika memang didukung, itu mendaftarkan file `sw.js` kita.

#### Cobalah

Memeriksa perubahan dengan membuka URL __127.0.0.1:8887__ dalam browser.

Buka Chrome DevTools untuk memeriksa konsol bagi `Service Worker is registered`, seperti:

![d712c8726928ca4.png](img/d712c8726928ca4.png)

### Mendapatkan Kunci Server Aplikasi

Untuk bekerja dengan code lab ini Anda harus membuat beberapa kunci server aplikasi yang bisa kita lakukan dengan situs pendamping ini:  [https://web-push-codelab.appspot.com/](https://web-push-codelab.appspot.com/)

Di sini Anda bisa membuat pasangan kunci Publik dan Privat.

![a1304b99e7b981dd.png](img/a1304b99e7b981dd.png)

Menyalin kunci publik Anda ke `scripts/main.js` menggantikan nilai `<Your Public Key>`:

```
const applicationServerPublicKey = '<Your Public Key>';
```

Catatan: Anda sebaiknya tidak menaruh kunci privat di aplikasi web!

## Menginisialisasi Status

Pada saat ini tombol aplikasi web dinonaktifkan dan tidak bisa diklik. Hal ini karena akan lebih baik menonaktifkan tombol push secara default dan mengaktifkannya setelah Anda mengetahui bahwa push didukung dan bisa tahu apakah pengguna sedang berlangganan atau tidak.

Mari kita membuat dua fungsi dalam `scripts/main.js`, satu yang disebut `initialiseUI`, yang akan memeriksa apakah pengguna sedang berlangganan, dan satu lagi yang disebut `updateBtn` yang akan mengaktifkan tombol dan mengubah teks bila pengguna berlangganan maupun tidak.

Kita menginginkan fungsi `initialiseUI` terlihat seperti ini:

```
function initialiseUI() {
  // Set the initial subscription value
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    isSubscribed = !(subscription === null);

    if (isSubscribed) {
      console.log('User IS subscribed.');
    } else {
      console.log('User is NOT subscribed.');
    }

    updateBtn();
  });
}
```

Metode baru kami menggunakan `swRegistration` dari langkah sebelumnya dan memanggil `getSubscription()` pada `pushManager`. `getSubscription()` adalah metode yang mengembalikan promise yang diselesaikan dengan langganan aktif, jika ada, jika tidak maka akan mengembalikan `null`. Dengan ini kita bisa memeriksa apakah pengguna telah berlangganan atau tidak, menyetel beberapa status dan kemudian memanggil `updateBtn()` sehingga tombol dapat diaktifkan dengan beberapa teks yang membantu.

Tambahkan kode berikut untuk mengimplementasikan fungsi `updateBtn()`.

```
function updateBtn() {
  if (isSubscribed) {
    pushButton.textContent = 'Disable Push Messaging';
  } else {
    pushButton.textContent = 'Enable Push Messaging';
  }

  pushButton.disabled = false;
}
```

Fungsi ini hanya mengubah teks bergantung pada apakah pengguna berlangganan atau tidak dan kemudian mengaktifkan tombol.

Hal terakhir yang harus dilakukan adalah memanggil `initialiseUI()` ketika service worker sudah terdaftar.

```
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
  console.log('Service Worker is registered', swReg);

  swRegistration = swReg;
  initialiseUI();
})
```

#### Cobalah

Buka aplikasi web dan Anda akan melihat tombol 'Enable Push Messaging' sekarang diaktifkan (Anda bisa mengeklik-nya) dan Anda akan melihat 'User is NOT subscribed.' di konsol.

![b9787463acb7e3fb.png](img/b9787463acb7e3fb.png)

Ketika kita melangkah maju melalui code lab selanjutnya, Anda akan melihat perubahan teks tombol ketika pengguna berlangganan / berhenti-berlangganan.

## Buatlah pengguna berlangganan

Pada saat ini tombol 'Enable Push Messaging' tidak berbuat terlalu banyak, jadi mari kita memperbaikinya.

Menambahkan listener klik ke tombol dalam fungsi `initialiseUI()`, seperti:

```
function initialiseUI() {
  pushButton.addEventListener('click', function() {
    pushButton.disabled = true;
    if (isSubscribed) {
      // TODO: Unsubscribe user
    } else {
      subscribeUser();
    }
  });

  // Set the initial subscription value
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    isSubscribed = !(subscription === null);

    updateSubscriptionOnServer(subscription);

    if (isSubscribed) {
      console.log('User IS subscribed.');
    } else {
      console.log('User is NOT subscribed.');
    }

    updateBtn();
  });
}
```

Ketika pengguna mengeklik tombol push, pertama kita menonaktifkan tombol hanya untuk memastikan pengguna tidak dapat mengeklik untuk kedua kalinya sementara kita berlangganan push karena itu membutuhkan beberapa saat.

Kemudian kita memanggil `subscribeUser()` ketika kita mengetahui bahwa pengguna saat ini tidak berlangganan, jadi salin dan tempelkan kode berikut ke `scripts/main.js`.

```
function subscribeUser() {
  const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
  swRegistration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: applicationServerKey
  })
  .then(function(subscription) {
    console.log('User is subscribed:', subscription);

    updateSubscriptionOnServer(subscription);

    isSubscribed = true;

    updateBtn();
  })
  .catch(function(err) {
    console.log('Failed to subscribe the user: ', err);
    updateBtn();
  });
}
```

Mari kita masuk lebih dalam untuk mengetahui apa yang dilakukan kode ini dan caranya membuat pengguna berlangganan perpesanan push.

Pertama kita mengambil kunci publik server aplikasi, yang merupakan basis 64 URL aman di-enkode, dan kami mengubahnya menjadi `UInt8Array` karena ini adalah masukan yang diharapkan dari panggilan berlangganan. Kami sudah memberikan Anda fungsi `urlB64ToUint8Array` di atas `scripts/main.js`.

Setelah mengkonversi nilai, kita memanggil metode `subscribe()` pada service worker `pushManager`, meneruskan kunci publik server aplikasi dan nilai `userVisibleOnly: true`.

```
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
  userVisibleOnly: true,
  applicationServerKey: applicationServerKey
})
```

Parameter `userVisibleOnly` pada dasarnya adalah sebuah pengakuan bahwa Anda akan menampilkan notifikasi setiap kali pesan push dikirim. Pada saat penulisan, nilai ini diperlukan dan harus true.

Memanggil `subscribe()` mengembalikan promise yang akan diselesaikan setelah langkah-langkah berikut:

1. Pengguna telah diberikan izin untuk menampilkan notifikasi.
2. Browser telah mengirimkan permintaan jaringan ke layanan push agar mendapatkan rincian untuk menghasilkan PushSubscription.

Promise `subscribe()` akan diselesaikan dengan `PushSubscription` jika langkah-langkah ini berhasil. Jika pengguna tidak memberikan izin atau jika ada masalah dalam langganan pengguna, promise akan menolak dengan kesalahan. Ini memberi kita rangkaian promise berikut di codelab:

```
swRegistration.pushManager.subscribe({
  userVisibleOnly: true,
  applicationServerKey: applicationServerKey
})
.then(function(subscription) {
  console.log('User is subscribed:', subscription);

  updateSubscriptionOnServer(subscription);

  isSubscribed = true;

  updateBtn();

})
.catch(function(err) {
  console.log('Failed to subscribe the user: ', err);
  updateBtn();
});
```

Dengan ini, kita mendapatkan langganan dan memperlakukan pengguna sebagai berlangganan atau kita menangkap kesalahan dan mencetaknya ke konsol. Dalam kedua skenario kita memanggil `updateBtn()` untuk memastikan tombol diaktifkan-kembali dan memiliki teks yang tepat.

Metode `updateSubscriptionOnServer` adalah metode yang dalam aplikasi sesungguhnya kita mengirim langganan ke backend, namun untuk codelab ini, kita akan mencetak langganan di UI kita yang akan memudahkan kita di kemudian hari. Tambahkan metode ini ke `scripts/main.js`:

```
function updateSubscriptionOnServer(subscription) {
  // TODO: Send subscription to application server

  const subscriptionJson = document.querySelector('.js-subscription-json');
  const subscriptionDetails =
    document.querySelector('.js-subscription-details');

  if (subscription) {
    subscriptionJson.textContent = JSON.stringify(subscription);
    subscriptionDetails.classList.remove('is-invisible');
  } else {
    subscriptionDetails.classList.add('is-invisible');
  }
}
```

#### Cobalah

Bila Anda kembali ke aplikasi web dan coba mengeklik tombol, Anda akan melihat konfirmasi izin seperti ini:

![5b8a7e9905f2237b.png](img/5b8a7e9905f2237b.png)

Jika Anda memberikan izin, Anda akan melihat konsol mencetak `User is subscribed:` dengan `PushSubscription`, teks tombol akan berubah menjadi 'Disable Push Messaging' dan Anda bisa melihat langganan sebagai JSON di bagian bawah halaman.

![bfdc9f92e001934a.png](img/bfdc9f92e001934a.png)

## Menangani Izin Ditolak

Satu hal yang belum kita tangani adalah apa yang terjadi bila pengguna memblokir permintaan izin. Hal ini memerlukan beberapa pertimbangan khusus karena bila pengguna memblokir izin, aplikasi web kita tidak bisa menampilkan kembali konfirmasi izin dan tidak dapat membuat pengguna berlangganan, jadi kita setidaknya perlu menonaktifkan tombol push sehingga pengguna tahu bahwa itu tidak bisa digunakan.

Tempat yang tepat bagi kita untuk menangani skenario ini adalah dalam fungsi `updateBtn()`. Yang perlu kita lakukan hanyalah memeriksa nilai `Notification.permission`, seperti:

```
function updateBtn() {
  if (Notification.permission === 'denied') {
    pushButton.textContent = 'Push Messaging Blocked.';
    pushButton.disabled = true;
    updateSubscriptionOnServer(null);
    return;
  }

  if (isSubscribed) {
    pushButton.textContent = 'Disable Push Messaging';
  } else {
    pushButton.textContent = 'Enable Push Messaging';
  }

  pushButton.disabled = false;
}
```

Kita tahu bahwa jika izin tersebut `denied`, maka pengguna tidak bisa berlangganan dan tidak ada lagi yang bisa kita lakukan, jadi menonaktifkan tombol untuk hal yang baik adalah pendekatan terbaik.

#### Cobalah

Karena kita sudah memberikan izin untuk aplikasi web dari langkah sebelumnya, kita harus mengeklik __i__ dalam lingkaran di bilah URL dan mengubah izin notifikasi ke *Use global default (Ask)* .

![c69f7428408c5bbc.png](img/c69f7428408c5bbc.png)

Setelah Anda mengubah setelan ini, segarkan laman dan klik tombol *Enable Push Messaging* dan kali ini pilih *Block* pada dialog izin. Teks tombol sekarang akan bertuliskan *Push Messaging Blocked* dan dinonaktifkan.

![e36f921fa7598419.png](img/e36f921fa7598419.png)

Dengan perubahan ini, sekarang kita bisa membuat pengguna berlangganan dan kita mengatasi skenario izin yang mungkin.

## Menangani Kejadian Push

Sebelum kita membahas cara mengirim pesan push dari backend Anda, kita perlu mempertimbangkan apa yang sebenarnya akan terjadi ketika pengguna berlangganan menerima pesan push.

Saat kita memicu pesan push, browser menerima pesan push, menetapkan service worker yang diperlukan push sebelum mengaktifkan service worker dan mengirimkan kejadian push. Kita harus mendengarkan kejadian ini dan menunjukkan notifikasi sebagai hasilnya.

Tambahkan kode berikut ke file `sw.js` Anda:

```
self.addEventListener('push', function(event) {
  console.log('[Service Worker] Push Received.');
  console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

  const title = 'Push Codelab';
  const options = {
    body: 'Yay it works.',
    icon: 'images/icon.png',
    badge: 'images/badge.png'
  };

  event.waitUntil(self.registration.showNotification(title, options));
});
```

Mari melangkah melalui kode ini. Kita mendengarkan kejadian push di service worker dengan menambahkan event listener ke service worker, yaitu potongan kode ini:

```
self.addEventListener('push', ...... );
```

Kecuali Anda pernah memakai Web Workers sebelumnya, `self` mungkin adalah hal baru. `self` adalah referensi service worker itu sendiri, jadi kita menambahkan event listener ke service worker kita.

Ketika pesan push diterima, event listener akan diaktifkan, dan kita membuat notifikasi dengan memanggil `showNotification()` pada pendaftaran. `showNotification()` berharap `title` dan kita diberikan sebuah objek `options`. Di sini kita akan menyetel body pesan, ikon dan lencana dalam opsi (lencana hanya digunakan di Android pada saat penulisan).

```
const title = 'Push Codelab';
const options = {
  body: 'Yay it works.',
  icon: 'images/icon.png',
  badge: 'images/badge.png'
};
self.registration.showNotification(title, options);
```

Hal terakhir yang perlu dibahas pada kejadian push kita adalah `event.waitUntil()`. Metode ini mengambil promise dan browser akan menjaga service worker tetap aktif dan berjalan sampai promise yang diteruskan telah diselesaikan.

Agar kode di atas sedikit lebih mudah dipahami kita bisa menulis ulang seperti ini:

```
const notificationPromise = self.registration.showNotification(title, options);
event.waitUntil(notificationPromise);
```

Sekarang setelah kita melangkah masuk kejadian push, mari kita menguji kejadian push.

#### Cobalah

Dengan kejadian push kita di service worker, kita bisa menguji apa yang terjadi ketika pesan diterima dengan memicu kejadian push palsu menggunakan DevTools.

Pada aplikasi web Anda, ikutlah berlangganan perpesanan push, pastikan Anda mendapat *User IS subscribed* di konsol Anda, lalu buka panel *Application* dalam DevTools dan di bawah tab *Service Workers* klik pada tautan *Push* di bawah service worker Anda.

![c0fab1022906d01f.png](img/c0fab1022906d01f.png)

Setelah mengekliknya Anda akan mendapatkan notifikasi seperti ini:

![eee7f9133a97c1c4.png](img/eee7f9133a97c1c4.png)

Catatan: Jika langkah ini tidak berhasil, cobalah membatalkan pendaftaran service worker Anda, melalui tautan *Unregister* dalam panel Aplikasi DevTools, tunggu service worker dihentikan, kemudian muat ulang laman.

## Klik notifikasi

Jika Anda mengeklik salah satu notifikasi ini, Anda akan menyadari bahwa tidak ada yang terjadi. Kita bisa menangani klik notifikasi dengan mendengarkan kejadian `notificationclick` di service worker Anda.

Mulailah dengan menambahkan listener `notificationclick` di `sw.js` seperti:

```
self.addEventListener('notificationclick', function(event) {
  console.log('[Service Worker] Notification click Received.');

  event.notification.close();

  event.waitUntil(
    clients.openWindow('https://developers.google.com/web/')
  );
});
```

Ketika pengguna mengeklik notifikasi, event listener `notificationclick` akan dipanggil.

Dalam code lab ini, pertama-tama kita akan menutup notifikasi yang diklik dengan:

```
event.notification.close();
```

Kemudian kita membuka jendela / tab baru yang memuat url [developers.google.com](/web/), silakan mengubah ini :)

```
clients.openWindow('https://developers.google.com/web/')
```

Kita memanggil `event.waitUntil()` lagi untuk memastikan browser tidak menghentikan service worker sebelum jendela baru ditampilkan.

#### Cobalah

Cobalah memicu pesan push di DevTools lagi dan klik pada notifikasi. Sekarang Anda akan melihat notifikasi menutup dan membuka tab baru.

## Mengirim pesan push

Kita telah melihat bahwa aplikasi web kita mampu menampilkan notifikasi menggunakan DevTools dan melihat cara menutup notifikasi melalui klik, langkah berikutnya adalah mengirim pesan push yang sebenarnya.

Biasanya proses ini akan mengirimkan langganan dari laman web ke backend dan backend kemudian akan memicu pesan push dengan membuat panggilan API ke endpoint di langganan.

Ini di luar cakupan codelab ini, namun Anda bisa menggunakan situs pendamping ( [https://web-push-codelab.appspot.com/](https://web-push-codelab.appspot.com/)) bagi code lab ini untuk memicu pesan push yang sebenarnya. Salin dan tempel langganan di bagian bawah laman Anda:

![cb84e05044ad029f.png](img/cb84e05044ad029f.png)

Kemudian tempel ini ke situs pendamping di area teks *Subscription to Send To*:

![e320ddd1b66682e6.png](img/e320ddd1b66682e6.png)

Kemudian di bawah *Text to Send* Anda bisa menambahkan string yang ingin Anda kirim dengan pesan push dan terakhir klik tombol *Send Push Message*.

![3c5c0d5d1c3deda4.png](img/3c5c0d5d1c3deda4.png)

Anda kemudian akan menerima pesan push dan teks yang Anda sertakan akan dicetak ke konsol.

![fdedaa6d10e2f43e.png](img/fdedaa6d10e2f43e.png)

Ini akan memberikan Anda kesempatan untuk menguji proses mengirim dan menerima data serta memanipulasi notifikasi sebagai akibatnya.

Aplikasi pendamping sebenarnya hanyalah server simpul yang menggunakan [pustaka web-push](https://github.com/web-push-libs/web-push) untuk mengirim pesan. Anda pasti akan terbantu bila memeriksa [web-push-libs org di Github](https://github.com/web-push-libs/) untuk melihat apa pustaka yang tersedia untuk mengirim pesan push bagi Anda (ini menangani banyak detail mendalam tentang memicu pesan push).

## Menghentikan langganan pengguna

Satu hal yang tidak kita dapatkan adalah kemampuan untuk menghentikan langganan pengguna dari push. Untuk melakukan ini kita harus memanggil `unsubscribe()` pada `PushSubscription`.

Kembali pada file `scripts/main.js` kita, ubah listener klik `pushButton` di `initialiseUI()` sebagai berikut:

```
pushButton.addEventListener('click', function() {
  pushButton.disabled = true;
  if (isSubscribed) {
    unsubscribeUser();
  } else {
    subscribeUser();
  }
});
```

Perhatikan bahwa kita sekarang akan memanggil fungsi `unsubscribeUser()` baru. Dalam metode ini kita akan mendapatkan langganan aktif dan memanggil berhenti berlangganan di atasnya. Tambahkan kode berikut ke `scripts/main.js`:

```
function unsubscribeUser() {
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    if (subscription) {
      return subscription.unsubscribe();
    }
  })
  .catch(function(error) {
    console.log('Error unsubscribing', error);
  })
  .then(function() {
    updateSubscriptionOnServer(null);

    console.log('User is unsubscribed.');
    isSubscribed = false;

    updateBtn();
  });
}
```

Mari menjelajahi fungsi ini.

Pertama kita dapatkan langganan aktif dengan memanggil `getSubscription()`:

```
swRegistration.pushManager.getSubscription()
```

Ini mengembalikan promise yang diselesaikan dengan `PushSubscription` jika ada, jika tidak maka itu mengembalikan `null`. Jika ada langganan, kita memanggil `unsubscribe()` di atasnya, yang membuat `PushSubscription` menjadi tidak valid.

```
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
  if (subscription) {
    // TODO: Tell application server to delete subscription
    return subscription.unsubscribe();
  }
})
.catch(function(error) {
  console.log('Error unsubscribing', error);
})
```

Memanggil `unsubscribe()` akan mengembalikan promise, karena itu memerlukan beberapa saat untuk diselesaikan, kita mengembalikan promise tersebut sehingga `then()` berikutnya dalam rangkaian menunggu `unsubscribe()` untuk diselesaikan. Kita juga menambahkan penangan tangkap apabila pemanggilan `unsubscribe()` menghasilkan kesalahan. Setelah ini kita bisa memperbarui UI.

```
.then(function() {
  updateSubscriptionOnServer(null);

  console.log('User is unsubscribed.');
  isSubscribed = false;

  updateBtn();
})
```

#### Cobalah

Anda seharusnya bisa menekan  *Enable Push Messaging*  /  *Disable Push Messaging*  di aplikasi web Anda dan log akan menunjukkan pengguna yang berlangganan dan berhenti berlangganan.

![32acb7ec17ef75a8.png](img/32acb7ec17ef75a8.png)

## Selesai

Selamat telah menyelesaikan codelab ini!

Code lab ini menunjukkan kepada Anda cara bangun dan berjalan dengan menambahkan push ke aplikasi web Anda. Jika Anda ingin mengetahui selengkapnya tentang apa yang bisa dilakukan notifikasi web,  [lihat dokumen ini](/web/fundamentals/engage-and-retain/push-notifications/).

Jika Anda ingin menerapkan push pada situs, Anda mungkin tertarik untuk menambahkan dukungan bagi compliant browser lama / non-standar yang menggunakan GCM, [ketahui selengkapnya di sini](https://web-push-book.gauntface.com/chapter-06/01-non-standards-browsers/).

### Bacaan Lebih Lanjut

*  Dokumentasi [Pemberitahuan Push Web](/web/fundamentals/engage-and-retain/push-notifications/) pada Web__Fundamentals__
*  [Pustaka Web Push](https://github.com/web-push-libs/) - Pustaka Web Push termasuk Node.js, PHP, Java dan Python.

#### Entri blog terkait

*  [Enkripsi Payload Web Push](/web/updates/2016/03/web-push-encryption)
*  [Kunci Server Aplikasi dan Web Push](/web/updates/2016/07/web-push-interop-wins)
*  [Tindakan Notifikasi](/web/updates/2016/01/notification-actions)
*  [Ikon, Kejadian Tutup, Pemberitahuan-ulang Preferensi dan Stempel Waktu](/web/updates/2016/03/notifications)

## Menemukan masalah, atau memiliki masukan? {: .hide-from-toc }
Bantu kami menjadikan code lab lebih baik dengan mengirimkan
[masalah](https://github.com/googlechrome/push-notifications/issues) hari ini. Dan terima kasih!

{# wf_devsite_translation #}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Options</title>
<meta name="date" content="2022-02-10">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.printnode.api

Class Options

java.lang.Object

com.printnode.api.Options

public class Options
extends java.lang.Object

Object to be serailized into JSON in createPrintJob.

Constructor Summary

Constructors

Constructor and Description

Options()

Default constructor.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
setBin(java.lang.String newBin)

void
setCollate(boolean newCollate)

void
setCopies(int newCopies)

void
setDpi(java.lang.String newDpi)

void
setDuplex(java.lang.String newDuplex)

void
setFitToPage(boolean newFitToPage)

void
setMedia(java.lang.String newMedia)

void
setNup(int newNup)

void
setPages(java.lang.String newPages)

void
setPaper(java.lang.String newPaper)

void
setRotate(int newRotate)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Options

public Options()

Default constructor.

Method Detail

setBin

public final void setBin(java.lang.String newBin)

Parameters:

newBin - set the bin we want to use.

setCollate

public final void setCollate(boolean newCollate)

Parameters:

newCollate - Set whether we want to collate.

setCopies

public final void setCopies(int newCopies)

Parameters:

newCopies - Set the amount of copies we want to print.

setDpi

public final void setDpi(java.lang.String newDpi)

Parameters:

newDpi - Set the DPI.

setDuplex

public final void setDuplex(java.lang.String newDuplex)

Parameters:

newDuplex - Set the duplex.

setFitToPage

public final void setFitToPage(boolean newFitToPage)

Parameters:

newFitToPage - set whether we want to fit the content to the page.

setMedia

public final void setMedia(java.lang.String newMedia)

Parameters:

newMedia - Set the media for the printer.

setNup

public final void setNup(int newNup)

Parameters:

newNup - Set number of pages to print per page for a compact layout printing.

setPages

public final void setPages(java.lang.String newPages)

Parameters:

newPages - set the pages to print.

setPaper

public final void setPaper(java.lang.String newPaper)

Parameters:

newPaper - set paper type.

setRotate

public final void setRotate(int newRotate)

Parameters:

newRotate - set rotation. Can only be 90,180 or 270.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import { Category } from '../storiesHierarchy';

export const storySettings = {
  category: Category.SELECTION,
  storyName: '4.8 Slider',
  dataHook: 'story-slider',
};


text:
import Control.Monad
import Control.Monad.Logic.Class
import Control.Monad.Trans
import System.Environment
import System.IO

-- A micro-benchmark of LogicT measuring repeated reflection

-- the three implementations of Logic:

--import BeforeFix.Logic -- direct style implementation
--import Control.Monad.Logic -- two continuation implementation
import Fixed.Logic -- direct style implementation with our solution applied to it

seqN :: MonadLogic m => Int -> m a -> m [a]
seqN n m | n == 0     = return []
         | otherwise  = msplit m >>= \x -> case x of
                          Nothing    -> return []
                          Just (a,m) -> liftM (a:) $ seqN (n-1) m

nats = natsFrom 0 where
  natsFrom n = return n `mplus` natsFrom (n + 1)

bench n = observeT $ seqN n nats

main = do args <- getArgs
          let n = read (head args)
          bench n


text:
'use strict';

angular.module('dtuWork')
    .config(function ($stateProvider) {
        $stateProvider
            .state('contact', {
                parent: 'main',
                url: '/contact',
                views: {
                    'content@': {
                        templateUrl: 'main/script/contact/contact.html',
                        controller: 'ContactController'
                    }
                }
            });
    });


text:
package jp.ne.naokiur.design.pattern.mediator.character.notmediator;

import jp.ne.naokiur.design.pattern.mediator.Position;
import jp.ne.naokiur.design.pattern.mediator.Status;

public abstract class CharacterBase implements Character {
    private Position position;
    private Status status;

    public CharacterBase() {
        this.position = Position.FRONT;
        this.status = Status.ALIVE;
    }

    @Override
    public Status getStatus() {
        return this.status;
    }

    @Override
    public void setStatus(Status status) {
        this.status = status;
    }

    @Override
    public Position getPosition() {
        return this.position;
    }

    @Override
    public void setPosition(Position position) {
        this.position = position;
    }

    @Override
    public void cross() {
        switch (this.getPosition()) {
        case FRONT:
            this.setPosition(Position.BEYOND);

            break;

        case BEYOND:
            this.setPosition(Position.FRONT);

            break;

        default:
            break;
        }
    }

}


text:
package script.lua;

import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
import org.luaj.vm2.lib.jse.JsePlatform;

import script.Script;

public class LuaScript extends Script{

	static Globals globals = JsePlatform.standardGlobals();

	public LuaScript(String name){
		script = globals.loadfile("./res/script/lua/" + name + ".lua");
	}

	protected LuaValue script;

	@Override
	public void execute() {
		script.call();
	}

	public Globals getGlobals(){
		return globals;
	}

	public LuaValue getScript(){
		return script;
	}

	 public static LuaValue callFunction(String table, String functionName, Object[] objects) {

	        LuaValue luaFunction = globals.get(table).get(functionName);

	        if (luaFunction.isfunction()) {
	        	LuaValue[] parameters = new LuaValue[objects.length];

	        	for (int i = 0; i < objects.length; i++)
	        		parameters[i] = CoerceJavaToLua.coerce(objects[i]);

	        	try {
	        		return (LuaValue) luaFunction.invoke(parameters);
	        	} catch (LuaError e) {
	        		return e.getMessageObject();
	        	}
	        }
	        return LuaValue.valueOf("NO SUCH FUNCTION");
	    }

	public static LuaValue callFunction(String table, String name){
		return globals.get(table).get(name).call();
	}

	public static LuaValue callFunction(String table, String name, String arg1){
		return globals.get(table).get(name).call(arg1);
	}

	public static LuaValue callFunction(String table, String name, String arg1, String arg2){
		return globals.get(table).get(name).call(LuaValue.valueOf(arg1), LuaValue.valueOf(arg2));
	}
	public static LuaValue callFunction(String table, String name, String arg1, String arg2, String arg3){
		return globals.get(table).get(name).call(LuaValue.valueOf(arg1), LuaValue.valueOf(arg2), LuaValue.valueOf(arg3));
	}

	public static LuaValue callFunction(String table, String name, LuaValue arg1){
		return globals.get(table).get(name).call(arg1);
	}

	public static LuaValue callFunction(String table, String name, LuaValue arg1, LuaValue arg2){
		return globals.get(table).get(name).call(arg1, arg2);
	}

	public static LuaValue callFunction(String table, String name, LuaValue arg1, LuaValue arg2, LuaValue arg3){
		return globals.get(table).get(name).call(arg1, arg2, arg3);
	}

}


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>glif library multiple contexts example</title>

<link rel="stylesheet" type="text/css" href="../css/demo.css">

Multiple WebGL Contexts Example
glif library

source image

<canvas id="effect_canvas" height="504" width="423"></canvas>

contrast enhance

<canvas id="blur_canvas" height="504" width="423"></canvas>

blur

<canvas id="both_canvas" height="504" width="423"></canvas>

blur + contrast


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta http-equiv="Cache-Control" content="no-siteapp"/>
		<meta name="renderer" content="webkit" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
        <meta name="keywords" content="Editor.md,editor,Markdown Editor,Markdown,编辑器,Markdown编辑器,Markdown在线编辑器,在线编辑器,开源编辑器,开源Markdown编辑器" />
        <meta name="description" content="Editor.md: a simple online markdown editor. 开源在线 Markdown 编辑器" />
        <title>Page break - Editor.md examples</title>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="../css/editormd.css" />
        <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />

Page break

                <button id="print-btn">Print Test</button>
                <button id="disabled-btn">Disabled</button>
                <button id="enabled-btn">Enabled</button>

                <textarea style="display:none;">#### Syntax

    [At least 8 equals]

    [========]

#### Disabled

    {
        pageBreak : false
    }

#### Examples

[========]

> page start

#### Editor.md directory

    editor.md/
            lib/
            css/
            scss/
            tests/
            fonts/
            images/
            plugins/
            examples/
            languages/
            editormd.js
            ...

> page end
</textarea>


text:
package com.amazonaws.eclipse.ec2.ui;

import java.util.LinkedList;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;

import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.ec2.ShellCommandException;
import com.amazonaws.eclipse.ec2.ShellCommandResults;

/**
 * Dialog for showing the details of a failed attempt at executing a command,
 * including support for possible retries, and directing users to more help.
 */
public class ShellCommandErrorDialog extends MessageDialog {

    private final ShellCommandException sce;
    private Text outputText;
    private Text errorOutputText;
    private List<Button> attemptRadioButtons = new LinkedList<>();

    /**
     * Creates a new ShellCommandErrorDialog, ready to be opened and display
     * information the specified ShellCommandException.
     *
     * @param sce
     *            The ShellCommandException to display.
     */
    public ShellCommandErrorDialog(ShellCommandException sce) {
        super(Display.getDefault().getShells()[0],
                "Error Executing Command",
                null,
                sce.getMessage(),
                MessageDialog.ERROR,
                new String[] {"Ok"},
                1);

        this.sce = sce;
    }

    /* (non-Javadoc)
     * @see org.eclipse.jface.dialogs.MessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite)
     */
    @Override
    protected Control createCustomArea(Composite parent) {
        Composite composite = new Composite(parent, SWT.NONE);
        composite.setLayoutData(new GridData(GridData.FILL_BOTH));
        composite.setLayout(new GridLayout(1, false));

        if (sce.getNumberOfAttempts() > 1) {
            createAttemptSelectionArea(composite);
            attemptRadioButtons.get(0).setSelection(true);
        }
        createCommandOutputArea(composite);
        createHelpLinkArea(composite);

        update();

        return composite;
    }

    /*
     * Private Interface
     */

    /**
     * Creates a new UI section displaying a link where users can go for more
     * help.
     *
     * @param composite
     *            The parent composite for this new section.
     */
    private void createHelpLinkArea(Composite composite) {
        Link link = new Link(composite, SWT.WRAP);
        link.setText("Need help?  " +
                "http://aws.amazon.com/eclipse/");
        WebLinkListener webLinkListener = new WebLinkListener();
        link.addListener(SWT.Selection, webLinkListener);
    }

    /**
     * Creates a new UI section displaying the details of the selected attempt
     * to execute a command.
     *
     * @param composite
     *            The parent composite for this new section.
     */
    private void createCommandOutputArea(Composite composite) {
        Composite outputComposite = new Composite(composite, SWT.NONE);
        outputComposite.setLayout(new GridLayout(1, false));
        outputComposite.setLayoutData(new GridData(GridData.FILL_BOTH));

        Group outputGroup = new Group(outputComposite, SWT.None);
        outputGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
        outputGroup.setLayout(new GridLayout(2, false));
        outputGroup.setText("Command Output:");

        newLabel(outputGroup, "Output:");
        outputText = newText(outputGroup, "");

        newLabel(outputGroup, "Errors:");
        errorOutputText = newText(outputGroup, "");
    }

    /**
     * Creates a new UI section displaying a list of attempts that a user can
     * select to see more information.
     *
     * @param composite
     *            The parent composite for this new section.
     */
    private void createAttemptSelectionArea(Composite composite) {
        Composite attemptsComposite = new Composite(composite, SWT.NONE);
        attemptsComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        attemptsComposite.setLayout(new GridLayout(1, true));

        Group attemptsGroup = new Group(attemptsComposite, SWT.None);
        attemptsGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
        attemptsGroup.setLayout(new GridLayout(1, false));

        Label l = new Label(attemptsGroup, SWT.WRAP);
        l.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        l.setText("Select an attempt to see the output from it:");

        SelectionListener listener = new SelectionListener() {
            @Override
            public void widgetDefaultSelected(SelectionEvent e) {
            }

            @Override
            public void widgetSelected(SelectionEvent e) {
                update();
            }
        };

        attemptRadioButtons = new LinkedList<>();
        for (ShellCommandResults results : sce.getShellCommandResults()) {
            Button button = new Button(attemptsGroup, SWT.RADIO);
            button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
            attemptRadioButtons.add(button);

            button.addSelectionListener(listener);

            button.setText("Attempt " + attemptRadioButtons.size()
                    + "  (exit code: " + results.exitCode + ")");
            button.setData(results);
        }
    }

    /**
     * Returns the ShellCommandResults associated with the selected command
     * execution attempt.
     *
     * @return The ShellCommandResults associated with the selected attempt.
     */
    private ShellCommandResults getSelectedAttempt() {
        for (Button button : attemptRadioButtons) {
            if (button.getSelection()) {
                return (ShellCommandResults)button.getData();
            }
        }

        return sce.getShellCommandResults().get(0);
    }

    /**
     * Updates the command output section so that the correct output is
     * displayed based on what command execution attempt is selected.
     */
    private void update() {
        ShellCommandResults results = getSelectedAttempt();

        outputText.setText(results.output);
        errorOutputText.setText(results.errorOutput);
    }

    /**
     * Utility method for creating a Text widget.
     */
    private Text newText(Composite composite, String s) {
        Text text = new Text(composite, SWT.READ_ONLY | SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
        text.setText(s);

        GridData data = new GridData(GridData.FILL_BOTH);
        data.minimumHeight = 80;
        data.heightHint = 100;
        data.minimumWidth  = 100;
        data.widthHint = 250;
        text.setLayoutData(data);

        return text;
    }

    /**
     * Utility method for creating a Label widget.
     */
    private Label newLabel(Composite outputComposite, String text) {
        Label label = new Label(outputComposite, SWT.NONE);
        label.setText(text);

        GridData data = new GridData();
        data.verticalAlignment = SWT.TOP;
        label.setLayoutData(data);

        return label;
    }

}


text:
using System;
using System.Text;

namespace IsoscelesTriangle
{
    class IsoscelesTriangle
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            Console.WriteLine("   ©" + "\n");
            Console.WriteLine("  © ©" + "\n");
            Console.WriteLine(" ©   ©" + "\n");
            Console.WriteLine("© © © ©" + "\n");
        }
    }
}


text:
from bs4 import BeautifulSoup
from urllib import urlopen
r = urlopen('http://sports.sina.com.cn/nba/2015-04-23/00007584374.shtml').read()
soup = BeautifulSoup(r)

#there is javasciript things to be cleaned.
s = soup.find_all("a")
for link in s:
    try:
        print link["href"]
    except KeyError:
        pass


text:
class User < ActiveRecord::Base
  include SocialMediaAuthentication
  attr_accessor :login

  devise :database_authenticatable, :registerable, :omniauthable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable,
         :omniauth_providers => [:google_oauth2]

         def self.find_for_database_authentication(conditions)
     email_name_regex  = '[\w\.%\+\-]+'.freeze
     domain_head_regex = '(?:[A-Z0-9\-]+\.)+'.freeze
     domain_tld_regex  = '(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|jobs|museum)'.freeze
     email_regex       = /\A#{email_name_regex}@#{domain_head_regex}#{domain_tld_regex}\z/i

    logger.debug "find_for_database_authentication:#{conditions.inspect}"

    login = conditions.delete(:login)
    login = conditions.delete(:name) if login.blank?

    if login =~ /^\d+$/ && login.length != 11
       u = where(conditions).where(["code = :login", {:login => login}]).first
       where(conditions).where(["name  = :login", {:login => login}]).first if u.nil?
    elsif  login =~ /^\d+$/ && login.length == 11
      where(conditions).where(["mobile = :login", {:login => login}]).first
    elsif login =~ email_regex
      where(conditions).where(["email = :login", {:login => login}]).first
    else
      where(conditions).where(["name  = :login", {:login => login}]).first
    end
  end
end


text:
gopaci
======

Parallels PACI API implementation in Go


text:
{% extends 'admin/model/list.html' %}

{% macro new_actions(actions, btn_class='btn dropdown-toggle') -%}
    {% for p in actions %}

        {{ _gettext(p[1]) }} Selected

    {% endfor %}
{% endmacro %}

{% block model_menu_bar %}
    {% if actions %}

            {{ _gettext('List') }} ({{ count }})

        {% if admin_view.can_create %}

            {{ _gettext('Create') }}

        {% endif %}

        {% if filters %}

            {{ model_layout.filter_options() }}

        {% endif %}

        {% if admin_view.new_actions %}

            {{ actionlib.dropdown(actions) }}

        {% elif actions %}
            {{ new_actions(actions) }}
        {% endif %}

        {% if search_supported %}

            {{ model_layout.search_form() }}

        {% endif %}

    {% endif %}
{% endblock %}

{% block list_row_actions_header %}
    {% if admin_view.can_edit or admin_view.can_delete %}

    {% endif %}
{% endblock %}

{% block list_row_actions_column scoped %}
    {% if admin_view.can_edit or admin_view.can_delete %}

        {% block list_row_actions scoped %}
            {%- if admin_view.can_edit -%}

            {%- endif -%}
            {%- if admin_view.can_delete -%}
            <form class="icon" method="POST" action="{{ get_url('.delete_view') }}">
                {{ delete_form.id(value=get_pk_value(row)) }}
                {{ delete_form.url(value=return_url) }}
                {{ delete_form.csrf_token }}
                <button onclick="return confirm('{{ _gettext('Are you sure you want to delete this record?') }}');" title="Delete record">

                </button>
            </form>
            {%- endif -%}
        {% endblock %}

    {%- endif -%}
{% endblock %}


text:
<template name="appBody">

萤火虫听英语

萤火虫听英语 可以听的英文名著

萤火虫听英语 听着听着就睡着了

          Home

          大家
正在听

          名著

          收藏

          关于我们

          登录

          登出

        {{#unless connected}}

Trying to connect

        {{/unless}}
        {{#each notifications}}

            {{action}}

{{title}}

        {{/each}}

    {{> overlay}}

        {{#BackButton}}

        {{/BackButton}}
      {{> yield}}

</template>


text:
<resources>

    <!-- App -->
    <string name="app_name">Scan4Review</string>
    <string name="loading">Loading</string>
    <string name="sending">Sending</string>
    <string name="yes">Yes</string>
    <string name="no">No</string>
    <string name="not_found">Not Found</string>
    <string name="anoname">Anonymous</string>
    <string name="send">Send</string>
    <string name="copiedcb">URL has been copied to clipboard</string>

    <!--Main Fragment-->
    <string name="main_h1">Do you want to know if the purchase is worth it?</string>
    <string name="main_h2">Just scan de barcode and find out.</string>
    <string name="button_scan">Scan</string>
    <string name="button_manual">Manually</string>
    <string name="enter_barcode_hint">Write The Barcode Of The Product</string>
    <string name="barcode">Barcode</string>
    <string name="search">Search</string>
    <string name="cancel">Cancel</string>

    <!--About-->
    <string name="action_about">About</string>
    <string name="about_text">
        This app will provide you with experiences from other user with some products, allowing you to decide if it suits your needs.\n\n
        Created by Eloy Barcia Durán\n
        Apache License 2.0\n
        Graphic Resources by Freepik
    </string>

    <!-- Camera-->
    <string name="camera_not_found">Camera not found!</string>
    <string name="scanning">Scanning...</string>

    <!--Info Activity -->
    <string name="drawer_open">open</string>
    <string name="drawer_close">close</string>

    <!--Navigation Items-->
    <string-array name="nd_items">
        <item>Scan4Review</item>
        <item>Amazon</item>
        <item>Amazon UK</item>
        <item>Amazon ES</item>
        <item>Amazon MX</item>
        <item>Amazon JP</item>
        <item>Google</item>
    </string-array>

    <!--Info Fragment-->
    <string name="action_addCom">Add</string>
    <string name="prod_image">Product Image</string>
    <string name="prod_descr">Product Description</string>
    <string name="prod_not_found">Product Not Found</string>
    <string name="prod_not_found_mess">Do you want to add it?</string>
    <string name="date_format">yyyy-MM-dd HH:mm:ss</string>

    <!-- Web Fragment -->
    <string name="amazon">Amazon</string>
    <string name="amazon_url">http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=</string>
    <string name="amazonUK">Amazon UK</string>
    <string name="amazonuk_url">http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=</string>
    <string name="amazonES">Amazon ES</string>
    <string name="amazones_url">http://www.amazon.es/s/ref=nb_sb_noss?__mk_es_ES=ÅMÅŽÕÑ&url=search-alias%3Daps&field-keywords=</string>
    <string name="amazonMX">Amazon MX</string>
    <string name="amazonmx_url">https://www.amazon.com.mx/s/ref=nb_sb_noss/192-8854717-5369709?__mk_es_MX=ÅMÅŽÕÑ&url=search-alias%3Daps&field-keywords=</string>
    <string name="amazonJP">Amazon JP</string>
    <string name="amazonjp_url">http://www.amazon.co.jp/s/ref=nb_sb_noss_2/377-0653209-5306825?__mk_ja_JP=カタカナ&url=search-alias%3Daps&field-keywords=</string>
    <string name="google">Google</string>
    <string name="google_url">https://www.google.com/#q=</string>
    <string name="copylabel">Copy URL To Clipboard</string>
    <string name="browserlabel">Open With Browser</string>

    <!-- New Product -->
    <string name="new_product">New Product</string>
    <string name="img_error_mess">Error uploading image, try again</string>
    <string name="img_take_mess">Please, take a photo of the product before send</string>
    <string name="np_prod_hint">Enter Product Name</string>
    <string name="np_prod_label">Product:</string>
    <string name="np_photo">Photo</string>
    <string name="np_descr_hint">Enter Product Description</string>
    <string name="np_descr_label">Description:</string>

    <!-- New Comment -->
    <string name="new_comment">New Comment</string>
    <string name="nc_user_hint">Enter User Name (Empty for Anonymous)</string>
    <string name="nc_user_label">User Name:</string>
    <string name="nc_rev_hint">Write Your Review</string>
    <string name="nc_rev_label">Review:</string>

</resources>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>hu.progtech.cd2t100</groupId>
	<artifactId>cd2t-100-game-shared</artifactId>
	<version>1.0</version>
	<name>CD2T-100 Game Shared Classes</name>
	<description>Module providing classes to utilize the CD2T-100 Core in a game.</description>

	<parent>
		<groupId>hu.progtech.cd2t100</groupId>
		<artifactId>cd2t-100-parent</artifactId>
		<version>1.0</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>hu.progtech.cd2t100</groupId>
			<artifactId>cd2t-100-core</artifactId>
			<version>1.0</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
<?xml version="1.0"?>

<!--
   Copyright 2008 - 2011 University of Rochester

   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.
-->

<!DOCTYPE hibernate-mapping SYSTEM
			"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
	Mapping for invite information

	@author Sharmila Ranganathan
-->
<hibernate-mapping package="edu.ur.ir.user">
	<class name="FileInviteInfo" schema="ir_user"
	    table="invite_info"
		lazy="true">

		<!-- Common id property. -->
		<id name="id" type="long" column="invite_info_id"
			unsaved-value="0" access="field">
			<generator class="sequence">
				<param name="sequence">ir_user.invite_info_seq</param>
			</generator>
		</id>

		<!-- A versioned entity. -->
		<version name="version" column="version"
			access="org.hibernate.property.DirectPropertyAccessor" />

		<!--  invite token -->
		<many-to-one class="edu.ur.ir.invite.InviteToken"
			name="inviteToken"
			column="invite_token_id"
			cascade="all"
			unique="true"
			access="field"/>

		<!-- files to share -->
		<set name="files"
		     table="ir_user.invite_files"
		     access="field" >
			<key column="invite_info_id" />
			<many-to-many column="versioned_file_id" class="edu.ur.ir.file.VersionedFile"/>
		</set>

		<!-- permissions on files -->
		<set name="permissions"
		     table="ir_user.invite_permissions"
		     access="field" >
			<key column="invite_info_id" />
			<many-to-many column="class_type_permission_id" class="edu.ur.ir.security.IrClassTypePermission"/>
		</set>

    </class>

    <!-- named query for getting invite information for given token-->
    <query name="findInviteInfoForToken">from FileInviteInfo inviteInfo
        where inviteInfo.inviteToken.token = :token </query>

    <!-- named query for getting invite information for given email -->
    <query name="findInviteInfoForEmail">from FileInviteInfo inviteInfo
        where lower(inviteInfo.inviteToken.email) = :email </query>

    <!-- named query for getting invite information made by a given user -->
    <query name="getInviteInfoMadeByUser">from FileInviteInfo inviteInfo
        where inviteInfo.inviteToken.invitingUser.id = :userId </query>

    <!-- named query for getting all invites with a particular versioned file id -->
    <query name="getInviteInfosWithVersionedFilesAndEmail">select distinct(inviteInfo) from FileInviteInfo as inviteInfo
        join inviteInfo.files as versionedFile
        where versionedFile.id in (:versionedFileIds)
        and lower(inviteInfo.inviteToken.email) = :email </query>

    <!--  Get a count of roles in the system -->
	<query name="inviteInfoCount">
	    select count(*) from FileInviteInfo
	</query>

		<!-- sort by last name asc -->
	<query name="getInviteInfosOrderByInvitorAsc">
		select inviteInfo from FileInviteInfo as inviteInfo
		order by inviteInfo.inviteToken.invitingUser.lowerCaseLastName asc,
		inviteInfo.inviteToken.invitingUser.lowerCaseFirstName asc,
		inviteInfo.inviteToken.invitingUser.lowerCaseMiddleName asc
	</query>

	<!-- sort by last name desc -->
	<query name="getInviteInfosOrderByInvitorDesc">
		select inviteInfo from FileInviteInfo as inviteInfo
		order by inviteInfo.inviteToken.invitingUser.lowerCaseLastName desc,
		inviteInfo.inviteToken.invitingUser.lowerCaseFirstName desc,
		inviteInfo.inviteToken.invitingUser.lowerCaseMiddleName desc
	</query>

</hibernate-mapping>


text:
If you are new to Trails, these topics are approximately in order. Begin your Journey by clicking [**Start**](/doc/en/start)!

1. [Start](/start)
2. [Build](/doc/en/build/)
  - [Controller](/doc/en/build/controller)
  - [Service](/doc/en/build/service)
  - [Policy](/doc/en/build/policy)
  - [Model](/doc/en/build/model)
  - [Resolver](/doc/en/build/resolver)
3. [Configure](/doc/en/config/)
  - [index](/doc/en/config/manifest)
  - [main](/doc/en/config/main)
  - [log](/doc/en/config/log)
  - [routes](/doc/en/config/routes)
  - [stores](/doc/en/config/stores)
  - [i18n](/doc/en/config/i18n)
  - [web](/doc/en/config/web)
4. [Test](/doc/en/test/)
  - [Introduction](/doc/en/test/intro)
  - [Unit Testing](/doc/en/test/unit)
  - [Integration Testing](/doc/en/test/integration)
5. [Debug](/doc/en/debug/)
6. [Deploy](/doc/en/deploy/)
  - [Requirements](/doc/en/deploy/requirements)
  - [Providers](/doc/en/deploy/providers)
  - [Security](/doc/en/deploy/security)
  - [Scaling](/doc/en/deploy/scaling)
7. [Extend](/doc/en/extend/)
  - [Trailpacks](/doc/en/extend/trailpack)
  - [Re-usable Services](/doc/en/extend/service)
  - [Server-Side Rendering](/doc/en/extend/views/)
  - [Authentication](/doc/en/extend/users/)
8. [Upgrade](/doc/en/upgrade/)
  - [Application](/doc/en/upgrade/app)
  - [Trailpack](/doc/en/upgrade/trailpack)
9. [API Reference](/doc/en/ref/)
  - [Trails](/doc/en/ref/trails)
  - [Trailpack](/doc/en/ref/trailpack)
  - [Controller](/doc/en/ref/controller)
  - [Service](/doc/en/ref/service)
  - [Model](/doc/en/ref/model)
  - [Resolver](/doc/en/ref/resolver)
  - [Policy](/doc/en/ref/policy)
  - [Reserved Keywords](/doc/en/ref/reserved)
10. [About Trails](/doc/en/about/)
  - [What is Trails?](/doc/en/about/trails)
  - [Design Theory](/doc/en/about/theory)
  - [Release Schedule](/doc/en/about/schedule)
  - [Contributing](/doc/en/about/contribute)
11. [Support](/support)


text:
//
//  QCWeChatSignAdaptor.h
//  QCWeChatPay
//
//  Created by JHQ0228 on 2016/12/20.
//  Copyright © 2016年 QianQian-Studio. All rights reserved.
//

/**
 *  微信支付签名工具类
 */

#import <Foundation/Foundation.h>

@interface QCWeChatSignAdaptor : NSObject

@property (nonatomic,strong) NSMutableDictionary *dic;

- (instancetype)initWithWechatAppId:(NSString *)wechatAppId
                        wechatMCHId:(NSString *)wechatMCHId
                            tradeNo:(NSString *)tradeNo
                   wechatPartnerKey:(NSString *)wechatPartnerKey
                           payTitle:(NSString *)payTitle
                           orderNo :(NSString *)orderNo
                           totalFee:(NSString *)totalFee
                           deviceIp:(NSString *)deviceIp
                          notifyUrl:(NSString *)notifyUrl
                          tradeType:(NSString *)tradeType;

/// 创建发起支付时的 sign 签名(二次签名)
- (NSString *)createMD5SingForPay:(NSString *)appid_key
                        partnerid:(NSString *)partnerid_key
                         prepayid:(NSString *)prepayid_key
                          package:(NSString *)package_key
                         noncestr:(NSString *)noncestr_key
                        timestamp:(UInt32)timestamp_key;

@end


text:
<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>test</groupId>
  <artifactId>basic-resolveDependencies.xml</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>org.apache.maven.its</groupId>
      <artifactId>a</artifactId>
      <version>0.1</version>
    </dependency>
  </dependencies>
</project>


text:
Ti=Accountability

sec=

{Base.sec}

{Tracking.sec}

{Personnel.sec}

{Practice.sec}

{Communicate.sec}

Base.sec=All persons and organizations are accountable for promoting and protecting {_data} privacy and security, including when {_data} are shared with {_data_user}s, repositories, and service providers.

Tracking.sec=Data stewards should keep track of all whereabouts of the {_data} and the persons and/or organizations with access to the {_data}.

Personnel.sec=Data stewards should clearly identify the individuals within their organization who are responsible for {_data} privacy, {_data} management, and reporting procedures (including a contact person or contact point for complaints). Appropriate and regular training for the identified individuals to discharge these duties should be provided.

Practice.sec=Data stewards should track relevant new laws, regulations, policies, expectations, and best practices, sharing these with responsible individuals within their organization or entity, and with {_data_user}s as appropriate.

Communicate.sec=Where relevant, ongoing communication links should be maintained between {_data_steward}s, {_data_user}s, and research ethics committees and/or {_data} access committees.

=[G/Z/Base]


text:
#pragma once

#include "VectorMath.h"
#include "ColliderComponent.h"

namespace ECSE {

//! A Component which stores line collision mask data.
class LineColliderComponent : public ColliderComponent
{
public:
    //! This is an extension of ColliderComponent.
    using ExtendsComponent = ColliderComponent;

    sf::Vector2f vec;       //!< The vector representing the difference between the line's start and end positions.

    //! Set the line's end point using a polar offset from the start.
    /*!
    * \param angle The angle of the line.
    * \param length The length of the line.
    */
    inline void setPolar(float angle, float length)
    {
        vec = sf::Vector2f(cos(angle) * length,
                                -sin(angle) * length);
    }

    //! Get the line's length (magnitude).
    /*!
    * \return The line's length.
    */
    inline float getLength()
    {
        return getMagnitude(vec);
    }

    //! Get the line's angle.
    /*!
    * \return The line's angle.
    */
    inline float getAngle()
    {
        return getHeading(vec);
    }
};

}


text:
from .base import *

try:
	from .local import *
except ImportError:
	pass


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Pyccuweather: pyccuweather.objects.Observation Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Pyccuweather
    0.31

The Python Accuweather Client

Main Page

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

pyccuweather

objects

Observation

Public Member Functions |
Public Attributes |
List of all members

pyccuweather.objects.Observation Class Reference

Inheritance diagram for pyccuweather.objects.Observation:

  <map id="pyccuweather.objects.Observation_map" name="pyccuweather.objects.Observation_map">
</map>

Public Member Functions

def 	__init__ (self, json)

def 	__str__ (self)

Public Attributes

 	date_time

 	epoch_time

 	synopsis

 	temperature

 	link

 	mobile_link

 	raw

The documentation for this class was generated from the following file:

pyccuweather/objects.py

<address class="footer">
Generated on Sat Jul 4 2015 17:36:10 for Pyccuweather by

 1.8.9.1
</address>