mardi 2 janvier 2018

c# how to get the values next to checked datagridview checkboxes?

I have a DataGridView with CheckBox column, my question is how do I get the data next to a checked checkbox and print them all at once using MessageBox? I have tried these:

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {            
        foreach (DataGridViewRow row in this.dataGridView1.Rows)
        {
            if (Convert.ToBoolean(this.dataGridView1.Rows[e.RowIndex].Cells["chkBoxColumn"].Value = true) == true)
            {
                MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
            }
        }   
    }

It prints the last checked item over and over.

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        for (int i = 0; i < dataGridView1.Rows.Count; i++)

        {
            if (bool.Parse(dataGridView1.Rows[i].Cells["chkBoxColumn"].Value.ToString()) == true)
            {
                MessageBox.Show(dataGridView1.Rows[i].Cells[1].Value.ToString());
            }
        }
    } 

and i'm getting a null reference exception using this.




Selecting multiple values from checkboxGroupInput and plotting

Hi all and happy new year,

with the below code, I am trying to have it so that the user can filter data to look at whatever combination of days of the week they desire, so, for example, they will be able to select the data from 'Mondays' and 'Thursdays'. Currently the ggplot plots just the data from the first value checked, so, for example, if 'Mondays' and 'Thursdays' are both checked only the data from 'Mondays' will be shown. N.B there's also a checkbox in the code which is working fine.

    ui <- fluidPage(
  titlePanel("Transfers Analysis App"),


  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("Day", "Days of Week", c("All", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), selected="All"),
      checkboxInput("Outage", "Highlight Days when an Outage Occured", FALSE)),

    mainPanel(
             plotOutput("plot1", height = "600px", width = "100%",
             hover = hoverOpts(id = "plot_hover")),
       verbatimTextOutput("hover_info")

)))


server <- function(input, output) {

  output$plot1 <- renderPlot({
    Day <- input$Day
    Month <- input$Month
    Outage <- input$Outage


    if(Day == "Monday")
      data<-data[data$day == "Monday"]
    if(Day == "Tuesday")
      data<-data[data$day == "Tuesday"]
    if(Day == "Wednesday")
      data<-data[data$day == "Wednesday"]
    if(Day == "Thursday")
      data<-data[data$day == "Thursday"]
    if(Day == "Friday")
      data<-data[data$day == "Friday"]
    if(Day == "Saturday")
      data<-data[data$day == "Saturday"]

    #ggplot(data, aes(Date, NUMBER_OF_TRANSFERS)) + geom_point()
    #plot(data$Date,data$NUMBER_OF_TRANSFERS, xlab = "Date", ylab = "Transfers") 

    if(Outage == TRUE)
      ggplot(data, aes(Date, NUMBER_OF_TRANSFERS, colour = Incident)) + geom_point() + scale_colour_manual(values=c( "red", "black"))

    else
      ggplot(data, aes(Date, NUMBER_OF_TRANSFERS)) + geom_point()
      #points(data$Date[data$Quantity == "1"],data$NUMBER_OF_TRANSFERS[data$Quantity == "1"], col='red')
  })




lundi 1 janvier 2018

Show/Hide LineGraph/BarGraph on checkbox listener, BarGraph not working. MPAndroidChart Android

I am using MPANDROIDCHART library to show a chart, in combine chart, I am showing Line chart and Bar Chart. My requirement is when Line checkbox true it should show line and when Bar checkbox is true it should show barchart. When I uncheck line checkbox Line chart should hide. and when uncheck bar checkbox bar chart should hide.

My code is working in case of Line but in case of Bar chart, it is not working I am getting the Nullpointer exception.

Below is my code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
   xmlns:app="http://ift.tt/GEGVYd"
   xmlns:tools="http://ift.tt/LrGmb4"
   android:layout_width="match_parent"
   android:orientation="vertical"
   android:layout_height="match_parent"
   tools:context="com.swytch.chartdemo.MainActivity">

   <LinearLayout
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">

    <CheckBox
        android:id="@+id/chechbToken"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="line" />

    <CheckBox
        android:id="@+id/chechbEnergy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bar" />

</LinearLayout>



  <com.github.mikephil.charting.charts.CombinedChart
      android:id="@+id/chart1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>

</LinearLayout>

MainActivity.java

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.BubbleDataSet;
import com.github.mikephil.charting.data.BubbleEntry;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private CombinedChart mChart;
    private final int itemcount = 12;
    private CheckBox chechmnb,chechabc;

    protected String[] mMonths = new String[] {
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};

    private XAxis xAxis;

    private BarData barData;
    private LineData lineData;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        mChart = (CombinedChart) findViewById(R.id.chart1);

        checkBoxInitialiozation();
        chartInitialization();
        setChartDataBasic();
     }


     private void checkBoxInitialiozation() {

         chechabc = findViewById(R.id.chechbEnergy);
         chechmnb = findViewById(R.id.chechbToken);

         chechabc.setChecked(true);
         chechmnb.setChecked(true);

         chechabc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                 if (!b) {
                    if (!chechmnb.isChecked()) {
                        chechabc.setChecked(true);

                    } else {
                         chechabc.setChecked(false);
                      }

                 }
                 setChartData();

             }
           });
           chechmnb.setOnCheckedChangeListener(new 
  CompoundButton.OnCheckedChangeListener() {
             @Override
             public void onCheckedChanged(CompoundButton compoundButton, 
 boolean b) {
                 if (!b) {
                     if (!chechabc.isChecked()) {
                       chechmnb.setChecked(true);
                   } else {
                        chechmnb.setChecked(false);
                    }
                }
                setChartData();
            }
        });
    }
     protected float getRandom(float range, float startsfrom) {
         return (float) (Math.random() * range) + startsfrom;
     }

     private void chartInitialization() {

         mChart.getDescription().setEnabled(false);
         mChart.setBackgroundColor(Color.WHITE);
         mChart.setDrawGridBackground(false);
         mChart.setDrawBarShadow(false);
         mChart.setHighlightFullBarEnabled(false);

         // draw bars behind lines
         mChart.setDrawOrder(new CombinedChart.DrawOrder[]{
                 CombinedChart.DrawOrder.BAR,CombinedChart.DrawOrder.LINE
         });

         Legend l = mChart.getLegend();
         l.setWordWrapEnabled(true);
         l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
         l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
         l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
         l.setDrawInside(false);

         YAxis rightAxis = mChart.getAxisRight();
         rightAxis.setDrawGridLines(false);
         rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
         rightAxis.setEnabled(false);

         YAxis leftAxis = mChart.getAxisLeft();
         leftAxis.setDrawGridLines(false);
         leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

         xAxis = mChart.getXAxis();
         xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
         xAxis.setAxisMinimum(0f);
         xAxis.setGranularity(1f);

     }

     private LineData generateLineData(ArrayList<Entry> entries) {

         LineData d = new LineData();
         LineDataSet set = new LineDataSet(entries, "Token");

         set.setLineWidth(2.5f);

         set.setCircleRadius(3f);
         set.setCircleColor(getResources().getColor(R.color.colorAccent));
         set.setColors(getResources().getColor(R.color.colorAccent));
         set.setFillColor(getResources().getColor(R.color.colorPrimary));
       set.setValueTextColor(getResources().getColor(R.color.colorPrimary));
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set.setValueTextSize(10f);
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
         //to draw value in side graph
        set.setDrawValues(false);
        d.addDataSet(set);

       return d;
    }

   private BarData generateBarData(ArrayList<BarEntry> entries) {

        BarDataSet set1 = new BarDataSet(entries, "Energy");
        set1.setColor(getResources().getColor(R.color.colorPrimary));

    set1.setValueTextColor(getResources().getColor(R.color.colorAccent));
    set1.setValueTextSize(10f);
    set1.setAxisDependency(YAxis.AxisDependency.LEFT);
    //to draw value inside graph
    set1.setDrawValues(false);

    float barWidth = 0.45f; // x2 dataset

    BarData d = new BarData(set1);
    d.setBarWidth(barWidth);

    return d;
   }
   private void setChartDataBasic() {

        ArrayList<BarEntry> entriesBarEntry = new ArrayList<BarEntry>();
        ArrayList<Entry> entriesLineEntry = new ArrayList<Entry>();


        entriesBarEntry.clear();
        entriesLineEntry.clear();

        for (int index = 0; index < itemcount; index++)
            entriesLineEntry.add(new Entry(index + 0.5f, getRandom(15, 5)));

         entriesBarEntry = getBarEnteries(entriesBarEntry);

         try {
             if (mMonths.length > 0) {
               xAxis.setValueFormatter(new IAxisValueFormatter() {
                   @Override
                    public String getFormattedValue(float value, AxisBase axis) {
                    return mMonths[(int) value % mMonths.length];
                }
            });

            barData = generateBarData(entriesBarEntry);
            lineData = generateLineData(entriesLineEntry);
            setChartData();
        } else {

            mChart.setData(null);
            mChart.notifyDataSetChanged();
            mChart.invalidate();
        }
    } catch (ArithmeticException e) {
        Log.d("MainActivity", "setChartData: " + e.getMessage());
    }
}


  public void setChartData() {

    CombinedData chartData = new CombinedData();
    if (chechabc.isChecked())
        chartData.setData(barData);
    if (chechmnb.isChecked())
        chartData.setData(lineData);
    xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
    mChart.setData(chartData);
    mChart.notifyDataSetChanged();
    mChart.invalidate();

  }


   private ArrayList<BarEntry> getBarEnteries(ArrayList<BarEntry> entries) {
    entries.add(new BarEntry(1, 20));
    entries.add(new BarEntry(2, 10));
    entries.add(new BarEntry(3, 80));
    entries.add(new BarEntry(4, 40));
    entries.add(new BarEntry(5, 20));
    entries.add(new BarEntry(6, 60));
    entries.add(new BarEntry(7, 22));
    entries.add(new BarEntry(8, 15));
    entries.add(new BarEntry(9, 45));
    return entries;
  }
 }

Facing Exception

 FATAL EXCEPTION: main
                                                                  Process: 
com.swytch.chartdemo, PID: 10510

java.lang.NullPointerException: Attempt to invoke virtual method 'int 
com.github.mikephil.charting.data.BarData.getDataSetCount()' on a null 
object reference
                                                                      at 
 com.github.mikephil.charting.renderer.BarChartRenderer
 .initBuffers(BarChartRenderer.java:61)
                                                                      at 
 com.github.mikephil.charting.renderer.CombinedChartRenderer
.initBuffers(CombinedChartRenderer.java:82)
                                                                      at 
 com.github.mikephil.charting.charts.BarLineChartBase
 .notifyDataSetChanged(BarLineChartBase.java:326)
                                                                      at 
  com.github.mikephil.charting.charts.Chart.setData(Chart.java:304)
                                                                      at 
  com.github.mikephil.charting.charts.CombinedChart
 .setData(CombinedChart.java:94)
                                                                      at 
   com.swytch.chartdemo.MainActivity
  .setChartData(MainActivity.java:240)
                                                                      at 
  com.swytch.chartdemo.MainActivity$1
  .onCheckedChanged(MainActivity.java:93)
                                                                      at 
  android.widget.CompoundButton.setChecked(CompoundButton.java:154)
                                                                      at 
  android.widget.CompoundButton.toggle(CompoundButton.java:113)
                                                                      at 
  android.widget.CompoundButton.performClick(CompoundButton.java:118)
                                                                      at 
  android.view.View$PerformClick.run(View.java:19884)
                                                                      at 
  android.os.Handler.handleCallback(Handler.java:739)
                                                                      at 
  android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at 
  android.os.Looper.loop(Looper.java:135)
                                                                      at 
  android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                      at 
  java.lang.reflect.Method.invoke(Native Method)
                                                                      at 
  java.lang.reflect.Method.invoke(Method.java:372)
                                                                      at 

  com.android.internal.os.ZygoteInit$MethodAndArgsCaller
  .run(ZygoteInit.java:905)
                                                                      at 
   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

OutputImage :-

enter image description here

enter image description here




Passing data from one view to email template view on checkbox checked in code-igniter

I'm using a code-igniter to develop an web application. I'm trying to create a dynamic email template which loads data dynamically when I'm check a checkbox from other view.

Here is my scenario: enter image description here

If I'm checking a checkbox for HMO_001, then all data that will loaded in the table for HMO_001 will pass to my email template, and when I'm click on Send button the mail will send to particular landlord.

Now I'm able to send an email to multiple landlords at a time on button click when I'm check multiple checkbox, but the email is hard coded. I'm trying to make it dynamic, but no success.

Here is my Code:

Controller to load table data:

public function index()
    {
        # code...
        $user = $this->ion_auth->user()->row();
        $data['username'] = $user->username;
        $data['user_id'] = $user->id;

        $landlord = $this->input->post('landlord_id');
        $property = $this->input->post('property_id');
        $certificate = $this->input->post('certificate_id');

        if( $landlord =='') {
            $landlord = 0;
        }
        if($property == ''){
            $property = 0;
        }
        if($certificate == ''){
            $certificate = 0;
        }

        $data['landlords'] = $this->c->landlordList();
        //$data['properties'] = $this->c->propertyList();
        $data['certificates'] = $this->c->certificateList();
        //$data['certified'] = $this->c->certificate_List();

        $data['certified'] = $this->c->getcertificateByLandlordProperty($landlord, $property, $certificate);

        // print_r($data['landlords']);
        // print_r($data['properties']);
        // echo "<pre>";
        // print_r($data['certificates']);
        // echo "</pre>";
        // exit();
        $data['title'] = 'Certificate List';

        $this->load->view('template/header', $data);
        $this->load->view('certificate/certificate_list', $data);
        $this->load->view('template/footer');
    }

Controller to send mail:

public function sendMail()
    {
        # code...
        //$data['certified'] = $this->c->getcertificateByLandlordProperty($landlord, $property, $certificate);


        if(isset($_POST['submit'])){//to run PHP script on submit
            if(!empty($_POST['sendMail'])){
            // Loop to store and display values of individual checked checkbox.
                foreach($_POST['sendMail'] as $selected){
                    //echo $selected."</br>";
                }
            }
        }

        $email_to = $this->input->post('sendMail[]');

        <!-- echo "<pre>";
        print_r($email_to);
        echo "</pre>";
        exit(); -->
        $body = $this->load->view('emailTemplate/certTemplate', $data);

        $this->load->library('email');        
        $config = array();
            $config['protocol'] = 'mail';
            $config['smtp_port'] = 587;
            $config['smtp_host'] = 'smtp.office365.com';
            $config['smtp_user'] = 'info@admin.com';
            $config['smtp_pass'] = '**********';
            $config['smtp_crypto'] = 'STARTTLS';   
            $config['newline'] = "\r\n"; //REQUIRED! Notice the double quotes!
            $config['crlf'] = "\r\n";
            $config['mailtype'] = "html";

        $this->email->initialize($config);

        $this->email->from('info@admin.com', 'Administrator');
        $this->email->to($email_to);
        $this->email->subject('Your Subject');
        $this->email->message('$body');

        $sent = $this->email->send();

        if ($sent)
        {
            echo 'OK, mail send successfully';

        } else {
            echo $this->email->print_debugger();
        }
    }

Any kind of help is welcome, Thanks in advance.




Advanced Custom Field checkbox query not working

I am using an Advanced Custom Field to allocate a custom field to posts. This field is then used by a filtering system to filter posts using a custom query (via the pre_get_posts action). The other query arguments are working fine, except for the one which relies on ACF’s field.

The current query arguments of the field’s meta_query have been constructed according to the ACF documentation for the field (hence the quotation marks surrounding the value).

Can anyone advise me as to where this is going wrong? The query doesn’t seem to return any posts based on the values I am passing to the query.

Query arguments:

$courses = get_query_var('courses');
if ($courses) {
    $query->set('meta_query', array(
            array(
                'key' => 'course_check',
                'value' => '"'.$courses.'"', //i.e mdia-403
                'compare' => 'LIKE'
            ),
        )
    );
}




CakePHP 3 - Set checkbox to checked in edit view

maybe I'm blind on the point but I'm struggling for over an hour and can not find a solution.

My goal is in edit view a checkbox, which is set in the database to "yes", also to be displayed as checked.

My InputField looks like this:

<?php
    echo $this->Form->checkbox(
        'active',[
            'value'=>'yes',
            'hiddenField'=>'no'
        ]
    );
?>

Saving the values, works. But if the value "Yes" is saved, I call the edit view again, the checkbox is not marked as checked.

Is there any way to get around this? Would be more pleasant for the corresponding user as in the remaining input fields to get the value issued.

Do you have an idea or an approach?

Thank you in advance.




Elegant way to get boolean from checkbox using Apache FileItem

There is the form with the checkbox input:

<form action='${pageContext.request.contextPath}/register' method="POST"
      enctype="multipart/form-data">

        <div>
            <label class="form-check-label">
                <input id="news_feed" name="news_feed" class="form-check-input" type="checkbox" value="${sessionScope.bean.interestedInNewsFeed}">
                I want to receive updates via email.
            </label>
        </div>
</form>

In my servlet I'm trying to receive the value:

List<FileItem> multiparts = new ServletFileUpload(
                        new DiskFileItemFactory()).parseRequest(req);
                boolean interestedInNewsFeed = Boolean.parseBoolean(multiparts.stream().filter((x) -> x.getFieldName().equals("news_feed")).
                        findFirst().get().getString());

However, I'm getting the exception:

java.util.NoSuchElementException: No value present

I tried to see returned string:

  1. If checkbox is checked then empty string is returned.
  2. If checkbox isn't checked - exception is thrown.

How can I parse the checkbox value into boolean using FileItem class of Apache-Commons-FileUpload library without getting the exception?

I googled the question but can't find any relevant information.