lundi 1 août 2016

Why does my if else statement refuses to read a certain row?

I have a table below that contains the students' results in a DataGridView:-

ID  NAME    RESULT
1   Peter   PASS
1   Peter   SILVER
2   Sam     FAIL
2   Sam     SILVER
3   Simon   FAIL
4   Cliff   PASS
5   Jason   FAIL
5   Jason   FAIL
6   Leonard PASS
6   Leonard FAIL

I'm trying to produce a simple program that will filter out certain rows base on the Results upon a click of a button. What I have achieved right now is that I have able to filter out those who with PASS and/or SILVER as their Result and only display out FAIL.

The problem is right now whenever the button is clicked, it will removed the rows with a PASS and/or SILVER, except the 2nd Row: 1 Peter SILVER. Leaving me with this table below as the end result:-

enter image description here

The only way to resolved this right now is to click the button again.

Below is the source code for the button:-

    private void btnGenerate_Click(object sender, EventArgs e)
    {
       if (dtList.Rows.Count != 0)
       {
           try
           {
               foreach (DataGridViewRow dr in dtList.Rows)
               {
                   //Column names in excel file
                   string colID = dr.Cells["ID"].Value.ToString();
                   string colName = dr.Cells["Name"].Value.ToString();
                   string colResult = dr.Cells["Result"].Value.ToString();


                   if (!colResult.Equals("FAIL", StringComparison.InvariantCultureIgnoreCase))
                   {
                       dtList.Rows.Remove(dr);
                   }

               }
           }
           catch
           {

           }
        }

    }

if else cascading replacement: best option [on hold]

I am developing a simple java program which is run from command prompt using the JAR that I built. My program involves a lot of if conditions. My scenario is like, even if one if condition fails there is no point in running the remaining program.

When an if condition fails I want to do the following.

  1. I want to show the reason for stopping the program
  2. I want to quit running the program.

When an if condition validates to true, I want to continue with my execution and check the next if condition

Approach 1

I am aware that this can be achieved by using if else construct. But it leads to a lot of if else cascading and makes the code less readable and maintainable. Please find the sample below

if(name!=null){
            //some code here before next if condition
            if(gender!=null){
                //some code here before next if condition
                if(age==20){
                    //some code here before next if condition
                    if(zip!=null){
                        //some code here before next if condition
                        if(country!=null){
                            //some code here before next if condition..........
                        }
                        else{
                            System.out.println("country can't be null");
                        }
                    }
                    else{
                        System.out.println("zip can't be null");
                    }
                }
                else{
                    System.out.println("age should be 20");
                }
            }
            else{
                System.out.println("gender can't be null");
            }
        }
        else{
            System.out.println("name can't be null");
        }

Approach 2:

I was wondering if using System.exit(0) could be a good alternative to avoid cascading. Please find the sample below.

if(name==null){
            System.out.println("name can't be null");
            System.exit(0);
        }
        //some code here before next if condition
        if(gender==null){
            System.out.println("gender can't be null");
            System.exit(0);
        }
        //some code here before next if condition
        if(age==0){
            System.out.println("age should be 20");
            System.exit(0);
        }
        //some code here before next if condition
        if(zip==null){
            System.out.println("zip can't be null");
            System.exit(0);
        }
        //some code here before next if condition
        if(country==null){
            System.out.println("country can't be null");
            System.exit(0);
        }

Approach 3:

After some research I got to know that a custom exception can be thrown as well. Please find the below code.

try {
            if (name == null) {
                throw new MyCustomException("name can't be null");
            }
            // some code here before next if condition
            if (gender == null) {
                throw new MyCustomException("gender can't be null");
            }
            // some code here before next if condition
            if (age == 0) {
                throw new MyCustomException("age should be 20");
            }
            // some code here before next if condition
            if (zip == null) {
                throw new MyCustomException("zip can't be null");
            }
            // some code here before next if condition
            if (country == null) {
                throw new MyCustomException("country can't be null");
            }
        } catch (MyCustomException cusExep) {

        }

Approach 4:

I believe this is the best approach though, your thoughts please

if (name == null) {
    return("name can't be null");
}
// some code here before next if condition
if (gender == null) {
    return("gender can't be null");
}
// some code here before next if condition
if (age == 0) {
    return("age should be 20");
}
// some code here before next if condition
if (zip == null) {
    return("zip can't be null");
}
// some code here before next if condition
if (country == null) {
    return("country can't be null");
}

My question are

  1. Which is a better practice. Approach 1,2,3 or 4?
  2. Can System.exit(0) be used in scenarios like mine? If no, on what scenarios should I use System.exit(0). of course I did some research. Please find the few of the many links I deemed useful.

Thanks for being patient.

How to pass parmeters to functions inside tf.cond in Tensorflow?

I have following simple placeholders:

x = tf.placeholder(tf.float32, shape=[1])
y = tf.placeholder(tf.float32, shape=[1])
z = tf.placeholder(tf.float32, shape=[1])

There are two functions f1 and f2 defined as:

def fn1(a, b): 
    return tf.mul(a, b)
def fn2(a, b): 
    return tf.add(a, b)

Now I want to calculate result based on pred condition:

pred = tf.placeholder(tf.bool, shape=[1])
result = tf.cond(pred, f1(x,y), f2(y,z))

But it gives me an error saying fn1 and fn2 must be callable.

How can I write fn1 and fn2 so that they can receive parameters at runtime? I want to call the following:

sess.run(result, feed_dict={x:1,y:2,z:3,pred:True})

If/Else work around in PHP Codeigniter

I have an issue i've been trying to fix for a while now.

$question_session = $this->session->userdata();
    $questions = $question_session['question_details'];
    $answer_data = [];
    if (!empty($questions)) {
        $current_question = $question_session['question_details'][array_rand(($question_session['question_details']))];
         $current_question_key = array_search($current_question, $question_session['question_details']);
        unset($question_session['question_details'][$current_question_key]);
        array_values($question_session['question_details']);
        $this->session->set_userdata('question_details', $question_session['question_details']);
        $current_question['counter'] = $current_question_key + 1;
        $this->load->view('gameplay', $current_question);

        //getting the answers
        $answer = $this->input->post('answer');
        $answers =  array($current_question['_id']=>$answer);

    }

    else{
         //get answer from if condition and validate it.
    }

So, am using the above code to randomly load questions unto a page using. The questions have already been loaded into a session timer. My if statement works well. However, i'm trying to write the else statement such that when the questions in the session is empty(which means user has answered all his questions for the time), i go to another page and get the questions from the if and validate them.

Continue as First Statement in Concise If Else

I have the following if else statement inside of a foreach loop:

string date = GetDate(item)
if (date == null)
{
    continue;
}
else
{
    article.Date = date;
}

And I would like to write this in the concise format using ? ::

string date = GetDate(item)
date == null ? continue : article.Date = date;

From what I gather, this should work, as it is in the format condition ? first_expression : second_expression;, where first_expression is continue, however in Visual Studio 2015 I am seeing these errors for the given areas:

continue

Invalid expression term 'continue'

Syntax error, ':' expected

Invalid expression term 'continue'

; expected

:

; expected

: expected

Is it possible to use continue in this types of If/Else? If not, is there any reason for this?

Jquery datepicker if day=friday change options of other input dropdown

I want to let users set a date (with jquery datepicker) and a time for a meeting. Problem is, that the possible time range for the input options is shorter on fridays.

I managed to get it running onselect, so if a user selects a friday, everything works fine. But if the initial date is a friday there is no selection and therefor the function is not called. I couldn't find any onload methods, so what can I do?

$(function() {
            $('#datepicker').datepicker({
                prevText: '<zurück', prevStatus: '',
                prevJumpText: '<<', prevJumpStatus: '',
                nextText: 'Vor>', nextStatus: '',
                nextJumpText: '>>', nextJumpStatus: '',
                currentText: 'heute', currentStatus: '',
                todayText: 'heute', todayStatus: '',
                clearText: '-', clearStatus: '',
                closeText: 'schließen', closeStatus: '',
                minDate:0,
                maxDate:"+14D",
                monthNames: ['Januar','Februar','März','April','Mai','Juni',
                'Juli','August','September','Oktober','November','Dezember'],
                monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
                'Jul','Aug','Sep','Okt','Nov','Dez'],
                dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
                dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
                dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
                showMonthAfterYear: false,
                showOn: 'both',
                buttonImage: '/wp-content/themes/advoneo/img/icons/calendar-small.png',
                buttonImageOnly: true,
                dateFormat:'dd.mm.yy',
                beforeShowDay : function (date) {
                  var dayOfWeek = date.getDay ();
                  // 0 : Sunday, 1 : Monday, ...
                  if (dayOfWeek == 0 || dayOfWeek == 6) return [false];
                  else return [true];
                },
                onSelect: function (selectedDate) {
                    var date = $(this).datepicker('getDate');
                    var day = date.getDay();
                        if(day === 5 && navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1)
                           {
                            var otherFridayTime = $("#SATerminUhrzeit").find('option[value="13:00"], option[value="13:30"], option[value="14:00"], option[value="14:30"], option[value="15:00"], option[value="15:30"], option[value="16:00"], option[value="16:30"], option[value="17:00"], option[value="17:30"], option[value="18:00"], option[value="18:30"]').detach();                                                                    
                            $("#SATerminUhrzeit").append(otherFridayTime);
                        }                       
                    else {
                        if (day === 5) {    
                        $("#SATerminUhrzeit").find('option[value="13:00"], option[value="13:30"], option[value="14:00"], option[value="14:30"], option[value="15:00"], option[value="15:30"], option[value="16:00"], option[value="16:30"], option[value="17:00"], option[value="17:30"], option[value="18:00"], option[value="18:30"]').hide();                                                                    
                        }
                        else {                                              
                        $("#SATerminUhrzeit").find('option[value="13:00"], option[value="13:30"], option[value="14:00"], option[value="14:30"], option[value="15:00"], option[value="15:30"], option[value="16:00"], option[value="16:30"], option[value="17:00"], option[value="17:30"], option[value="18:00"], option[value="18:30"]').show();                                                                    
                        }
                    }
                },
                firstDay: 1
            });
        });
          </script>

Language is in German because thats where I come from. And because hide() and show() don't work for safari there is that extra "if". That is not working also but that's a problem for another question.

I hope you can help me I'm really stuck here...

dimanche 31 juillet 2016

Load existing files in blueimp jQuery file upload by id

hi iam trying to use blueimp jQuery file upload with codeigniter but i need to load existing files by id inserted in database

this is function in my controller

 public function get_files()
{

    $last = $this->uri->total_segments();
    $record_num = $this->uri->segment($last);

    if (is_numeric($record_num) == TRUE) {

    $upload_path_url = base_url() . 'uploads/';
    $config['upload_path'] = FCPATH . 'uploads/';
    $config['allowed_types'] = 'jpg|jpeg|png|gif';
    $config['max_size'] = '30000';

        $existingFiles = get_dir_file_info($config['upload_path']);
        $foundFiles = array();
        $f=0;
        foreach ($existingFiles as $fileName => $info) {
          if($fileName!='thumbs'){//Skip over thumbs directory
            //set the data for the json array   
            $foundFiles[$f]['name'] = $fileName;
            $foundFiles[$f]['size'] = $info['size'];
            $foundFiles[$f]['url'] = $upload_path_url . $fileName;
            $foundFiles[$f]['thumbnailUrl'] = $upload_path_url . 'thumbs/' .                 $fileName;
            $foundFiles[$f]['deleteUrl'] = base_url() . 'http://ift.tt/2akxtQW' . $fileName;
            $foundFiles[$f]['deleteType'] = 'DELETE';
            $foundFiles[$f]['error'] = null;

            $f++;
          }
        }
        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(array('files' => $foundFiles)));

and in main.js

// Load existing files:
    $('#fileupload').addClass('fileupload-processing');
    $.ajax({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        // url: $('#fileupload').fileupload('option', 'url'),
        url: 'http://localhost/mysite/index.php/App/controll/get_files',
        dataType: 'json',
        context: $('#fileupload')[0]
    }).always(function () {
        $(this).removeClass('fileupload-processing');
    }).done(function (result) {
        $(this).fileupload('option', 'done')
            .call(this, $.Event('done'), {result: result});
    });

but this if statement if (is_numeric($record_num) == TRUE) didn't work