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

class KelolaMember extends CI_Controller {

	public function _construct()
	{
		parent::_construct();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->library('input');
		$this->load->library('form_validation');
		$this->load->library('session');

	}

	public function index()
	{
		if($this->session->userdata('admin_logged_in')){
		$this->load->model('member_models/MemberModels');
		$data['listMember'] = $this->MemberModels->get_data_member();

		$this->load->view('skin/admin/header_admin');
		$this->load->view('skin/admin/nav_kiri');
		$this->load->view('content_admin/kelola_member', $data);
		$this->load->view('skin/admin/footer_admin');
		} else {
			redirect(site_url('Account'));
		}
	}

	//Delete Data
	public function delete_member()//$id_produk
	{
		$id_member = $_POST['id_member'];
		$this->load->model('member_models/MemberModels');
		$this->MemberModels->delete_member($id_member);

		$this->index();
	}

	//Delete Data detail produk
	public function delete_detail_member($id_member)//
	{
		$this->load->model('member_models/MemberModels');
		$this->MemberModels->delete_member($id_member);

		redirect(site_url('KelolaMember'));
	}

	//Lihat detail produk
	public function lihat_detail_member($id_member)
	{	if($this->session->userdata('admin_logged_in')){
		$this->load->model('member_models/MemberModels');

		//Ambil id_agenda yang akan diedit

		$member=$this->MemberModels->select_by_id_member($id_member);
		$data['id_member'] = $member['id_member'];
		$data['nama_member'] = $member['nama_member'];
		$data['username'] = $member['username'];
		$data['email'] = $member['email'];
		$data['telepon'] = $member['telepon'];
		$data['status'] = $member['status'];
		$data['date_join'] = $member['date_join'];
		$data['path_foto'] = $member['path_foto'];

		$this->load->view('skin/admin/header_admin');
		$this->load->view('skin/admin/nav_kiri');
		$this->load->view('content_admin/detail_member', $data);
		$this->load->view('skin/admin/footer_admin');
		} else {
			redirect(site_url('Account'));
		}
	}

	//Validasi member
	public function validasi_member()
	{	if($this->session->userdata('admin_logged_in')){
		$this->load->model('member_models/MemberModels');
		$data['listMember'] = $this->MemberModels->get_data_member_pend();

		$this->load->view('skin/admin/header_admin');
		$this->load->view('skin/admin/nav_kiri');
		$this->load->view('content_admin/validasi_member', $data);
		$this->load->view('skin/admin/footer_admin');
		} else {
			redirect(site_url('Account'));
		}
	}

	//Setujui member
	public function setuju_member()
	{
		$id_member = $_POST['id_member'];
		$this->load->model('member_models/MemberModels');
		$this->MemberModels->setuju_member($id_member);
		$member = $this->MemberModels->select_by_id($id_member)->row();
		$nama_member = $member->nama_member;
		$username = $member->username;
		$email  = $member->email;
		$telepon = $member->telepon;

		$sub_setuju = 'Pendaftaran Member Boloku.id';
		$msg_setuju = 'Selamat sekarang Kamu sudah menjadi boloku.

';
		$msg_setuju .= 'Berikut data diri Anda,
 ';
		$msg_setuju .= 'Nama :'.$nama_member.'
';
		$msg_setuju .= 'Username :'.$username.'
';
		$msg_setuju .= 'Email :'.$email.'
';
		$msg_setuju .= 'Telepon :'.$telepon.'

';

		$this->kirim_email($sub_setuju,$msg_setuju,$email);
		$this->validasi_member();
	}

	//Setujui member
	public function setuju_detail_member($id_member)
	{
		$this->load->model('member_models/MemberModels');
		$this->MemberModels->setuju_member($id_member);
		$member = $this->MemberModels->select_by_id($id_member)->row();
		$nama_member = $member->nama_member;
		$username = $member->username;
		$email  = $member->email;
		$telepon = $member->telepon;

		$sub_setuju = 'Pendaftaran Member Boloku.id';
		$msg_setuju = 'Selamat sekarang Anda sudah menjadi boloku.

';
		$msg_setuju .= 'Berikut data diri Anda,
 ';
		$msg_setuju .= 'Nama :'.$nama_member.'
';
		$msg_setuju .= 'Username :'.$username.'
';
		$msg_setuju .= 'Email :'.$email.'
';
		$msg_setuju .= 'Telepon :'.$telepon.'

';

		$this->kirim_email($sub_setuju,$msg_setuju,$email);
		$this->validasi_member();
	}

	//Tolak Data
	public function tolak_member()
	{
		$id_member = $_POST['id_member'];
		$this->load->model('member_models/MemberModels');

		$member = $this->MemberModels->select_by_id($id_member)->row();
		$nama_member = $member->nama_member;
		$username = $member->username;
		$email  = $member->email;
		$telepon = $member->telepon;

		$sub_tolak = 'Pendaftaran Member Boloku.id';
		$msg_tolak = 'Mohon maaf Anda belum bisa menjadi Boloku.

';

		$this->kirim_email($sub_tolak,$msg_tolak,$email);
		$this->MemberModels->delete_member($id_member);
		$this->validasi_member();
	}

	//Tolak Data
	public function tolak_detail_member($id_member)
	{
		$this->load->model('member_models/MemberModels');

		$member = $this->MemberModels->select_by_id($id_member)->row();
		$nama_member = $member->nama_member;
		$username = $member->username;
		$email  = $member->email;
		$telepon = $member->telepon;

		$sub_tolak = 'Pendaftaran Member Boloku.id';
		$msg_tolak = 'Mohon maaf Anda belum bisa menjadi Boloku.

';

		$this->kirim_email($sub_tolak,$msg_tolak,$email);
		$this->MemberModels->delete_member($id_member);
		$this->validasi_member();
	}

	//kirim email
    function kirim_email($sub, $msg, $email) {
      $config['protocol'] = 'smtp';
      $config['smtp_host'] = 'mail.boloku.id'; //change this
      $config['smtp_port'] = '465';
      $config['smtp_user'] = 'info@boloku.id'; //change this
      $config['smtp_pass'] = 'cz431081994'; //change this
      $config['mailtype'] = 'html';
      $config['charset'] = 'iso-8859-1';
      $config['smtp_crypto'] = 'ssl';
      $config['wordwrap'] = TRUE;
      $config['newline'] = "\r\n"; //use double quotes to comply with RFC 822 standard
      $this->load->library('email'); // load email library
      $this->email->initialize($config);
      $this->email->from('info@boloku.id', 'boloku.id');
      $this->email->to($email);
      $this->email->subject($sub);
      $this->email->message($msg);
      if ($this->email->send()){
         $this->session->set_flashdata('msg_berhasil', 'Pesan balasan telah terkirim.');
         //redirect('FrontControl_ContactUs/kelola_message');
         }
      else{
         show_error($this->email->print_debugger());}
    }

	//tambah member soon
	public function tambah_member()
	{	if($this->session->userdata('admin_logged_in')){
		$this->load->model('member_models/MemberModels');

		$this->load->view('skin/admin/header_admin');
		$this->load->view('skin/admin/nav_kiri');
		$this->load->view('content_admin/tambah_member');
		$this->load->view('skin/admin/footer_admin');
		} else {
			redirect(site_url('Account'));
		}
	}

	function tambah_member_check() {
		if($this->session->userdata('admin_logged_in')){
        $this->load->model('member_models/MemberModels');
		$this->load->library('form_validation');

		$tambah = $this->input->post('submit');

		if ($tambah == 1)
		{
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('nama_member', 'Nama Member', 'required');
			$this->form_validation->set_rules('email', 'Email', 'required');
			$this->form_validation->set_rules('telepon', 'Telepon', 'required');

			/*if ($this->form_validation->run() == TRUE)
			{*/		$data_member=array(
						'username'=>$this->input->post('username'),
						'nama_member'=>$this->input->post('nama_member'),
						'password'=>md5($this->input->post('nama_member')),
						'email'=>$this->input->post('email'),
						'date_join'=>date("Y-m-d h:i:sa"),
						'telepon'=>$this->input->post('telelpon'),
						'path_foto'=>0,
						'status'=>1
					);
					$data['dataMember'] = $data_member;
				if($this->db->insert('member', $data_member))
				{
					$this->session->set_flashdata('msg_berhasil', 'Selamat, kowe wis dadi boloku ndes. Monggo LOGIN');
					redirect('KelolaMember');
				}
				else
				{
					$this->session->set_flashdata('msg_gagal', 'Data member gagal ditambahkan');

					$this->load->view('skin/admin/header_admin');
					$this->load->view('skin/admin/nav_kiri');
					$this->load->view('content_admin/tambah_member', $data);
					$this->load->view('skin/admin/footer_admin');
				}
			/*}
			else
			{
				$this->session->set_flashdata('msg_gagal', 'Data Youth member gagal ditambahkan');
				$this->tambah_member_check();
			}*/
		}
		else
		{
			$this->load->view('skin/admin/header_admin');
			$this->load->view('skin/admin/nav_kiri');
			$this->load->view('content_admin/tambah_member');
			$this->load->view('skin/admin/footer_admin');
		}
		} else {
			redirect(site_url('Account'));
		}

	}

	function cari_kata($kata) {
		$kata=str_replace('%20',' ',$kata);
        header('Access-Control-Allow-Origin: *');
        header('Content-type: text/xml');

        //var_dump($search_term); exit();
        $get_kata=$this->db->like('jawa',$this->db->escape_like_str($kata))->get('member');

        $this->load->helper('xml');
		$xml_out = '<kosakata>';
        if ($get_kata->num_rows()>0) {
            foreach ($get_kata->result() as $row_kata) {
                $xml_out .= '<kata ';
                $xml_out .= 'id="' . xml_convert($row_kata->id_member) . '" ';
                $xml_out .= 'jawa="' . xml_convert($row_kata->jawa) . '" ';
                $xml_out .= 'indonesia="' . xml_convert(($row_kata->indonesia)) . '" ';
                $xml_out .= 'deskripsi_jawa="' . xml_convert(($row_kata->deskripsi_jawa)) . '" ';
                $xml_out .= '/>';
            }
        }

		$xml_out .= '</kata>';

        echo $xml_out;

    }
	//Fungsi melakukan update pada database
	public function edit_member($id_member)
	{	if($this->session->userdata('admin_logged_in')){
		$this->load->model('member_models/MemberModels');
		$this->load->library('form_validation');

		$edit = $this->input->post('save');

		if (isset($_POST['save']))
		{
			if($this->input->post('passwordbaru')==NULL){
				$password=$this->input->post('passwordlama');
			} else{
				$password=md5($this->input->post('passwordbaru'));
			}
			$id_member = $this->input->post('id_member');

			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('nama_member', 'Nama_Member', 'required');
			$this->form_validation->set_rules('email', 'email', 'required');
			$this->form_validation->set_rules('telepon', 'Telepon', 'required');

			//Mengambil filename gambar untuk disimpan
			$nmfile = "file_".time();
			$config['upload_path'] = './asset/upload_img_member/';
			$config['allowed_types'] = 'jpg|png|jpeg';
			$config['max_size'] = '4000'; //kb
			$config['file_name'] = $nmfile;

			$data['username'] = $this->input->post('username');
			$data['nama_member'] = $this->input->post('nama_member');
			$data['email'] = $this->input->post('email');
			$data['telepon'] = $this->input->post('telepon');
			$data['password'] = $password;

			$data_member=array(
							'username'=>$this->input->post('username'),
							'nama_member'=>$this->input->post('nama_member'),
							'email'=>$this->input->post('email'),
							'telepon'=>$this->input->post('telepon'),
							'password'=>$password
							);

			//value id_koridor berisi beberapa data, sehingga dilakukan split dengan explode
			if (($this->form_validation->run() == TRUE))
			{
				$gbr = NULL;
				$iserror = false;
				if ((!empty($_FILES['filefoto']['name']))) {

					$this->load->library('upload', $config);
					if($this->upload->do_upload('filefoto'))
					{
						//echo "Masuk";
						$gbr = $this->upload->data();

						$data_member['path_foto'] = $gbr['file_name'];

					}
					else
					{
						$this->session->set_flashdata('msg_gagal', 'Data member gagal diperbaharui');
						$iserror = true;
					}

				}
				if (!$iserror) {
					$this->db->update('member', $data_member, array('id_member'=>$id_member));
					$this->session->set_flashdata('msg_berhasil', 'Data member berhasil diperbaharui');
					redirect('KelolaMember');
				}
			}
			else
			{
				$this->session->set_flashdata('msg_gagal', 'Data member gagal diperbaharui');
				//$this->edit_member();
			}
		}
		else
		{
			$member = $this->MemberModels->select_by_id_member($id_member);
			$data['username'] = $member['username'];
			$data['nama_member'] = $member['nama_member'];
			$data['email'] = $member['email'];
			$data['telepon'] = $member['telepon'];
			$data['password'] = $member['password'];
			$data['path_foto'] = $member['path_foto'];
			/*$data_member=array(
							'username'=>$data['member']->username,
							'nama_member'=>$data['member']->nama_member,
							'email'=>$data['member']->email,
							'password'=>$data['member']->password,
							'path_foto'=> $data['member']->path_foto
							);
			$data['dataMember'] = $data_member;*/

		}
		$data['idMember'] = $id_member;
		$this->load->view('skin/admin/header_admin');
		$this->load->view('skin/admin/nav_kiri');
		$this->load->view('content_admin/edit_member', $data);
		$this->load->view('skin/admin/footer_admin');
		} else {
			redirect(site_url('Account'));
		}
	}

	//Masuk ke halaman registrasi
	public function registrasi_member_baru()
	{
		$this->load->view('skin/front_end/header_front_end');
        $this->load->view('content_front_end/register_member_page');
        $this->load->view('skin/front_end/footer_front_end');
	}

	function member_baru_check() {
        $this->load->model('member_models/MemberModels');
		$this->load->library('form_validation');

		$tambah = $this->input->post('submit');

		if ($tambah == 1)
		{
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('nama_member', 'Nama Member', 'required');
			$this->form_validation->set_rules('email', 'Email', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			$this->form_validation->set_rules('pertanyaan', 'Pertanyaan', 'required');
			$this->form_validation->set_rules('jawaban', 'Jawaban', 'required');

			/*if ($this->form_validation->run() == TRUE)
			{*/		$data_member=array(
						'username'=>trim($this->input->post('username')),
						'nama_member'=>trim($this->input->post('nama_member')),
						'password'=>md5($this->input->post('password')),
						'email'=>trim($this->input->post('email')),
						'telepon'=>$this->input->post('telepon'),
						'pertanyaan_rahasia'=>$this->input->post('pertanyaan'),
						'jawaban_rahasia'=>trim($this->input->post('jawaban')),
						'date_join'=>date("Y-m-d h:i:sa"),
						'path_foto'=>0,
						'status'=>1
					);
					$data['dataMember'] = $data_member;
				if($this->db->insert('member', $data_member))
				{

				    $sub = 'Pendaftaran Member Boloku.id';
            		$msg = 'Selamat sekarang Kamu sudah menjadi boloku.

';
            		$msg .= 'Berikut data diri Anda,
 ';
            		$msg .= 'Nama :'.trim($this->input->post('nama_member')).'
';
            		$msg .= 'Username :'.trim($this->input->post('username')).'
';
            		$msg .= 'Email :'.trim($this->input->post('email')).'
';
            		$msg .= 'Telepon :'.trim($this->input->post('telepon')).'

';

            		$this->kirim_email($sub,$msg,trim($this->input->post('email')));
					$this->session->set_flashdata('msg_berhasil', 'Selamat, kowe wis dadi boloku saiki');
					$this->load->view('skin/front_end/header_front_end');
					$this->load->view('content_front_end/register_member_page');
					$this->load->view('skin/front_end/footer_front_end');

				}
				else
				{
					$this->session->set_flashdata('msg_gagal', 'Data member gagal ditambahkan');

					$this->load->view('skin/front_end/header_front_end');
					$this->load->view('content_front_end/register_member_page',$data);
					$this->load->view('skin/front_end/footer_front_end');
				}
			/*}
			else
			{
				$this->session->set_flashdata('msg_gagal', 'Data Youth member gagal ditambahkan');
				$this->tambah_member_check();
			}*/
		}
		else
		{
			$this->load->view('skin/front_end/header_front_end');
			$this->load->view('content_front_end/register_member_page');
			$this->load->view('skin/front_end/footer_front_end');
		}

	}

	public function reset_password_member()
	{
		$this->load->view('skin/front_end/header_front_end');
        $this->load->view('content_front_end/reset_password_member');
        $this->load->view('skin/front_end/footer_front_end');
	}

	//Masuk ke dashboard member
	public function dashboard_member()
	{
		if($this->session->userdata('is_logged_in')){
		$id_member = $this->session->userdata('id_member');
		$this->load->model('member_models/MemberModels');
		$this->load->model('home_models/HomeModels');
		$this->load->model('coming_models/ComingModels');

		$data['kotaLokasi'] = $this->ComingModels->kota_lokasi();
		$member=$this->MemberModels->select_by_id_member($id_member);
		$data['id_member'] = $member['id_member'];
		$data['nama_member'] = $member['nama_member'];
		$data['username'] = $member['username'];
		$data['email'] = $member['email'];
		$data['telepon'] = $member['telepon'];
		$data['path_foto'] = $member['path_foto'];
		$data['password'] = $member['password'];

		$kategori_coming = array(
							  'Seni'=>'Seni',
                              'Travel dan Outdoor'=>'Travel dan Outdoor',
                              'Bisnis'=>'Bisnis',
                              'Science dan Teknologi'=>'Science dan Teknologi',
                              'Spirituality'=>'Spirituality',
                              'Musik'=>'Musik',
                              'Keluarga dan Pendidikan'=>'Keluarga dan Pendidikan',
                              'Hobi'=>'Hobi',
                              'Lain-Lain'=>'Lain-Lain'
                              );
		$tipe_event = array(
							  'Attraction'=>'Attraction',
                              'Class'=>'Class',
                              'Conference'=>'Conference',
                              'Expo'=>'Expo',
                              'Festival'=>'Festival',
                              'Game'=>'Game',
                              'Party'=>'Party',
                              'Performance'=>'Performance',
                              'Seminar'=>'Seminar',
                              'Tour'=>'Tour',
                              'Lain-Lain'=>'Lain-Lain'
                              );

		$data_coming_tambah=array(
						'nama_coming'=>'',
						'jenis_event'=>'',
						'pendaftaran'=>'',
						'kategori_coming'=>'',
						'tipe_event'=>'',
						'deskripsi_coming'=>'',
						'tanggal_posting'=>'',
						'posted_by'=>'',
						'institusi'=>'',
						'telepon'=>'',
						'email'=>'',
						'tgl_mulai'=>'',
						'tgl_selesai'=>'',
						'jam_mulai'=>'',
						'jam_selesai'=>'',
						'path_gambar'=> NULL,
						'status'=>1
					);

		$jam_event=array();
		for ($i=0; $i<24; $i++)
		{
	 		for ($j=0; $j<=45; $j=$j+15)
	 		{
	 			if ($i<=9)
	 			{
	 				if ($j==0)
	 				{
	 					$jam_event["0".$i.":".$j."0"]="0".$i.":".$j."0";
	 				}
	 				else
	 				{
	 					$jam_event["0".$i.":".$j.""]="0".$i.":".$j."";
	 				}
	 			}
	 			else
	 			{
	 				if ($j==0)
	 				{
	 					$jam_event["".$i.":".$j."0"]="".$i.":".$j."0";
	 				}
	 				else
	 				{
	 					$jam_event["".$i.":".$j.""]="".$i.":".$j."";
	 				}
	 			}
	 		}
		}

		$data['kategori_coming']= $kategori_coming;
		$data['tipe_event']= $tipe_event;
		$data['jam_event']= $jam_event;

		$data['listEvent'] = $this->MemberModels->event_by_id_member($id_member);
		//$data['jumlahTestimoni'] = $this->HomeModels->jumlah_testimoni();

		$this->load->view('skin/front_end/header_front_end');
        $this->load->view('content_front_end/member_area_dashboard',$data);
        $this->load->view('skin/front_end/footer_front_end');
		} else {
			redirect(site_url());
		}
	}

	function tambah_event() {
        $this->load->model('coming_models/ComingModels');
		$this->load->library('form_validation');

		$tambah = $this->input->post('submit');
		$kategori_coming = array(
							  'Seni'=>'Seni',
                              'Travel dan Outdoor'=>'Travel dan Outdoor',
                              'Bisnis'=>'Bisnis',
                              'Science dan Teknologi'=>'Science dan Teknologi',
                              'Spirituality'=>'Spirituality',
                              'Musik'=>'Musik',
                              'Keluarga dan Pendidikan'=>'Keluarga dan Pendidikan',
                              'Hobi'=>'Hobi',
                              'Lain-Lain'=>'Lain-Lain'
                              );
		$tipe_event = array(
							  'Attraction'=>'Attraction',
                              'Class'=>'Class',
                              'Conference'=>'Conference',
                              'Expo'=>'Expo',
                              'Festival'=>'Festival',
                              'Game'=>'Game',
                              'Party'=>'Party',
                              'Performance'=>'Performance',
                              'Seminar'=>'Seminar',
                              'Tour'=>'Tour',
                              'Lain-Lain'=>'Lain-Lain'
                              );

		$data_coming_tambah=array(
						'nama_coming'=>'',
						'jenis_event'=>'',
						'pendaftaran'=>'',
						'kategori_coming'=>'',
						'tipe_event'=>'',
						'deskripsi_coming'=>'',
						'tanggal_posting'=>'',
						'posted_by'=>'',
						'institusi'=>'',
						'telepon'=>'',
						'email'=>'',
						'tgl_mulai'=>'',
						'tgl_selesai'=>'',
						'jam_mulai'=>'',
						'jam_selesai'=>'',
						'path_gambar'=> NULL,
						'status'=>1
					);

		$jam_event=array();
		for ($i=0; $i<24; $i++)
		{
	 		for ($j=0; $j<=45; $j=$j+15)
	 		{
	 			if ($i<=9)
	 			{
	 				if ($j==0)
	 				{
	 					$jam_event["0".$i.":".$j."0"]="0".$i.":".$j."0";
	 				}
	 				else
	 				{
	 					$jam_event["0".$i.":".$j.""]="0".$i.":".$j."";
	 				}
	 			}
	 			else
	 			{
	 				if ($j==0)
	 				{
	 					$jam_event["".$i.":".$j."0"]="".$i.":".$j."0";
	 				}
	 				else
	 				{
	 					$jam_event["".$i.":".$j.""]="".$i.":".$j."";
	 				}
	 			}
	 		}
		}

		$data['kategori_coming']= $kategori_coming;
		$data['tipe_event']= $tipe_event;
		$data['jam_event']= $jam_event;
		$data['dataComing'] = $data_coming_tambah;

		/*$seat=$this->input->post('seat');
		if($seat==1){
			$jumlah_seat=$this->input->post('jumlah_seat');
		} else{
			$jumlah_seat=0;
		}

		$jenis_event=$this->input->post('jenis_event');
		if($jenis_event==0){
			$harga=$this->input->post('harga');
		} else{
			$harga=0;
		}*/

			$this->form_validation->set_rules('judul_coming', 'Judul', 'required');
			$this->form_validation->set_rules('institusi', 'Institusi', 'required');
			$this->form_validation->set_rules('email', 'Email', 'required');
			$this->form_validation->set_rules('telepon', 'Telepon', 'required');
			$this->form_validation->set_rules('jenis_event', 'Jenis', 'required');
			//$this->form_validation->set_rules('seat', 'Seat', 'required');
			$this->form_validation->set_rules('tipe', 'Tipe', 'required');
			$this->form_validation->set_rules('kategori', 'Kategori', 'required');
			$this->form_validation->set_rules('tgl_event', 'Tanggal', 'required');
			$this->form_validation->set_rules('jam_mulai', 'Jam', 'required');
			$this->form_validation->set_rules('jam_selesai', 'Jam', 'required');
			$this->form_validation->set_rules('kota', 'Kota', 'required');
			$this->form_validation->set_rules('alamat', 'Alamat', 'required');
			$this->form_validation->set_rules('pendaftaran', 'Pendaftaran', 'required');
			$this->form_validation->set_rules('deskripsi_coming', 'Deskripsi', 'required');

			//Mengambil filename gambar untuk disimpan
			$nmfile = "file_".time();
			$config['upload_path'] = './asset/upload_img_coming/';
			$config['allowed_types'] = 'jpg|png|jpeg';
			$config['max_size'] = '4000'; //kb
			$config['file_name'] = $nmfile;

			//value id_koridor berisi beberapa data, sehingga dilakukan split dengan explode
			if (($this->form_validation->run() == TRUE) AND (!empty($_FILES['filefoto']['name'])))
			{
				$gbr = NULL;

					$data_coming=array(
						'id_member'=>$this->input->post('id_member'),
						'nama_coming'=>$this->input->post('judul_coming'),
						'jenis_event'=>$this->input->post('jenis_event'),
						'harga'=>0,
						'pendaftaran'=>$this->input->post('pendaftaran'),
						'kategori_coming'=>$this->input->post('kategori'),
						'tipe_event'=>$this->input->post('tipe'),
						'deskripsi_coming'=>$this->input->post('deskripsi_coming'),
						'tanggal_posting'=>date("Y-m-d h:i:sa"),
						'posted_by'=>$this->input->post('nama_member'),
						'institusi'=>$this->input->post('institusi'),
						'telepon'=>$this->input->post('telepon'),
						'email'=>$this->input->post('email'),
						'tgl_mulai'=>$this->input->post('tgl_mulai'),
						'tgl_selesai'=>$this->input->post('tgl_selesai'),
						'jam_mulai'=>$this->input->post('jam_mulai'),
						'jam_selesai'=>$this->input->post('jam_selesai'),
						'id_lokasi'=>$this->input->post('kota'),
						'alamat'=>$this->input->post('alamat'),
						'path_gambar'=> NULL,
						'seat'=> 0,
						'jumlah_seat'=> 0,
						'top_event'=> 2,
						'status'=>2
					);
					$data['dataComing'] = $data_coming;
				$this->load->library('upload', $config);
				if($this->upload->do_upload('filefoto'))
				{
					//echo "Masuk";
					$gbr = $this->upload->data();
					$this->crop($gbr['full_path'],$gbr['file_name']);

					$data_coming['path_gambar'] = $gbr['file_name'];

					$this->db->insert('coming', $data_coming);
					$nama_tiket = $this->input->post('nama_tiket');
					$harga = $this->input->post('harga');
					$jenisqty = $this->input->post('jenisqty');
					$qty = $this->input->post('qty');
					$id_event = $this->db->insert_id();
					$status = 1;
					$data_tiket = array();

					foreach ($nama_tiket as $key => $value)
					{
						if($jenisqty[$key]=='open'){
							$jumlah = NULL;
						} else {
							$jumlah = ((int)$qty[$key]);
						}
						$data_tiket[] = array(
						'nama_tiket' => $value,
						'harga' => $harga[$key],
						'seat' => $jumlah,
						'id_event' => $id_event,
						'status' => 1
						);
					}

					$this->db->insert_batch('tiket', $data_tiket);
					$this->session->set_flashdata('msg_berhasil', 'Data Event kamu berhasil disimpan, Admin kami akan melakukan verifikasi terhadap data event mu dalam kurun waktu 1 x 24 jam.');
					redirect('KelolaMember/dashboard_member');
				}
				else
				{
					$this->session->set_flashdata('msg_gagal', 'Data Event baru gagal ditambahkan, cek type file dan ukuran file yang anda upload');

					$this->load->view('skin/front_end/header_front_end');
					$this->load->view('content_front_end/member_area_dashboard',$data);
					$this->load->view('skin/front_end/footer_front_end');
				}
			}
			else
			{
				$error = validation_errors('
','
');
				$this->session->set_flashdata('msg_gagal', $error);
				redirect('KelolaMember/dashboard_member');
			}

	}

	public function edit_member_area($id_member)
	{
		$this->load->model('member_models/MemberModels');
		$this->load->library('form_validation');

		if($this->input->post('edit_password')==NULL){
			$password=$this->input->post('passwordlama');
		} else{
			$password=md5($this->input->post('edit_password'));
		}

		//Mengambil filename gambar untuk disimpan
		$nmfile = "file_".time();
		$config['upload_path'] = './asset/upload_img_member/';
		$config['allowed_types'] = 'jpg|png|jpeg';
		$config['max_size'] = '4000'; //kb
		$config['file_name'] = $nmfile;

		$data_member=array(
			'username'=>$this->input->post('edit_username'),
			'nama_member'=>$this->input->post('edit_nama_member'),
			'email'=>$this->input->post('edit_email'),
			'telepon'=>$this->input->post('edit_telepon'),
			'password'=>$password
			);
		$data['dataMember'] = $data_member;

		$gbr = NULL;
		$iserror = false;
		if ((!empty($_FILES['filefoto']['name']))) {

			$this->load->library('upload', $config);
			if($this->upload->do_upload('filefoto'))
			{
				//echo "Masuk";
				$gbr = $this->upload->data();
				$this->crop_member($gbr['full_path'],$gbr['file_name']);
				$data_member['path_foto'] = $gbr['file_name'];

			}
			else
			{
				$this->session->set_flashdata('msg_gagal', 'Data member gagal diperbaharui');
				$iserror = true;
			}

		}
			$this->db->update('member', $data_member, array('id_member'=>$id_member));

			$this->session->set_flashdata('msg_berhasil', 'Data member berhasil diperbaharui');
			redirect('KelolaMember/dashboard_member');

	}

	function validate_passlama(){
		if(isset($_POST['password2'])){

		echo md5($_POST['password2']);

		}

	}

	function validate_username(){
		if(isset($_POST['username'])){
		$username = $_POST['username'];
		$query = $this->db->where('username',$username)->get('member');
		$check = sizeof($query->row_array());
		echo $check;
		}

	}

	function validate_email(){
		if(isset($_POST['email'])){
		$email = $_POST['email'];
		$query = $this->db->where('email',$email)->get('member');
		$check = sizeof($query->row_array());
		echo $check;
		}

	}

	function get_pertanyaan(){
		if(isset($_POST['username'])){
		$username = $_POST['username'];
		$query = $this->db->select('pertanyaan_rahasia, jawaban_rahasia')->where('username',$username)->get('member');
		echo json_encode($query->row_array());
		}

	}

	function reset_password(){
		if(isset($_POST['password_baru'])&&isset($_POST['username'])){
			$password_baru = md5($_POST['password_baru']);
			$username = $_POST['username'];
			$data = array (
				'password' => $password_baru
			);
			if($this->db->update('member',$data,array('username' => $username))){
				echo TRUE;
			} else {
				echo FALSE;
			}
		}

	}

	function crop($img,$filename){

		$name = $img;
		if(preg_match("/.jpg/i", "$name")){
		$myImage = imagecreatefromjpeg($name);
		$myImage83 = imagecreatefromjpeg($name);
		}
		if(preg_match("/.jpeg/i", "$name")){
		$myImage = imagecreatefromjpeg($name);
		$myImage83 = imagecreatefromjpeg($name);
		}
		if(preg_match("/.jpeg/i", "$name")){
		$myImage = Imagecreatefromjpeg($name);
		$myImage83 = Imagecreatefromjpeg($name);
		}
		if(preg_match("/.png/i", "$name")){
		$myImage = imagecreatefrompng($name);
		$myImage83 = imagecreatefrompng($name);

		}
		if(preg_match("/.gif/i", "$name")){
		$myImage = imagecreatefromgif($name);
		$myImage83 = imagecreatefromgif($name);
		}

		list($width, $height) = getimagesize($name);
		//get percent to resize to 900x550
		if($width<=$height){
			$percent = 800/$width;
			$newwidth = $width * $percent;
			$newheight = $height * $percent;
			if($newheight<550){
				$percent2 = 550/$newheight;
				$newwidth = $newwidth * $percent2;
				$newheight = $newheight * $percent2;
			}

			$percent83 = 83/$width;
			$newwidth83 = $width * $percent83;
			$newheight83 = $height * $percent83;
			if($newheight83<83){
				$percent83b = 83/$newheight83;
				$newwidth83 = $newwidth83 * $percent83b;
				$newheight83 = $newheight83 * $percent83b;
			}

		} else {
			$percent = 550/$height;
			$newwidth = $width * $percent;
			$newheight = $height * $percent;
			if($newwidth<800){
				$percent2 = 800/$newwidth;
				$newwidth = $newwidth * $percent2;
				$newheight = $newheight * $percent2;
			}

			$percent83 = 83/$height;
			$newwidth83 = $width * $percent83;
			$newheight83 = $height * $percent83;
			if($newwidth83<83){
				$percent83b = 83/$newwidth83;
				$newwidth83 = $newwidth83 * $percent83b;
				$newheight83 = $newheight83 * $percent83b;
			}
		}

		// resize image
		$thumb = imagecreatetruecolor($newwidth, $newheight);
		$thumb83 = imagecreatetruecolor($newwidth83, $newheight83);
		imagecopyresized($thumb, $myImage, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
		imagecopyresized($thumb83, $myImage83, 0, 0, 0, 0, $newwidth83, $newheight83, $width, $height);

		if(preg_match("/.jpg/i", "$name")){
		imagejpeg($thumb,"./asset/upload_img_coming/resize_".$filename);
		imagejpeg($thumb83,"./asset/upload_img_coming/resize83_".$filename);
		}
		if(preg_match("/.jpeg/i", "$name")){
		imagejpeg($thumb,"./asset/upload_img_coming/resize_".$filename);
		imagejpeg($thumb83,"./asset/upload_img_coming/resize83_".$filename);
		}
		if(preg_match("/.png/i", "$name")){
		imagepng($thumb,"./asset/upload_img_coming/resize_".$filename);
		imagepng($thumb83,"./asset/upload_img_coming/resize83_".$filename);
		}

		// crop thumb
		$imgThumb = './asset/upload_img_coming/resize_'.$filename;
		$imgThumb83 = './asset/upload_img_coming/resize83_'.$filename;

		if(preg_match("/.jpg/i", "$name")){
		$myThumb = imagecreatefromjpeg($imgThumb);
		$myThumb83 = imagecreatefromjpeg($imgThumb83);
		}
		if(preg_match("/.jpeg/i", "$name")){
		$myThumb = imagecreatefromjpeg($imgThumb);
		$myThumb83 = imagecreatefromjpeg($imgThumb83);
		}
		if(preg_match("/.png/i", "$name")){
		$myThumb = imagecreatefrompng($imgThumb);
		$myThumb83 = imagecreatefrompng($imgThumb83);
		}

		list($width, $height) = getimagesize($imgThumb);
		list($width83, $height83) = getimagesize($imgThumb83);
		$myThumbCrop =  imagecreatetruecolor(800, 550);
		$myThumbCrop83 =  imagecreatetruecolor(83,83);
		$x = ($width-800)/2;
		$x83 = ($width83-83)/2;
		imagecopyresampled($myThumbCrop,$myThumb,0,0,$x,0 ,$width,$height,$width,$height);
		imagecopyresampled($myThumbCrop83,$myThumb83,0,0,$x83,0 ,$width83,$height83,$width83,$height83);

		if(preg_match("/.png/i", "$name")){
		imagesavealpha($myThumbCrop, true);
		imagesavealpha($myThumbCrop83, true);
		$color = imagecolorallocatealpha($myThumbCrop, 0, 0, 0, 127);
		$color83 = imagecolorallocatealpha($myThumbCrop83, 0, 0, 0, 127);
		imagefill($myThumbCrop, 0, 0, $color);
		imagefill($myThumbCrop83, 0, 0, $color83);
		}
		unlink('./asset/upload_img_coming/resize_'.$filename);
		unlink('./asset/upload_img_coming/resize83_'.$filename);

		// Save the two images created
		$fileName="thumb_".$filename;
		$fileName83="thumb83_".$filename;

		if(preg_match("/.jpg/i", "$name")){
		imagejpeg( $myThumbCrop,"./asset/upload_img_coming/".$fileName );
		imagejpeg( $myThumbCrop83,"./asset/upload_img_coming/".$fileName83 );
		}
		if(preg_match("/.jpeg/i", "$name")){
		imagejpeg( $myThumbCrop,"./asset/upload_img_coming/".$fileName );
		imagejpeg( $myThumbCrop83,"./asset/upload_img_coming/".$fileName83 );
		}
		if(preg_match("/.png/i", "$name")){
		imagepng( $myThumbCrop,"./asset/upload_img_coming/".$fileName );
		imagepng( $myThumbCrop83,"./asset/upload_img_coming/".$fileName83 );
		}
	}

	function crop_member($img,$filename){

		$name = $img;
		if(preg_match("/.jpg/i", "$name")){
		$myImage = imagecreatefromjpeg($name);
		$myImage85 = imagecreatefromjpeg($name);
		}
		if(preg_match("/.jpeg/i", "$name")){
		$myImage = imagecreatefromjpeg($name);
		$myImage85 = imagecreatefromjpeg($name);
		}
		if(preg_match("/.jpeg/i", "$name")){
		$myImage = Imagecreatefromjpeg($name);
		$myImage85 = Imagecreatefromjpeg($name);
		}
		if(preg_match("/.png/i", "$name")){
		$myImage = imagecreatefrompng($name);
		$myImage85 = imagecreatefrompng($name);

		}
		if(preg_match("/.gif/i", "$name")){
		$myImage = imagecreatefromgif($name);
		$myImage85 = imagecreatefromgif($name);
		}
		list($width, $height) = getimagesize($name);
		//get percent to resize to 900x550
		if($width<=$height){
			$percent = 800/$width;
			$newwidth = $width * $percent;
			$newheight = $height * $percent;
			if($newheight<550){
				$percent2 = 550/$newheight;
				$newwidth = $newwidth * $percent2;
				$newheight = $newheight * $percent2;
			}

			$percent85 = 300/$width;
			$newwidth85 = $width * $percent85;
			$newheight85 = $height * $percent85;
			if($newheight85<300){
				$percent85b = 300/$newheight85;
				$newwidth85 = $newwidth85 * $percent85b;
				$newheight85 = $newheight85 * $percent85b;
			}
		} else {
			$percent = 550/$height;
			$newwidth = $width * $percent;
			$newheight = $height * $percent;
			if($newwidth85<800){
				$percent2 = 800/$newwidth;
				$newwidth = $newwidth * $percent2;
				$newheight = $newheight * $percent2;
			}

			$percent85 = 300/$height;
			$newwidth85 = $width * $percent85;
			$newheight85 = $height * $percent85;
			if($newwidth85<300){
				$percent85b = 300/$newwidth85;
				$newwidth85 = $newwidth85 * $percent85b;
				$newheight85 = $newheight85 * $percent85b;
			}
		}

		// resize image
		$thumb = imagecreatetruecolor($newwidth, $newheight);
		$thumb85 = imagecreatetruecolor($newwidth85, $newheight85);
		imagecopyresized($thumb, $myImage, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
		imagecopyresized($thumb85, $myImage85, 0, 0, 0, 0, $newwidth85, $newheight85, $width, $height);
		if(preg_match("/.jpg/i", "$name")){
		imagejpeg($thumb,"./asset/upload_img_member/resize_".$filename);
		imagejpeg($thumb85,"./asset/upload_img_member/resize85_".$filename);
		}
		if(preg_match("/.jpeg/i", "$name")){
		imagejpeg($thumb,"./asset/upload_img_member/resize_".$filename);
		imagejpeg($thumb85,"./asset/upload_img_member/resize85_".$filename);
		}
		if(preg_match("/.png/i", "$name")){
		imagepng($thumb,"./asset/upload_img_member/resize_".$filename);
		imagepng($thumb85,"./asset/upload_img_member/resize85_".$filename);
		}

		// crop thumb
		$imgThumb = './asset/upload_img_member/resize_'.$filename;
		$imgThumb85 = './asset/upload_img_member/resize85_'.$filename;
		if(preg_match("/.jpg/i", "$name")){
		$myThumb = imagecreatefromjpeg($imgThumb);
		$myThumb85 = imagecreatefromjpeg($imgThumb85);
		}
		if(preg_match("/.jpeg/i", "$name")){
		$myThumb = imagecreatefromjpeg($imgThumb);
		$myThumb85 = imagecreatefromjpeg($imgThumb85);
		}
		if(preg_match("/.png/i", "$name")){
		$myThumb = imagecreatefrompng($imgThumb);
		$myThumb85 = imagecreatefrompng($imgThumb85);
		}

		list($width, $height) = getimagesize($imgThumb);
		list($width85, $height85) = getimagesize($imgThumb85);
		$myThumbCrop =  imagecreatetruecolor(800,550);
		$myThumbCrop85 =  imagecreatetruecolor(300, 300);
		imagecopyresampled($myThumbCrop,$myThumb,0,0,0,0 ,$width,$height,$width,$height);
		imagecopyresampled($myThumbCrop85,$myThumb85,0,0,0,0 ,$width85,$height85,$width85,$height85);

		if(preg_match("/.png/i", "$name")){
		imagesavealpha($myThumbCrop, true);
		imagesavealpha($myThumbCrop85, true);
		$color = imagecolorallocatealpha($myThumbCrop, 0, 0, 0, 127);
		$color85 = imagecolorallocatealpha($myThumbCrop83, 0, 0, 0, 127);
		imagefill($myThumbCrop, 0, 0, $color);
		imagefill($myThumbCrop85, 0, 0, $color85);
		}
		unlink('./asset/upload_img_member/resize_'.$filename);
		unlink('./asset/upload_img_member/resize85_'.$filename);

		// Save the two images created
		$fileName="thumb_".$filename;
		$fileName85="thumb85_".$filename;
		if(preg_match("/.jpg/i", "$name")){
		imagejpeg( $myThumbCrop,"./asset/upload_img_member/".$fileName );
		imagejpeg( $myThumbCrop85,"./asset/upload_img_member/".$fileName85 );
		}
		if(preg_match("/.jpeg/i", "$name")){
		imagejpeg( $myThumbCrop,"./asset/upload_img_member/".$fileName );
		imagejpeg( $myThumbCrop85,"./asset/upload_img_member/".$fileName85 );
		}
		if(preg_match("/.png/i", "$name")){
		imagepng( $myThumbCrop,"./asset/upload_img_member/".$fileName );
		imagepng( $myThumbCrop85,"./asset/upload_img_member/".$fileName85 );
		}

	}

}


text:
<?php
require_once __DIR__ . '/../bootstrap.php';

$logger->info('Starting websocket gateway.');
$WorkerGateway = new ShinyDeploy\Core\WsGateway($config, $logger);
$loop = React\EventLoop\Factory::create();
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind($config->get('zmq.dsn'));
$pull->on('message', array($WorkerGateway, 'onApiEvent'));
$uri = $config->get('wss.host') .':'.$config->get('wss.port');
$webSock = new React\Socket\Server($uri, $loop);
$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $WorkerGateway
            )
        )
    ),
    $webSock
);

$loop->run();

redpajama_set_name: RedPajamaGithub


text:
module.exports = function(grunt) {
    "use strict";

    var config = grunt.config('build') || {};

    grunt.registerTask('pax-build', 'Build project', function() {});
    // grunt.registerTask('pax-build', 'Build project', (config.flow) ? config.flow : function() {});
    grunt.registerTask('build', 'Build project', function() {
        grunt.log.muted = false;

        grunt.log.subhead('Building project...');

        if (config.flow) {
            for(var i in config.flow) {
                grunt.task.run(config.flow[i]);
            }
        }

        // grunt.task.run('pax-build');
        // grunt.log.error('task is not defined yet!');

        // grunt.log.muted = true;

    });
};


text:
require 'spec_helper'

describe "gws_staff_record_public_user_occupations", type: :feature, dbscope: :example do
  let(:site) { gws_site }
  let(:year) { create :gws_staff_record_year }
  let(:section) { create :gws_staff_record_group, year_id: year.id }
  let!(:item) { create :gws_staff_record_user_occupation, year_id: year.id }
  let(:index_path) { gws_staff_record_user_occupations_path(site, year) }

  context "with auth", js: true do
    before { login_gws_user }

    it_behaves_like 'crud flow'

    it "#download" do
      visit index_path
      click_link I18n.t('ss.links.download')

      visit index_path
      click_link I18n.t('ss.links.import')
      click_button I18n.t('ss.import')
    end
  end
end


text:
"""This is the Bokeh charts interface. It gives you a high level API to build
complex plot is a simple way.

This is the Bar class which lets you build your Bar charts just passing
the arguments to the Chart class and calling the proper functions.
It also add a new chained stacked method.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import absolute_import, print_function, division

try:
    import numpy as np

except ImportError:
    raise RuntimeError("bokeh.charts Bar chart requires NumPy.")

from ..utils import chunk, cycle_colors
from .._builder import Builder, create_and_build
from ...models import ColumnDataSource, FactorRange, GlyphRenderer, Range1d
from ...models.glyphs import Rect
from ...properties import Any, Bool, Either, List

#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------

def Bar(values, cat=None, stacked=False, xscale="categorical", yscale="linear",
        xgrid=False, ygrid=True, continuous_range=None, **kw):
    """ Create a Bar chart using :class:`BarBuilder <bokeh.charts.builder.bar_builder.BarBuilder>`
    render the geometry from values, cat and stacked.

    Args:
        values (iterable): iterable 2d representing the data series
            values matrix.
        cat (list or bool, optional): list of string representing the categories.
            (Defaults to None)
        stacked (bool, optional): to see the bars stacked or grouped.
            (Defaults to False, so grouping is assumed)
        continuous_range(Range1d, optional): Custom continuous_range to be
            used. (Defaults to None)

    In addition the the parameters specific to this chart,
    :ref:`userguide_charts_generic_arguments` are also accepted as keyword parameters.

    Returns:
        a new :class:`Chart <bokeh.charts.Chart>`

    Examples:

        .. bokeh-plot::
            :source-position: above

            from collections import OrderedDict
            from bokeh.charts import Bar, output_file, show

            # (dict, OrderedDict, lists, arrays and DataFrames are valid inputs)
            xyvalues = OrderedDict()
            xyvalues['python']=[-2, 5]
            xyvalues['pypy']=[12, 40]
            xyvalues['jython']=[22, 30]

            cat = ['1st', '2nd']

            bar = Bar(xyvalues, cat, title="Stacked bars",
                    xlabel="category", ylabel="language")

            output_file("stacked_bar.html")
            show(bar)

    """
    if continuous_range and not isinstance(continuous_range, Range1d):
        raise ValueError(
            "continuous_range must be an instance of bokeh.models.ranges.Range1d"
        )

    # The continuous_range is the y_range (until we implement HBar charts)
    y_range = continuous_range

    return create_and_build(
        BarBuilder, values, cat=cat, stacked=stacked,
        xscale=xscale, yscale=yscale,
        xgrid=xgrid, ygrid=ygrid, y_range=y_range, **kw
    )

class BarBuilder(Builder):
    """This is the Bar class and it is in charge of plotting
    Bar chart (grouped and stacked) in an easy and intuitive way.

    Essentially, it provides a way to ingest the data, make the proper
    calculations and push the references into a source object.
    We additionally make calculations for the ranges.
    And finally add the needed glyphs (rects) taking the references
    from the source.

    The x_range is categorical, and is made either from the cat argument
    or from the indexes of the passed values if no cat is supplied.  The
    y_range can be supplied as the parameter continuous_range,
    or will be calculated as a linear range (Range1d) based on the supplied
    values using the following rules:

     * with all positive data: start = 0, end = 1.1 * max
     * with all negative data: start = 1.1 * min, end = 0
     * with mixed sign data:   start = 1.1 * min, end = 1.1 * max

    """

    cat = Either(Bool, List(Any), help="""
    List of string representing the categories. (Defaults to None.)
    """)

    stacked = Bool(False, help="""
    Whether to stack the bars. (Defaults to False)

    If True, bars are draw as a stack, to show the relationship of
    parts to a whole. Otherwise, bars are grouped on the same chart.

    """)

    def _process_data(self):
        """Take the Bar data from the input **value.

        It calculates the chart properties accordingly. Then build a dict
        containing references to all the calculated points to be used by
        the rect glyph inside the ``_yield_renderers`` method.
        """
        if not self.cat:
            self.cat = [str(x) for x in self._values.index]

        width = [0.8] * len(self.cat)
        # width should decrease proportionally to the value length.
        # 1./len(value) doesn't work well as the width needs to decrease a
        # little bit faster
        width_cat = [min(0.2, (1. / len(self._values)) ** 1.1)] * len(self.cat)
        zero = np.zeros(len(self.cat))
        self._data = dict(
            cat=self.cat, width=width, width_cat=width_cat, zero=zero
        )
        # list to save all the groups available in the incomming input grouping
        step = np.linspace(0, 1.0, len(self._values.keys()) + 1, endpoint=False)
        self._groups.extend(self._values.keys())

        for i, (val, values) in enumerate(self._values.items()):
            self.set_and_get("", val, list(values))
            mid = np.array(values) / 2
            self.set_and_get("mid", val, mid)
            self.set_and_get("stacked", val, zero + mid)
            # Grouped
            grouped = [c + ":" + str(step[i + 1]) for c in self.cat]
            self.set_and_get("cat", val, grouped)
            # Stacked
            zero += values

    def _set_sources(self):
        """Push the Bar data into the ColumnDataSource and calculate
        the proper ranges.
        """
        self._source = ColumnDataSource(self._data)
        self.x_range = FactorRange(factors=self._source.data["cat"])

        if not self.y_range:
            if self.stacked:
                data = np.array(self._data['zero'])
            else:
                cats = [i for i in self._attr if not i.startswith(("mid", "stacked", "cat"))]
                data = np.array([self._data[cat] for cat in cats])

            all_positive = True if np.all(data > 0) else False
            all_negative = True if np.all(data < 0) else False
            # Set the start value
            if all_positive:
                start = 0
            else:
                start = 1.1 * data.min()  # Will always be negative

            # Set the end value
            if all_negative:
                end = 0
            else:
                end = 1.1 * data.max()

            self.y_range = Range1d(start=start, end=end)

    def _yield_renderers(self):
        """Use the rect glyphs to display the bars.

        Takes reference points from data loaded at the ColumnDataSource.
        """
        quartets = list(chunk(self._attr, 4))
        colors = cycle_colors(quartets, self.palette)

        # quartet elements are: [data, mid, stacked, cat]
        for i, quartet in enumerate(quartets):
            if self.stacked:
                glyph = Rect(
                    x="cat", y=quartet[2],
                    width="width", height=quartet[0],
                    fill_color=colors[i], fill_alpha=0.7,
                    line_color="white"
                )
            else:  # Grouped
                glyph = Rect(
                    x=quartet[3], y=quartet[1],
                    width="width_cat", height=quartet[0],
                    fill_color=colors[i], fill_alpha=0.7,
                    line_color="white"
                )
            renderer = GlyphRenderer(data_source=self._source, glyph=glyph)
            self._legends.append((self._groups[i], [renderer]))
            yield renderer


text:
require "rest-client"
require "net/http"
require "openssl"

module Bitflyer
  module Net
    def self.to_uri(path)
      return "https://api.bitflyer.jp#{path}"
    end

    def self.get(path, options = {}, private_api = false)
      begin
        path += "?#{URI.encode_www_form(options)}" unless options.empty?
        if private_api
          RestClient.get(self.to_uri(path), self.headers_for(path, options))
        else
          RestClient.get(self.to_uri(path))
        end
      rescue RestClient::BadRequest => e
        raise BadRequest.new(e.response)
      end
    end

    def self.post(path, options = {})
      begin
        RestClient.post(self.to_uri(path), options.to_json, self.headers_for(path, options, "POST"))
      rescue RestClient::BadRequest => e
        raise BadRequest.new(e.response)
      end
    end

    class BadRequest < RuntimeError; end

    private

    def self.headers_for(path, options = {}, method = "GET")
      timestamp = Time.now.to_i.to_s
      if method == "GET"
        text = timestamp + method + path
      else
        text = timestamp + method + path + options.to_json
      end

      signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha256"), Bitflyer.secret, text)
      {
        "Content-Type" => "application/json",
        "Accept" => "application/json",
        "ACCESS-KEY" => Bitflyer.key,
        "ACCESS-TIMESTAMP" => timestamp,
        "ACCESS-SIGN" => signature
      }
    end
  end
end


text:
import collections
import os
import re
import struct
import unittest
import uuid

import plankton.codec
import plankton.schema

class SpecTestBlock(object):
  """An individual section of a spec test."""

  def __init__(self, config):
    self.config = config

  def is_canonical(self):
    return self.config.get("canonical", "true").lower() == "true"

  @staticmethod
  def parse(header, config, lines):
    return _SPEC_TEST_BLOCKS[header]._parse_concrete(config, lines)

class ExpressionBlock(SpecTestBlock):

  def _eval_composite(self, vars, expr, dest=None):
    """Evaluates a possibly composite expression."""
    parts = expr.strip().split(" ")
    if len(parts) == 1:
      try:
        # Try parsing as an atom; may fail which is okay, there's more cases we
        # can try below.
        return self._eval_atom(vars, parts[0])
      except NotAnAtom:
        pass
    (instr, arg) = parts[0].split(":")
    if instr == "array":
      count = int(arg)
      result = []
      if not dest is None:
        vars[dest] = result
      for part in parts[1:]:
        result.append(self._eval_atom(vars, part))
      assert count == len(result)
      return result
    elif instr == "map":
      count = int(arg)
      result = collections.OrderedDict()
      if not dest is None:
        vars[dest] = result
      for i in range(0, count):
        key = self._eval_atom(vars, parts[1 + 2 * i])
        value = self._eval_atom(vars, parts[2 + 2 * i])
        result[key] = value
      return result
    elif instr == "seed":
      count = int(arg)
      header = self._eval_atom(vars, parts[1])
      fields = collections.OrderedDict()
      result = plankton.codec.Seed(header, fields)
      if not dest is None:
        vars[dest] = result
      for i in range(0, count):
        field = self._eval_atom(vars, parts[2 + 2 * i])
        value = self._eval_atom(vars, parts[3 + 2 * i])
        fields[field] = value
      return result
    elif instr == "struct":
      count = int(arg)
      fields = []
      result = plankton.codec.Struct(fields)
      if not dest is None:
        vars[dest] = result
      for i in range(0, count):
        tag = int(parts[1 + 2 * i])
        value = self._eval_atom(vars, parts[2 + 2 * i])
        fields.append((tag, value))
      return result
    raise Exception("Unexpected expression {}".format(expr))

  def _eval_atom(self, vars, word):
    """
    Parses a string as an atomic expression. If we can't recognize the string as
    a valid atom NotAnAtom is raised.
    """
    if word == "null":
      return None
    elif word == "true":
      return True
    elif word == "false":
      return False
    elif word.startswith("$"):
      return vars[word[1:]]
    (instr, arg) = word.split(":")
    if instr == "int":
      return int(arg)
    elif instr == "float":
      return float(arg)
    elif instr == "id":
      return uuid.UUID(arg.zfill(32))
    elif instr == "blob":
      return bytearray.fromhex(arg)
    elif instr == "str":
      return arg
    else:
      raise NotAnAtom()

class DataBlock(ExpressionBlock):

  def __init__(self, config, instrs):
    super(DataBlock, self).__init__(config)
    self._instrs = instrs

  def eval(self):
    """Returns the parsed data/object this test case represents."""
    vars = {}
    for line in self._instrs:
      yield_result = False
      save_result = None
      yield_match = re.match(r"yield (.*)", line)
      if yield_match:
        expr = yield_match.group(1)
        yield_result = True
      var_match = re.match(r"\$([a-z0-9]+) = (.*)", line)
      if var_match:
        save_result = var_match.group(1)
        expr = var_match.group(2)
      value = self._eval_composite(vars, expr, save_result)
      if yield_result:
        return value
      if not save_result is None:
        vars[save_result] = value

  @staticmethod
  def _parse_concrete(config, instrs):
    return DataBlock(config, instrs)

class StreamBlock(ExpressionBlock):

  def __init__(self, config, instrs):
    super(StreamBlock, self).__init__(config)
    self._instrs = instrs

  def generate(self):
    schema = plankton.schema.Schema()
    for line in self._instrs:
      template_match = re.match(r"-\s+([^(]+)\(\)\s+=>\s+(.*)", line)
      if template_match:
        name = self._eval_composite(None, template_match.group(1), None)
        value = self._eval_composite(None, template_match.group(2), None)
        template = plankton.schema.Template(name, None, value)
        schema.add_template(template)
      elif line == "! schema":
        yield ("schema", schema)
        schema = plankton.schema.Schema()

  @staticmethod
  def _parse_concrete(config, instrs):
    return StreamBlock(config, instrs)

class BtonBlock(SpecTestBlock):
  """A binary plankton block."""

  def __init__(self, config, data):
    super(BtonBlock, self).__init__(config)
    self.data = data

  @staticmethod
  def _parse_concrete(config, lines):
    bton = bytearray.fromhex("".join(lines))
    return BtonBlock(config, bton)

class TtonBlock(SpecTestBlock):
  """A text plankton block."""

  def __init__(self, config, source):
    super(TtonBlock, self).__init__(config)
    self.source = source

  @staticmethod
  def _parse_concrete(config, lines):
    tton = "".join(lines)
    return TtonBlock(config, tton)

_SPEC_TEST_BLOCKS = {
  "bton": BtonBlock,
  "data": DataBlock,
  "stream": StreamBlock,
  "tton": TtonBlock,
}

class NotAnAtom(Exception):
  pass

class ParsedSpecTest(object):
  """Holds the partially parsed information about a test case from spec/."""

  def __init__(self, blocks):
    self.blocks = blocks

  @property
  def datas(self):
    return self.blocks.get("data", [])

  @property
  def btons(self):
    return self.blocks.get("bton", [])

  @property
  def ttons(self):
    return self.blocks.get("tton", [])

  @property
  def canonical_tton(self):
    for tton in self.ttons:
      if tton.is_canonical:
        return tton

  @property
  def streams(self):
    return self.blocks.get("stream", [])

  @classmethod
  def parse(cls, source):
    """Parses an entire test case file into blocks."""
    lines = list(cls._strip_lines(source.splitlines()))
    offset = 0
    blocks = {}
    while offset < len(lines):
      # Scan until we find a block.
      while offset < len(lines):
        header_match = re.match(r"---+ (.*) ---+", lines[offset])
        offset += 1
        if header_match:
          header = header_match.group(1)
          break
      config = {}
      while offset < len(lines):
        config_match = re.match(r"^%\s*([\w_]+)\s*:(.*)$", lines[offset])
        if not config_match:
          break
        config[config_match.group(1).strip()] = config_match.group(2).strip()
        offset += 1
      block_lines = []
      while offset < len(lines) and (re.match(r"---+ (.*) ---+", lines[offset]) == None):
        block_lines.append(lines[offset])
        offset += 1
      if not header in blocks:
        blocks[header] = []
      blocks[header].append(SpecTestBlock.parse(header, config, block_lines))
    return ParsedSpecTest(blocks)

  @staticmethod
  def _strip_lines(lines):
    """Strips spaces from the given lines, skipping empty lines."""
    for line in lines:
      stripped = line.strip()
      if stripped:
        yield stripped

def _read_spec_test(filename):
  """Given a file name, returns the parsed test case contained in the file."""
  with open(filename, "rt") as file:
    source = file.read()
  return ParsedSpecTest.parse(source)

def build_test_suite(loader, tests, pattern, test_case_factory):
  """Called by the test framework to produce the test suite to run."""
  suite = unittest.TestSuite()
  data_root = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'spec')
  assert os.path.exists(data_root)
  test_files = []
  absroot = os.path.abspath(data_root)
  for (dirpath, dirnames, filenames) in os.walk(absroot):
    for filename in filenames:
      if filename.endswith(".txt"):
        test_file = os.path.join(dirpath, filename)
        test_files.append(test_file)
  test_files.sort()
  for test_file in test_files:
    test_name = test_file[len(absroot)+1:]
    spec_test = _read_spec_test(test_file)
    test_class = test_case_factory(test_file, test_name, spec_test)
    if test_class:
      suite.addTests(loader.loadTestsFromTestCase(test_class))
  return suite

class SpecTestCase(unittest.TestCase):
  """Adds a few utilities that are useful to spec tests."""

  def assertStructurallyEqual(self, a, b):
    """Assertion that fails unless a and b are structurally equal."""
    if not is_structurally_equal(a, b):
      message = "%s !~= %s" % (repr(a), repr(b))
      self.fail(message)

def is_structurally_equal(a, b, assumed_equivs=None):
  """
  Returns true iff a and b are structurally equal, that is, atomic values are
  equal, composite values have the same size and elements, and values reference
  each other (by object identity) in the same way. Floats are structurally equal
  if they are exactly equal -- so for instance NaN is structurally equal to NaN
  and -0 and 0 are not equal.

  Assumed_equivs is a set of pairs (id1, id2) where, if we encounter two objects
  where one has id1 and the other has id2 then we will just accept them as equal
  without explicitly checking, because then we'll either already have checked
  that they're equal elsewhere or we'll be in the middle of checking them right
  now and so doing it recursively will cause the comparison to diverge.
  """
  if assumed_equivs is None:
    assumed_equivs = set()

  if isinstance(a, (list, tuple)):
    # Checks that don't traverse a or b.
    if not isinstance(b, (list, tuple)):
      return False
    if not len(a) == len(b):
      return False

    if _are_assumed_equal(a, b, assumed_equivs):
      return True

    # Traverse the array.
    for i in range(0, len(a)):
      if not is_structurally_equal(a[i], b[i], assumed_equivs):
        return False

    return True

  elif isinstance(a, dict):
    # Checks that don't traverse a or b.
    if not isinstance(b, dict):
      return False
    if not len(a) == len(b):
      return False

    if _are_assumed_equal(a, b, assumed_equivs):
      return True

    # Traverse the array.
    for k in a.keys():
      if not k in b:
        return False
      if not is_structurally_equal(a[k], b[k], assumed_equivs):
        return False

    return True

  elif isinstance(a, plankton.codec.Seed):
    # Checks that don't traverse a or b.
    if not isinstance(b, plankton.codec.Seed):
      return False
    if len(a.fields) != len(b.fields):
      return False

    if _are_assumed_equal(a, b, assumed_equivs):
      return True

    if not is_structurally_equal(a.header, b.header, assumed_equivs):
      return False

    for f in a.fields.keys():
      if not f in b.fields:
        return False
      if not is_structurally_equal(a.fields[f], b.fields[f], assumed_equivs):
        return False

    return True

  elif isinstance(a, plankton.codec.Struct):
    # Checks that don't traverse a or b.
    if not isinstance(b, plankton.codec.Struct):
      return False
    if len(a.fields) != len(b.fields):
      return False

    if _are_assumed_equal(a, b, assumed_equivs):
      return True

    for i in range(0, len(a.fields)):
      (ta, va) = a.fields[i]
      (tb, vb) = b.fields[i]
      if ta != tb:
        return False
      if not is_structurally_equal(va, vb, assumed_equivs):
        return False

    return True

  elif isinstance(a, float):
    if not isinstance(b, float):
      return False

    # Float comparison is tricky and magical and what we're really after is
    # whether the two values are *exactly* the same. So we compare the binary
    # representation instead of the values.
    a_bytes = struct.pack("<d", a)
    b_bytes = struct.pack("<d", b)
    return a_bytes == b_bytes

  else:
    return a == b

def _are_assumed_equal(a, b, assumed_equivs):
  """
  Returns true iff a and b are already assumed to be equal. Otherwise adds an
  equivalence of a and b to the set and returns false.
  """

  # Are we just assuming that the two are equal?
  equiv = (id(a), id(b))
  if equiv in assumed_equivs:
    return True

  # If we see these two again assume they're equal. If they're not then the
  # traversal will detect it.
  assumed_equivs.add(equiv)
  return False


text:
<?php

/*# declare(strict_types=1); */

namespace Phossa\Cache\Misc;

/**
 * TaggableItemInterface
 *
 * @interface
 * @package Phossa\Cache
 * @author  Hong Zhang <phossa@126.com>
 * @version 1.0.8
 * @since   1.0.8 added
 */
interface TaggableItemInterface
{
    /**
     * Set tags to this item
     *
     * @param  string[] $tags tags array
     * @return void
     * @access public
     * @api
     */
    public function setTags(array $tags);

    /**
     * Get item tags
     *
     * @param  string[]
     * @access public
     * @api
     */
    public function getTags()/*# : array */;
}


text:
using Manos.IO;

namespace Manos.Http
{
    public interface IHttpBodyHandler
    {
        void HandleData(HttpEntity entity, ByteBuffer data, int pos, int len);

        void Finish(HttpEntity entity);
    }
}


text:
require "namba/version"
require 'namba/client'
require 'namba/config'
require 'namba/railtie' if defined? Rails

module Namba
  extend Config

  class << self

    # Alias for Namba::Client.new()
    def new
      Namba::Client.new
    end

    # Alias for Namba::Config.configure
    def configure &block
      Namba::Config.configure &block
    end

  end
end


text:
var parent = require('../../actual/string/includes');

module.exports = parent;


text:
@font-face {
    font-family: 'icomoon';
    src:    url('fonts/icomoon.eot?6031hv');
    src:    url('fonts/icomoon.eot?6031hv#iefix') format('embedded-opentype'),
        url('fonts/icomoon.ttf?6031hv') format('truetype'),
        url('fonts/icomoon.woff?6031hv') format('woff'),
        url('fonts/icomoon.svg?6031hv#icomoon') format('svg');
    font-weight: normal;
    font-style: normal;
}

[class^="icon-"], [class*=" icon-"] {
    /* use !important to prevent issues with browser extensions that change fonts */
    font-family: 'icomoon' !important;
    speak: none;
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;

    /* Better Font Rendering =========== */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.icon-arrow-bottom:before {
    content: "\e900";
}
.icon-arrow-right:before {
    content: "\e901";
}
.icon-bag:before {
    content: "\e902";
}
.icon-calendar-clock:before {
    content: "\e903";
}
.icon-cell-money:before {
    content: "\e904";
}
.icon-download:before {
    content: "\e905";
}
.icon-increased-revenue:before {
    content: "\e906";
}
.icon-local:before {
    content: "\e907";
}
.icon-payment:before {
    content: "\e908";
}
.icon-sales:before {
    content: "\e909";
}
.icon-time:before {
    content: "\e90a";
}


text:
1. Download this project: git clone 'URL of this project'
2. Open cmd, and go to the path of this project on your PC: >cd path
3. Install npm inside this project: >npm install
4. Create new folder inside the project with name 'fonts' and put these three files inside it:
  fontawesome-webfont.ttf
  fontawesome-webfont.woff
  fontawesome-webfont.woff2
5. Run the project: > npm start
6. You can check it :)


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.Analytics.Synapse.Artifacts.Models
{
    /// <summary> Format write settings. </summary>
    public partial class FormatWriteSettings
    {
        /// <summary> Initializes a new instance of FormatWriteSettings. </summary>
        public FormatWriteSettings()
        {
            AdditionalProperties = new ChangeTrackingDictionary<string, object>();
            Type = "FormatWriteSettings";
        }

        /// <summary> Initializes a new instance of FormatWriteSettings. </summary>
        /// <param name="type"> The write setting type. </param>
        /// <param name="additionalProperties"> Additional Properties. </param>
        internal FormatWriteSettings(string type, IDictionary<string, object> additionalProperties)
        {
            Type = type ?? "FormatWriteSettings";
            AdditionalProperties = additionalProperties;
        }

        /// <summary> The write setting type. </summary>
        internal string Type { get; set; }
        /// <summary> Additional Properties. </summary>
        public IDictionary<string, object> AdditionalProperties { get; }
    }
}


text:
var gulp = require('gulp');
var webpack = require('gulp-webpack');
var config = require('../config');

gulp.task('webpack', function () {
  gulp.src(config.webpack.entry)
      .pipe(webpack(config.webpack))
      .pipe(gulp.dest(config.js.dest));
});


text:
@implementation UITextFieldPassword

#define MAX_LENGTH 6
- (void)awakeFromNib
{
    [super awakeFromNib];

    if (self) {
        self.delegate = self;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if(range.location >= MAX_LENGTH)
        return NO;
    else
        return YES;
}

@end


text:
layout: post
title: 'Groovy Quick Tip: String to Enum Coercion'
categories:
- groovy
tags: []
status: publish
type: post
published: true
meta:
  _wp_old_slug: ''
  _edit_last: '2'
  _edit_lock: '1386863551'
  _syntaxhighlighter_encoded: '1'
---
With all the fuss about the new closure to SAM type coercion in Groovy 2.2 [0] I was remembered of another neat coercion feature some of my work colleagues seemed not to know about.

Strings and Enumerations in Groovy

Since Groovy 1.7.6 the language supports a feature called "String to enum coercion" [1]. Well, that might say it all, but let's have a look what this means with a small code example:

{% highlight groovy %}

enum Day {
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}

 {% endhighlight %}

Let's assume we have an enum type called <tt>Day</tt>, resembling an enumeration of all the week days. If we wanted to get the enumeration value for a given string, we would have to do something like that in Java code:

{% highlight java %}

Day sunday = Day.valueOf("Sunday");

 {% endhighlight %}

Groovy comes with a nicer way of coercing a string to an arbitrary enumeration using the <tt>as</tt> operator:

{% highlight groovy %}
Day sunday = "Sunday" as Day
 {% endhighlight %}

The <tt>as</tt> operator can actually be left aside in this case which leaves us with:

{% highlight groovy %}
Day sunday = "Sunday"
 {% endhighlight %}

Note that this feature not only works for plain <tt>java.lang.String</tt> instances but also for <tt>GString</tt> instances:

{% highlight groovy %}
Day sunday = "${ ['Sun', 'day'].join()}"
 {% endhighlight %}

The coercion also works in the opposite direction, if we wanted a string from our enumeration value we can simply do:

{% highlight groovy %}
String day = Day.Sunday
 {% endhighlight %}

Conclusion

The String to enum coercion is especially useful if your are dealing with strings coming for example from HTTP request instances and you need a fast way to retrieve an enumeration value.

[0] Groovy 2.2 Release Notes

[1] GROOVY-4501: String to enum coercion


text:
package org.kuali.rice.krms.api.engine.expression;

import org.kuali.rice.krms.api.KrmsConstants;
import org.kuali.rice.krms.framework.engine.expression.EngineComparatorExtension;
import org.kuali.rice.krms.framework.engine.expression.StringCoercionExtension;

import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import java.util.List;

/**
 * Interface for registering {@link EngineComparatorExtension} for use as a
 * {@link org.kuali.rice.krms.framework.engine.expression.ComparisonOperator} when comparing
 * {@link org.kuali.rice.krms.framework.engine.Proposition} {@link Term}s
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
@WebService(name = "comparisonOperatorService", targetNamespace = KrmsConstants.Namespaces.KRMS_NAMESPACE_2_0)
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public interface ComparisonOperatorService extends StringCoercionExtension {

    /**
     * The {@link List} of {@link EngineComparatorExtension}s.
     * @return List<EngineComparatorExtension> of configured {@link EngineComparatorExtension}s.
     */
    public List<EngineComparatorExtension> getOperators();

    /**
     * List<EngineComparatorExtension> to use.
     * @param operators
     */
    public void setOperators(List<EngineComparatorExtension> operators);

    @Override
    @WebMethod(operationName = "canCoerce")
    @WebResult(name = "coerced")
    public boolean canCoerce(String type, String value);

    @Override
    @WebMethod(operationName = "coerce")
    @WebResult(name = "coerced")
    public Object coerce(String type, String value);

    /**
     * Returns the int result of a compare between the lhs and rhs objects.
     * @param lhs left hand side object
     * @param rhs right hand side object
     * @return int result of compare between lhs and rhs objects
     */
    public int compare(Object lhs, Object rhs);

    /**
     * Does the service have an Extension that can compare the given objects?
     *
     * @param leftHandSide left hand side Object
     * @param rightHandSide right hand side Object
     * @return boolean true a configured {@link EngineComparatorExtension} can compare the lhs and rhs Objects.
     */
    public boolean canCompare(Object leftHandSide, Object rightHandSide);

    /**
     * {@link EngineComparatorExtension} that canCompare the given Objects
     * @param leftHandSide left hand side Object
     * @param rightHandSide right hand side Object
     * @return the EngineComparatorExtension that can compare the given Objects.
     */
    public EngineComparatorExtension findComparatorExtension(Object leftHandSide, Object rightHandSide);

    /**
     *
     * @return List<StringCoercionExtension>
     */
    // this would move to a StringCoercionExtensionService if we go that way
    public List<StringCoercionExtension> getStringCoercionExtensions();

    /**
     * The {@link List} of {@link StringCoercionExtension}s.
     * @param stringCoercionExtensions
     */
    // this would move to a StringCoercionExtensionService if we go that way
    public void setStringCoercionExtensions(List<StringCoercionExtension> stringCoercionExtensions);

    /**
     *
     * @param type to coerce
     * @param value to coerce
     * @return {@link StringCoercionExtension} that can coerce the given type and value
     */
    // this would move to a StringCoercionExtensionService if we go that way
    StringCoercionExtension findStringCoercionExtension(String type, String value);

}


text:
package de.lessvoid.xml.lwxs.processor;

import de.lessvoid.xml.lwxs.Schema;
import de.lessvoid.xml.lwxs.elements.Type;
import de.lessvoid.xml.xpp3.Attributes;
import de.lessvoid.xml.xpp3.SubstitutionGroup;
import de.lessvoid.xml.xpp3.XmlParser;
import de.lessvoid.xml.xpp3.XmlProcessor;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class TypeProcessor implements XmlProcessor {
  @Nonnull
  private final Schema niftyXmlSchema;

  public TypeProcessor(@Nonnull final Schema niftyXmlSchemaParam) {
    niftyXmlSchema = niftyXmlSchemaParam;
  }

  @Override
  public void process(@Nonnull final XmlParser xmlParser, @Nonnull final Attributes attributes) throws Exception {
    String name = getNameAttribute(attributes);

    Type type = new Type(name, getExtendsAttribute(attributes));
    niftyXmlSchema.addType(name, type);

    SubstitutionGroup substGroup = new SubstitutionGroup();
    substGroup.add("element", new TypeProcessorElement(type));
    substGroup.add("group", new TypeProcessorSubstitutionGroup(type));

    xmlParser.nextTag();
    xmlParser.zeroOrMore(substGroup);
  }

  @Nonnull
  private String getNameAttribute(@Nonnull final Attributes attributes) throws Exception {
    String name = attributes.get("name");
    if (name == null) {
      throw new Exception("[name] attribute is a required attribute");
    }
    return name;
  }

  @Nullable
  private String getExtendsAttribute(@Nonnull final Attributes attributes) {
    return attributes.get("extends");
  }
}


text:
@charset UTF-8;
.flexigrid{font-family:Arial, Helvetica, sans-serif;font-size:11px;position:relative;border:0 solid #eee;overflow:hidden;color:#000}
.flexigrid.hideBody{height:26px!important;border-bottom:1px solid #ccc}
.ie6fullwidthbug{border-right:0 solid #ccc;padding-right:2px}
.flexigrid div.nDiv{background:#eee url(flexi-images/line.gif) repeat-y -1px top;border:1px solid #ccc;border-top:0;overflow:auto;left:0;position:absolute;z-index:999;float:left}
.flexigrid div.nDiv table{margin:2px}
.flexigrid div.hDivBox{float:left;padding-right:40px}
.flexigrid div.bDiv table{margin-bottom:10px;border-bottom:1px solid #ccc}
.flexigrid div.bDiv table.autoht{border-bottom:0;margin-bottom:0}
.flexigrid div.nDiv td{border:1px solid #eee;cursor:default;padding:2px 3px}
.flexigrid div.nDiv tr:hover td,.flexigrid div.nDiv tr.ndcolover td{background:#d5effc url(flexi-images/hl.png) repeat-x top;border:1px solid #a8d8eb}
.flexigrid div.nDiv td.ndcol1{border-right:1px solid #ccc}
.flexigrid div.nDiv td.ndcol2{border-left:1px solid #fff;padding-right:10px}
.flexigrid div.nDiv tr:hover td.ndcol1,.flexigrid div.nDiv tr.ndcolover td.ndcol1{border-right:1px solid #d2e3ec}
.flexigrid div.nDiv tr:hover td.ndcol2,.flexigrid div.nDiv tr.ndcolover td.ndcol2{border-left:1px solid #eef8ff}
.flexigrid div.nBtn{position:absolute;height:24px;width:14px;z-index:900;background:#fafafa url(flexi-images/fhbg.gif) repeat-x bottom;border:0 solid #ccc;border-left:1px solid #ccc;top:0;left:0;margin-top:1px;cursor:pointer;display:none}
.flexigrid div.nBtn div{height:24px;width:12px;border-left:1px solid #fff;float:left;background:url(flexi-images/ddn.png) no-repeat center}
.flexigrid div.nBtn.srtd{background:url(flexi-images/wbg.gif) repeat-x 0 -1px}
.flexigrid div.mDiv{background:url(flexi-images/wbg.gif) repeat-x top;border:1px solid #ccc;border-bottom:0;border-top:0;font-weight:700;display:block;overflow:hidden;white-space:nowrap;position:relative}
.flexigrid div.mDiv div{white-space:nowrap;padding:6px}
.flexigrid div.mDiv div.ptogtitle{position:absolute;top:4px;right:3px;height:16px;width:16px;overflow:hidden;border:1px solid #ccc;cursor:pointer;padding:0}
.flexigrid div.mDiv div.ptogtitle:hover{background-position:left -2px;border-color:#bbb}
.flexigrid div.mDiv div.ptogtitle span{display:block;border-left:1px solid #eee;border-top:1px solid #fff;border-bottom:1px solid #ddd;width:14px;height:14px;background:url(flexi-images/uup.png) no-repeat center}
.flexigrid div.mDiv div.ptogtitle.vsble span{background:url(flexi-images/ddn.png) no-repeat center}
.flexigrid div.tDiv /*toolbar*/{background:#fafafa url(flexi-images/bg.gif) repeat-x top;position:relative;border:1px solid #ccc;border-bottom:0;overflow:hidden}
.flexigrid div.tDiv2{float:left;clear:both;padding:1px}
.flexigrid div.sDiv /*toolbar*/{background:#fafafa url(flexi-images/bg.gif) repeat-x top;position:relative;border:1px solid #ccc;border-top:0;overflow:hidden;display:block}
.flexigrid div.sDiv2{float:left;clear:both;width:1024px;padding:5px}
.flexigrid div.sDiv2 input,.flexigrid div.sDiv2 select{vertical-align:middle}
.flexigrid div.btnseparator{float:left;height:22px;border-left:1px solid #ccc;border-right:1px solid #fff;margin:1px}
.flexigrid div.fbutton{float:left;display:block;cursor:pointer;padding:1px}
.flexigrid div.fbutton div{float:left;padding:1px 3px}
.flexigrid div.fbutton span{float:left;display:block;padding:3px}
.flexigrid div.fbutton:hover,.flexigrid div.fbutton.fbOver{border:1px solid #ccc;padding:0}
.flexigrid div.fbutton:hover div,.flexigrid div.fbutton.fbOver div{border-left:1px solid #fff;border-top:1px solid #fff;border-right:1px solid #eee;border-bottom:1px solid #eee;padding:0 2px}
.flexigrid div.hDiv{background:#fafafa url(flexi-images/fhbg.gif) repeat-x bottom;position:relative;border:1px solid #ccc;border-bottom:0;overflow:hidden}
.flexigrid div.hDiv table{border-right:1px solid #fff}
.flexigrid div.cDrag{float:left;position:absolute;z-index:2;overflow:visible}
.flexigrid div.cDrag div{float:left;background:none;display:block;position:absolute;height:24px;width:5px;cursor:col-resize}
.flexigrid div.cDrag div:hover,.flexigrid div.cDrag div.dragging{background:url(flexi-images/line.gif) repeat-y 2px center}
.flexigrid div.iDiv{border:1px solid #316ac5;position:absolute;overflow:visible;background:none}
.flexigrid div.iDiv input,.flexigrid div.iDiv select,.flexigrid div.iDiv textarea{font-family:Arial, Helvetica, sans-serif;font-size:11px}
.flexigrid div.iDiv input.tb{border:0;width:100%;height:100%;background:none;padding:0}
.flexigrid div.bDiv{border:1px solid #ccc;border-top:0;background:#fff;overflow:auto;position:relative}
.flexigrid div.hGrip{position:absolute;top:0;right:0;height:5px;width:5px;background:url(flexi-images/line.gif) repeat-x center;margin-right:1px;cursor:col-resize}
.flexigrid div.hGrip:hover,.flexigrid div.hGrip.hgOver{border-right:1px solid #999;margin-right:0}
.flexigrid div.vGrip{height:5px;overflow:hidden;position:relative;background:#fafafa url(flexi-images/wbg.gif) repeat-x 0 -1px;border:1px solid #ccc;border-top:0;text-align:center;cursor:row-resize}
.flexigrid div.vGrip span{display:block;width:20px;height:1px;overflow:hidden;border-top:1px solid #aaa;border-bottom:1px solid #aaa;background:none;margin:1px auto}
.flexigrid div.hDiv th,.flexigrid div.bDiv td
/* common cell properties*/{text-align:left;border-right:1px solid #ddd;border-left:1px solid #fff;overflow:hidden;vertical-align:top!important;padding-left:0;padding-right:0}
.flexigrid div.hDiv th div,.flexigrid div.bDiv td div,div.colCopy div
/* common inner cell properties*/{border-left:0 solid #fff;padding:5px}
.flexigrid div.hDiv th,div.colCopy{font-weight:400;height:24px;cursor:default;white-space:nowrap;overflow:hidden}
div.colCopy{font-family:Arial, Helvetica, sans-serif;font-size:11px;background:#fafafa url(flexi-images/fhbg.gif) repeat-x bottom;border:1px solid #ccc;border-bottom:0;overflow:hidden}
.flexigrid div.hDiv th.sorted{background:url(flexi-images/wbg.gif) repeat-x 0 -1px;border-bottom:0 solid #ccc}
.flexigrid div.hDiv th.thOver div,.flexigrid div.hDiv th.sorted.thOver div{border-bottom:1px solid orange;padding-bottom:4px}
.flexigrid div.hDiv th.sorted div{border-bottom:0 solid #ccc;padding-bottom:5px}
.flexigrid div.hDiv th.thMove{background:#fff;color:#fff}
.flexigrid div.hDiv th.sorted.thMove div{border-bottom:1px solid #fff;padding-bottom:4px}
.flexigrid div.hDiv th.thMove div{background:#fff!important}
.flexigrid div.hDiv th div.sdesc{background:url(flexi-images/dn.png) no-repeat center top}
.flexigrid div.hDiv th div.sasc{background:url(flexi-images/up.png) no-repeat center top}
.flexigrid div.bDiv td{border-bottom:1px solid #fff;vertical-align:top;white-space:nowrap}
.flexigrid span.cdropleft{display:block;background:url(flexi-images/prev.gif) no-repeat -4px center;width:24px;height:24px;position:relative;top:-24px;margin-bottom:-24px;z-index:3}
.flexigrid div.hDiv span.cdropright{display:block;background:url(flexi-images/next.gif) no-repeat 12px center;width:24px;height:24px;float:right;position:relative;top:-24px;margin-bottom:-24px}
.flexigrid div.bDiv td div{border-top:0 solid #fff;padding-bottom:4px}
.flexigrid tr td.sorted{background:#f3f3f3;border-right:1px solid #ddd;border-bottom:1px solid #f3f3f3}
.flexigrid tr.erow td{background:#f7f7f7;border-bottom:1px solid #f7f7f7}
.flexigrid tr.erow td.sorted{background:#e3e3e3;border-bottom:1px solid #e3e3e3}
.flexigrid div.bDiv tr:hover td,.flexigrid div.bDiv tr:hover td.sorted,.flexigrid div.bDiv tr.trOver td.sorted,.flexigrid div.bDiv tr.trOver td{background:#d9ebf5;border-left:1px solid #eef8ff;border-bottom:1px dotted #a8d8eb}
.flexigrid div.bDiv tr.trSelected:hover td,.flexigrid div.bDiv tr.trSelected:hover td.sorted,.flexigrid div.bDiv tr.trOver.trSelected td.sorted,.flexigrid div.bDiv tr.trOver.trSelected td,.flexigrid tr.trSelected td.sorted,.flexigrid tr.trSelected td{background:#d5effc url(flexi-images/hl.png) repeat-x top;border-right:1px solid #d2e3ec;border-left:1px solid #eef8ff;border-bottom:1px solid #a8d8eb}
.flexigrid.novstripe .bDiv table{border-bottom:1px solid #ccc;border-right:1px solid #ccc}
.flexigrid.novstripe div.bDiv td{border-right-color:#fff}
.flexigrid.novstripe div.bDiv tr.erow td.sorted{border-right-color:#e3e3e3}
.flexigrid.novstripe div.bDiv tr td.sorted{border-right-color:#f3f3f3}
.flexigrid.novstripe div.bDiv tr.erow td{border-right-color:#f7f7f7;border-left-color:#f7f7f7}
.flexigrid.novstripe div.bDiv tr.trSelected:hover td,.flexigrid.novstripe div.bDiv tr.trSelected:hover td.sorted,.flexigrid.novstripe div.bDiv tr.trOver.trSelected td.sorted,.flexigrid.novstripe div.bDiv tr.trOver.trSelected td,.flexigrid.novstripe tr.trSelected td.sorted,.flexigrid.novstripe tr.trSelected td{border-right:1px solid #06F;border-left:1px solid #06F}
.flexigrid.novstripe div.bDiv tr.trOver td,.flexigrid.novstripe div.bDiv tr:hover td{border-left-color:#d9ebf5;border-right-color:#d9ebf5}
.flexigrid div.pDiv{background:url(flexi-images/wbg.gif) repeat-x 0 -1px;border:1px solid #ccc;border-top:0;overflow:hidden;white-space:nowrap;position:relative}
.flexigrid div.pDiv div.pDiv2{float:left;width:1024px;margin:3px 3px 3px -2px}
div.pGroup{float:left;background:none;height:24px;margin:0 5px}
.flexigrid div.pDiv .pPageStat,.flexigrid div.pDiv .pcontrol{position:relative;top:5px;overflow:visible}
.flexigrid div.pDiv input{vertical-align:text-top;position:relative;top:-5px}
.flexigrid div.pDiv div.pButton{float:left;width:22px;height:22px;border:0;cursor:pointer;overflow:hidden}
.flexigrid div.pDiv div.pButton:hover,.flexigrid div.pDiv div.pButton.pBtnOver{width:20px;height:20px;border:1px solid #ccc;cursor:pointer}
.flexigrid div.pDiv div.pButton span{width:20px;height:20px;display:block;float:left}
.flexigrid div.pDiv div.pButton:hover span,.flexigrid div.pDiv div.pButton.pBtnOver span{width:19px;height:19px;border-top:1px solid #fff;border-left:1px solid #fff}
.flexigrid .pSearch{background:url(flexi-images/magnifier.png) no-repeat center}
.flexigrid .pFirst{background:url(flexi-images/first.gif) no-repeat center}
.flexigrid .pPrev{background:url(flexi-images/prev.gif) no-repeat center}
.flexigrid .pNext{background:url(flexi-images/next.gif) no-repeat center}
.flexigrid .pLast{background:url(flexi-images/last.gif) no-repeat center}
.flexigrid .pReload{background:url(flexi-images/load.png) no-repeat center}
.flexigrid .pReload.loading{background:url(flexi-images/load.gif) no-repeat center}
.flexigrid.ie div.hDiv th div,.flexigrid.ie div.bDiv td div,div.colCopy.ie div
/* common inner cell properties*/{overflow:hidden}
.flexigrid div.fbutton .down {
	background: url(flexi-images/download.png) no-repeat center left;
}

.flexigrid div.fbutton .add {
    background: url(flexi-images/add.png) no-repeat center left;
}

.flexigrid div.fbutton .delete {
    background: url(flexi-images/close.png) no-repeat center left;
}

.flexigrid div.fbutton .edit {
    background: url(flexi-images/edit.png) no-repeat center left;
}

.flexigrid div.fbutton .close {
    background: url(flexi-images/close-modal.png) no-repeat center left;
}

.flexigrid div.fbutton .save {
    background: url(flexi-images/save.png) no-repeat center left;
}

.flexigrid div.fbutton .detail {
    background: url(flexi-images/detail.png) no-repeat center left;
}

.flexigrid div.fbutton .view {
    background: url(flexi-images/magnifier.png) no-repeat center left;
}

.flexigrid div.fbutton .print {
    background: url(flexi-images/print.png) no-repeat center left;
}