问:
Add dash/hyphen after 4 digits in edittext in android
I was implemented like after 4 digits hyphen display automatically like(2015-07) in edittext. my code works fine, but problem is while i delete before 4 digits value and again type it not working. addTextChangedListener not trigger when i edidtext retype like 2015-07 to 2014-07. But while i using "/" instead of "-" i can retype value. What is the problem?</p>

```<code>mEdtProductionCode.addTextChangedListener(new TextWatcher() {
        int prevL = 0;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            prevL = mEdtProductionCode.getText().toString().length();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            int length = s.length();
            if ((prevL < length) && length == 4) {
                String data = mEdtProductionCode.getText().toString();
                mEdtProductionCode.setText(data + "-");
                mEdtProductionCode.setSelection(length + 1);
            }
        }
    });
</code>```

答:
You should just move your character checking to the character after the fifth character has been entered, and then chop down String to put the custom character in between:

```<code> @Override
        public void afterTextChanged(Editable s) {
            int length = s.length();
            if ((prevL <= length) && length == 5) {

                String data = mEditProductionCode.getText().toString();
                String beginData = data.substring(0,4);

                String endData = Character.toString(data.charAt(length-1));
                mEditProductionCode.setText(beginData + "-" + endData);
                mEditProductionCode.setSelection(length + 1);
            }
        }
</code>```

You can also use data.charAt(length-1) != '-' to check if user manually made dash input, in which case you just ignore and do not make changes to TextEdit.

Body:
I was implemented like after 4 digits hyphen display automatically like(2015-07) in edittext. my code works fine, but problem is while i delete before 4 digits value and again type it not working. addTextChangedListener not trigger when i edidtext retype like 2015-07 to 2014-07. But while i using "/" instead of "-" i can retype value. What is the problem?

mEdtProductionCode.addTextChangedListener(new TextWatcher() {
        int prevL = 0;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            prevL = mEdtProductionCode.getText().toString().length();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            int length = s.length();
            if ((prevL < length) && length == 4) {
                String data = mEdtProductionCode.getText().toString();
                mEdtProductionCode.setText(data + "-");
                mEdtProductionCode.setSelection(length + 1);
            }
        }
    });

Body:
You should just move your character checking to the character after the fifth character has been entered, and then chop down String to put the custom character in between:

 @Override
        public void afterTextChanged(Editable s) {
            int length = s.length();
            if ((prevL <= length) && length == 5) {

                String data = mEditProductionCode.getText().toString();
                String beginData = data.substring(0,4);

                String endData = Character.toString(data.charAt(length-1));
                mEditProductionCode.setText(beginData + "-" + endData);
                mEditProductionCode.setSelection(length + 1);
            }
        }

You can also use data.charAt(length-1) != '-' to check if user manually made dash input, in which case you just ignore and do not make changes to TextEdit.


来源: stackexchange

问:
Form Button Refreshes on Click - One page Website
I've created a contact form so that users can send us an email. However, every time I click to send the email it also refreshes the page when clicked. This is a one page website.

I've attempted the fixes suggested in: How do I make an HTML button not reload the page

by using either the <button> element or use an <input type="button"/>. and also the fixes suggested in: prevent refresh of page when button inside form clicked

by adding onclick="return false;".

Both of these fixes stop the button from refreshing the page when it is clicked, however, it also stops the contact form from actually working and no longer sends an email to us.

I also updated my PHP to reflect the name changes of the type.

My PHP is:

```<code><?php
   if(isset($_POST['submit'])){
   $to = "example@example.com"; // this is your Email address
   $from = $_POST['email']; // this is the sender's Email address
   $name = $_POST['name'];
   $subject = "Form submission";
   $subject2 = "Copy of your form submission";
   $message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
   $message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];

   $headers = "From:" . $from;
   $headers2 = "From:" . $to;
   mail($to,$subject,$message,$headers);
   mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
   echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";

   }
?>
</code>```

My HTML is:

```<code><form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>
</code>```

This currently works for sending the email, but does not stop it from refreshing the page. Would appreciate any help as to why it is doing this..

EDIT:

I've tried a few different options using AJAX since it was suggested this was the best route to take. All successfully stopped the page from refreshing, but all the options once again, stopped my contact form from working. I tried:

1:

```<code>$(function() {
    $('#contactForm').on('submit', function(e) {
        $.post('index.php', $(this).serialize(), function (data) {
            // This is executed when the call to mail.php was succesful.
            // 'data' contains the response from the request
        }).error(function() {
            // This is executed when the call to mail.php failed.
        });
        e.preventDefault();
    });
});
</code>```

2:

```<code>$("#contactForm").submit(function(e) {
    e.preventDefault();
});
</code>```

3:

I also tried the answer offered to me by Harsh Panchal.

答:
Use jQuery AJAX form submit and also Event.preventDefault(), so that page is not refreshed further.

for more help here is the link https://api.jquery.com/jquery.post/

ContentLicense: CC BY-SA 3.0

Body:
I've created a contact form so that users can send us an email. However, every time I click to send the email it also refreshes the page when clicked. This is a one page website.

I've attempted the fixes suggested in: How do I make an HTML button not reload the page

by using either the <button> element or use an <input type="button"/>. and also the fixes suggested in: prevent refresh of page when button inside form clicked

by adding onclick="return false;".

Both of these fixes stop the button from refreshing the page when it is clicked, however, it also stops the contact form from actually working and no longer sends an email to us.

I also updated my PHP to reflect the name changes of the type.

My PHP is:

<?php
   if(isset($_POST['submit'])){
   $to = "example@example.com"; // this is your Email address
   $from = $_POST['email']; // this is the sender's Email address
   $name = $_POST['name'];
   $subject = "Form submission";
   $subject2 = "Copy of your form submission";
   $message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
   $message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];

   $headers = "From:" . $from;
   $headers2 = "From:" . $to;
   mail($to,$subject,$message,$headers);
   mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
   echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";

   }
?>

My HTML is:

<form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">

<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>

<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>

This currently works for sending the email, but does not stop it from refreshing the page. Would appreciate any help as to why it is doing this..

EDIT:

I've tried a few different options using AJAX since it was suggested this was the best route to take. All successfully stopped the page from refreshing, but all the options once again, stopped my contact form from working. I tried:

1:

$(function() {
    $('#contactForm').on('submit', function(e) {
        $.post('index.php', $(this).serialize(), function (data) {
            // This is executed when the call to mail.php was succesful.
            // 'data' contains the response from the request
        }).error(function() {
            // This is executed when the call to mail.php failed.
        });
        e.preventDefault();
    });
});

2:

$("#contactForm").submit(function(e) {
    e.preventDefault();
});

3:

I also tried the answer offered to me by Harsh Panchal.


问:
How to retrieve the latest eventName (latest by date)
I have two arrays

```<code>var events=["DELIVERED", "OUT TO DELEVERY", "REACHED WAREHOUSE", "DEPARTED"];

var eventDetails= [{
"source" : "application"
"DateTime": "2016-05-12 11:20:00",
"eventName" : "DELIVERED"
},
{
"source" : "application"
"DateTime": "2017-06-07 00:00:00",
"eventName" : "OUT TO DELEVERY"
},
{
"source" : "application"
"DateTime": "2016-11-05 11:20:00",
"eventNname" : "CUSTOM CLEARANCE"
}];
</code>```

I need to display the latest eventName (latest by date and time) from eventDetails array, if the latest eventName is present in "events" Array. Else it should return null( if eventName in latest updated record doesn't contain any of the value from event array).

答:
you can use javascript sort method and use indexOf to check the value is exist in the events array

var events=["DELIVERED", "REACHED WAREHOUSE", "OUT TO DELEVERY", "DEPARTED"];

var eventDetails= [{
"source" : "application",
"DateTime": "2016-05-12 11:20:00",
"eventName" : "DELIVERED"
},
{
"source" : "application",
"DateTime": "2017-06-07 00:00:00",
"eventName" : "OUT TO DELEVERY"
},
{
"source" : "application",
"DateTime": "2016-11-05 11:20:00",
"eventName" : "CUSTOM CLEARANCE"
}];

eventDetails = eventDetails.sort(function(a,b){
  return new Date(b.DateTime) - new Date(a.DateTime)
})

if( events.indexOf(eventDetails[0].eventName) !== -1 ){
  console.log('true')
}else{
 console.log('false')
}```

Body:
I have two arrays

var events=["DELIVERED", "OUT TO DELEVERY", "REACHED WAREHOUSE", "DEPARTED"];

var eventDetails= [{
"source" : "application"
"DateTime": "2016-05-12 11:20:00",
"eventName" : "DELIVERED"
},
{
"source" : "application"
"DateTime": "2017-06-07 00:00:00",
"eventName" : "OUT TO DELEVERY"
},
{
"source" : "application"
"DateTime": "2016-11-05 11:20:00",
"eventNname" : "CUSTOM CLEARANCE"
}];

I need to display the latest eventName (latest by date and time) from eventDetails array, if the latest eventName is present in "events" Array. Else it should return null( if eventName in latest updated record doesn't contain any of the value from event array).


答:
```<code>SELECT HOUR(your_date) as Hour,DAYNAME(your_date) as Dayname,WEEK(your_date) as Weeknumber, DAYOFMONTH(your_date) as datenumber from table.
</code>```

NOTE: You can use either DAYOFMONTH/DAYOFWEEK for day number.

Title: Divide timestamp in MySQL

Body:
I have a question regarding time in MySQL.
How do i get a time stamp like this:

2014-12-07 12:54:42.000000

To correctly insert itself in this table:
The timestamp has to divide to,Hour,Dayname,Weeknumber,Daynumber
I need a fixed value of 1 in every layar of the table

+-------------+----------+--------+-----+-----+-----------x
| fixedval    | Hour     | Dayname| Weeknumber| Daynumber |
+-------------+----------+--------+-----------+-----------+
| 1           |          |        |           |           |
| 1           |          |        |           |           |
| 1           |          |        |           |           |
| 1           |          |        |           |           |
| 1           |          |        |           |           |
+-------------+----------+--------+-----------+-----------+

Body:
SELECT HOUR(your_date) as Hour,DAYNAME(your_date) as Dayname,WEEK(your_date) as Weeknumber, DAYOFMONTH(your_date) as datenumber from table.

NOTE: You can use either DAYOFMONTH/DAYOFWEEK for day number.


问:
Monthly interval between two date
I have two dates like 2017-10-05 and 2018-02-20, my interval result should be:

```<code>2017-10-05
2017-10-31
2017-11-30
2017-12-31
2018-01-31
2018-02-20
2018-02-28
</code>```

Any suggestions to do this in C# using DateTime object?

UPDATE #1

The problem I mentioned first concerns is a real situation of a cash flow management, so I had to change dates specifications for the calculation of interest, dif and civ. This code i use for the purpose:

```<code>foreach (DataRow dr in DTFlussi.Rows)
{
    DateTime d1 = Convert.ToDateTime(DTFlussi.Rows[n]["data_scadenza"]).Date;
    DateTime d2 = Convert.ToDateTime(DTFlussi.Rows[n + 1]["data_scadenza"]).Date;
    int[] date = RecuperoDate(d1, d2);

    if (saldoConto > 0)
        InteressiAttivi(saldoConto, date, DTOneri, d1, d2);
    else if (saldoConto <= 0 && saldoConto >= (fidoConto * -1))
    {
        //esempio di interessi FIDO al 2%
        InteressiFido(saldoConto, date, tassoFIDO, DTOneri, d1, d2);
    }
    else if (saldoConto < 0 && saldoConto < (fidoConto * -1))
    {
        //esempio con interessi FIDO al 2% e interessi EXTRAFIDO al 4%
        InteressiExtraFido(saldoConto, fidoConto, date, tassoFIDO, tassoEXTRAFIDO, DTOneri, d1, d2);
    }
    catch (Exception)
    {

    }
    n++;
}
</code>```

The code for RecuperoDate is:

```<code>public int[] RecuperoDate(DateTime d1, DateTime d2)
{
    int[] diff = new int[2];

    //Gestione anno bisestile Febbrario
    int giorniFebbraio = 0;
    if (DateTime.IsLeapYear(d1.Year))
        giorniFebbraio = 29;
    else
        giorniFebbraio = 28;

    try
    {
        #region MESE 1

        if (d1.Date >= new DateTime(d1.Year, 1, 1) && d1.Date <= new DateTime(d1.Year, 1, 31) && d2.Date >= new DateTime(d1.Year, 1, 31))
        {
            DateTime Mese1 = new DateTime(d1.Year, 1, 31).Date;
            diff[0] = (int)(Mese1 - d1).TotalDays;
            diff[1] = (int)(d2 - Mese1).TotalDays;
        }

        #endregion

        //NOTE: incomplete code because is the same thing for the other months (February - December)
</code>```

This is necessary to obtain subsequent variations in the balance and at the end of the calculations this is what I want:

答:
Create an array.</p>

```<code>            DateTime[] dateArray = {
                                       DateTime.Parse("2017-10-05"),
                                       DateTime.Parse("2017-10-31"),
                                       DateTime.Parse("2017-11-30"),
                                       DateTime.Parse("2017-12-31"),
                                       DateTime.Parse("2018-02-20"),
                                       DateTime.Parse("2018-02-28")
                                   };
</code>```

Title: Monthly interval between two date

Body:
I have two dates like 2017-10-05 and 2018-02-20, my interval result should be:

2017-10-05
2017-10-31
2017-11-30
2017-12-31
2018-01-31
2018-02-20
2018-02-28

Any suggestions to do this in C# using DateTime object?

UPDATE #1

The problem I mentioned first concerns is a real situation of a cash flow management, so I had to change dates specifications for the calculation of interest, dif and civ. This code i use for the purpose:

foreach (DataRow dr in DTFlussi.Rows)
{
    DateTime d1 = Convert.ToDateTime(DTFlussi.Rows[n]["data_scadenza"]).Date;
    DateTime d2 = Convert.ToDateTime(DTFlussi.Rows[n + 1]["data_scadenza"]).Date;
    int[] date = RecuperoDate(d1, d2);

    if (saldoConto > 0)
        InteressiAttivi(saldoConto, date, DTOneri, d1, d2);
    else if (saldoConto <= 0 && saldoConto >= (fidoConto * -1))
    {
        //esempio di interessi FIDO al 2%
        InteressiFido(saldoConto, date, tassoFIDO, DTOneri, d1, d2);
    }
    else if (saldoConto < 0 && saldoConto < (fidoConto * -1))
    {
        //esempio con interessi FIDO al 2% e interessi EXTRAFIDO al 4%
        InteressiExtraFido(saldoConto, fidoConto, date, tassoFIDO, tassoEXTRAFIDO, DTOneri, d1, d2);
    }
    catch (Exception)
    {

    }
    n++;
}

The code for RecuperoDate is:

public int[] RecuperoDate(DateTime d1, DateTime d2)
{
    int[] diff = new int[2];

    //Gestione anno bisestile Febbrario
    int giorniFebbraio = 0;
    if (DateTime.IsLeapYear(d1.Year))
        giorniFebbraio = 29;
    else
        giorniFebbraio = 28;

    try
    {
        #region MESE 1

        if (d1.Date >= new DateTime(d1.Year, 1, 1) && d1.Date <= new DateTime(d1.Year, 1, 31) && d2.Date >= new DateTime(d1.Year, 1, 31))
        {
            DateTime Mese1 = new DateTime(d1.Year, 1, 31).Date;
            diff[0] = (int)(Mese1 - d1).TotalDays;
            diff[1] = (int)(d2 - Mese1).TotalDays;
        }

        #endregion

        //NOTE: incomplete code because is the same thing for the other months (February - December)

This is necessary to obtain subsequent variations in the balance and at the end of the calculations this is what I want:

Body:
Create an array.

            DateTime[] dateArray = {
                                       DateTime.Parse("2017-10-05"),
                                       DateTime.Parse("2017-10-31"),
                                       DateTime.Parse("2017-11-30"),
                                       DateTime.Parse("2017-12-31"),
                                       DateTime.Parse("2018-02-20"),
                                       DateTime.Parse("2018-02-28")
                                   };


问:
HTML Table : Overflow-x scroll if no of columns are more
I have a table with certain columns. If I add columns then the table div should scroll horizontally.

Let say I have 10 columns and I add 2 more columns.

so I want there is no scroll up to 10 columns and If there are 2 more columns , then There should be overflow-x:scroll.

.horizontal_scroll_div{

}

.horizontal_scroll_div .scroll_table_div{
  overflow-x: scroll !important;
}

.horizontal_scroll_div .scroll_table_div .table_section{
  width:1200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="horizontal_scroll_div">
    <div class="scroll_table_div b">
      <div class="table_section">
      <div class="row m-l-none m-r-none " >
          <div class="col-sm-12 col-md-12 set_padding_0">
                <div class="table-responsive m-b-none no_border">
                <table class="table b-t b-b no-footer">
                  <thead class="bg-white">
                  <tr>
                    <th>column 1</th>
                    <th>column 2</th>
                    <th>column 3</th>
                    <th>column 4</th>
                    <th>column 5</th>
                    <th>column 6</th>
                    <th>column 7</th>
                    <th>column 8</th>
                    <th>column 9</th>
                    <th>column 10</th>
                    <th>column 11</th>
                    <th>column 12</th>

                  </tr>
                  </thead>
                  <tbody>
                  <tr>
                    <td>value 1</td>
                    <td>value 2</td>
                    <td>value 3</td>
                    <td>value 4</td>
                    <td>value 5</td>
                    <td>value 6</td>
                    <td>value 7</td>
                    <td>value 8</td>
                    <td>value 9</td>
                    <td>value 10</td>
                    <td>value 11</td>
                    <td>value 12</td>
                  </tr>
                  </tbody>
                  </table>
               </div>
          </div>
       </div>
  </div>
  </div>
  </div></code>```

Any help would be great.
Thank You.

答:
Set a fixed width for the ten columns so that adding extra columns would be more than the fixed width, leading to a scroll appearing. In which case you can use</p>

```<code>overflow-x:auto;
</code>```

Body:
I have a table with certain columns. If I add columns then the table div should scroll horizontally.

Let say I have 10 columns and I add 2 more columns.

so I want there is no scroll up to 10 columns and If there are 2 more columns , then There should be overflow-x:scroll.

.horizontal_scroll_div{

}

.horizontal_scroll_div .scroll_table_div{
  overflow-x: scroll !important;
}

.horizontal_scroll_div .scroll_table_div .table_section{
  width:1200px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

                    column 1
                    column 2
                    column 3
                    column 4
                    column 5
                    column 6
                    column 7
                    column 8
                    column 9
                    column 10
                    column 11
                    column 12

                    value 1
                    value 2
                    value 3
                    value 4
                    value 5
                    value 6
                    value 7
                    value 8
                    value 9
                    value 10
                    value 11
                    value 12

Any help would be great.
Thank You.

Body:
Set a fixed width for the ten columns so that adding extra columns would be more than the fixed width, leading to a scroll appearing. In which case you can use

overflow-x:auto;


问:
Apache Tomcat/6.0.32 - Web app doesn't start
I'am trying start my webapp on my tomcat manager, but it dowsn't up.
I'm reading log file of the webapp and I have thise error:

8-giu-2017 9.41.12 org.apache.catalina.core.StandardContext start
  GRAVE: Error listenerStart
  8-giu-2017 9.41.12 org.apache.catalina.core.StandardContext start
  GRAVE: Context [/ImageProcessor] startup failed due to previous errors
  8-giu-2017 9.41.12 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
  GRAVE: The web application [/ImageProcessor] registered the JDBC driver [oracle.jdbc.OracleDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
  8-giu-2017 9.41.12 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
  GRAVE: The web application [/ImageProcessor] appears to have started a thread named [oracle.jdbc.driver.BlockSource.ThreadedCachingBlockSource.BlockReleaser] but has failed to stop it. This is very likely to create a memory leak.
  8-giu-2017 9.41.12 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
  GRAVE: The web application [/ImageProcessor] appears to have started a thread named [CommunicatorServer] but has failed to stop it. This is very likely to create a memory leak.

答:
The issue is that "oracle.jdbc.driver.BlockSource.ThreadedCachingBlockSource.BlockReleaser"
thread is running and it is not stopping so Tomcat will show it as a memory leak.
You have to deregister the drivers manually. See the link below to get insight.

https://stackoverflow.com/a/5315467/7083879


问:
CrashlyticsMissingDependencyException when compiling debug release on Android Studio
I'm receiving this error every time I compile the debug version of my app

```<code>03-04 12:02:48.241    8933-8933/com.cmr.activities E/Fabric﹕ This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,
install an Android build tool and ask a team member to invite you to this app's organization
</code>```

The problem it self is, I know the meaning of the error but I have all installed and when I had this error in the past I just cleaned the project and worked again. Now suddenly I'm receiving this error and now I can't fix it. Any idea?

I worked with Crashlytics since past year in several projects but I hate this "crash", and is worst with flavors changes configurations.

Actual configuration:

```<code>dependencies {
    classpath 'io.fabric.tools:gradle:1.15.2'
}

....
compile('com.crashlytics.sdk.android:crashlytics:2.2.1@aar') {
    transitive = true;
}
</code>```

And in Application

```<code>public void onCreate() {
    ...
    Fabric.with(this, new Crashlytics());
    ...
}
</code>```

And of course, Android Studio plugin installed and logged in.

Thanks!

答: Got this today and I solved it by removing everything crashlytics related in my code and do an "invalidate caches / restart", then select crashlytics and install via the plugin.</p>

Body:
I'm receiving this error every time I compile the debug version of my app

03-04 12:02:48.241    8933-8933/com.cmr.activities E/Fabric﹕ This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,
install an Android build tool and ask a team member to invite you to this app's organization

The problem it self is, I know the meaning of the error but I have all installed and when I had this error in the past I just cleaned the project and worked again. Now suddenly I'm receiving this error and now I can't fix it. Any idea?

I worked with Crashlytics since past year in several projects but I hate this "crash", and is worst with flavors changes configurations.

Actual configuration:

dependencies {
    classpath 'io.fabric.tools:gradle:1.15.2'
}

....
compile('com.crashlytics.sdk.android:crashlytics:2.2.1@aar') {
    transitive = true;
}

And in Application

public void onCreate() {
    ...
    Fabric.with(this, new Crashlytics());
    ...
}

And of course, Android Studio plugin installed and logged in.

Thanks!


问:
How to check different conditions into if statement based on different scenario
I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.

```<code>$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
    $cond = "$fstrto <= $cstrto";
}
else
{
    $cond = "$fstrto >= $cstrto";
}
if($cond)
{
    echo "Success";
}
</code>```

This code is not working as it takes the "$fstrto <= $cstrto" as variable.

答:
Remove the quotes. Use intval/doubleval if the input is a string as in $fstrto = intval($fstrto);.

```<code>$fstrto = 10;
$cstrto = 7;
if($status == 'N')
{
    $cond = $fstrto <= $cstrto;
}
else
{
    $cond = $fstrto >= $cstrto;
}
if($cond)
{
    echo "Success";
}
</code>```

Why it works: $cond is being assigned the value of a boolean expression, the values of which can be true or false. if($cond) just checks whether $cond is true or false

Body:
I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.

$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
    $cond = "$fstrto <= $cstrto";
}
else
{
    $cond = "$fstrto >= $cstrto";
}
if($cond)
{
    echo "Success";
}

This code is not working as it takes the "$fstrto <= $cstrto" as variable.

Body:
Remove the quotes. Use intval/doubleval if the input is a string as in $fstrto = intval($fstrto);.

$fstrto = 10;
$cstrto = 7;
if($status == 'N')
{
    $cond = $fstrto <= $cstrto;
}
else
{
    $cond = $fstrto >= $cstrto;
}
if($cond)
{
    echo "Success";
}

Why it works: $cond is being assigned the value of a boolean expression, the values of which can be true or false. if($cond) just checks whether $cond is true or false


问:
rxjava2 - how to pass in a consumer as parameter
i am using the following rxjava dependencies in android:

```<code> compile 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
</code>```

and i am trying to create a method that will take in a observer as a paramter. I am having some issues i think its because this is rxjava2 so things are updated and im a little confused.

Let me show you what i want to accomplish:

```<code>private Subscription subscription = Scriptions.empty(); //this isn't working. how to set a empty observer IN RXJAVA2?

protected abstract Observable buildUseCaseObservable(); //RETROFIT WILL BUILD THE OBSERVABLE FOR ME SOMEWHERE ELSE

public void execute(Consumer UseCaseSubscriber){
    this.subscription = this.buildUseCaseObservable()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(UseCaseSubscriber); //THIS LINE IS NOT WORKING , ERROR IS IN THE PHOTO
}

public void unsubscribe(){
    if(!subscription.isUnsubscribed()){
        subscription.unsubscribe();
    }
}
</code>```

Basically i am trying to create a method that will accept a observer/consumer as parameter and use that to update the UI after retrofit is done (being the observable).

UPDATE:
ok i changed it to disposables. now i'd like to store the disposable that i get back but its not working.

```<code>protected abstract Observable buildUseCaseObservable();

    @SuppressWarnings("unchecked")
    public void execute(Observer UseCaseSubscriber){
        this.subscription = this.buildUseCaseObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(UseCaseSubscriber);
    }

    public void unsubscribe(){
        if(!subscription.isUnsubscribed()){
            subscription.unsubscribe();
        }
    }
</code>```

i am getting the following warning:

The reason i want to store the whole thing in a subscription (or whatever else you recommend) is so i can unsubscribe to it whenever i want.

but from the docs:

Because Reactive-Streams base interface, org.reactivestreams.Publisher defines the subscribe() method as void, Flowable.subscribe(Subscriber) no longer returns any Subscription (or Disposable). The other base reactive types also follow this signature with their respective subscriber types.

so how to save disposable so we can unsubscribe then ?

答:
Subscription has been 'renamed' to Disposable with 2.x version. You can read the rxJava wiki explanation on this change here.

so how to save disposable so we can unsubscribe then ? Flowable.subscribe(Subscriber) doesn't return disposable, but Observable.subscribe(Subscriber) does. If you don't need back-pressure, just cast your Flowable to Observable with .toObservable().

Body:
i am using the following rxjava dependencies in android:

 compile 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

and i am trying to create a method that will take in a observer as a paramter. I am having some issues i think its because this is rxjava2 so things are updated and im a little confused.

Let me show you what i want to accomplish:

private Subscription subscription = Scriptions.empty(); //this isn't working. how to set a empty observer IN RXJAVA2?

protected abstract Observable buildUseCaseObservable(); //RETROFIT WILL BUILD THE OBSERVABLE FOR ME SOMEWHERE ELSE

public void execute(Consumer UseCaseSubscriber){
    this.subscription = this.buildUseCaseObservable()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(UseCaseSubscriber); //THIS LINE IS NOT WORKING , ERROR IS IN THE PHOTO
}

public void unsubscribe(){
    if(!subscription.isUnsubscribed()){
        subscription.unsubscribe();
    }
}

Basically i am trying to create a method that will accept a observer/consumer as parameter and use that to update the UI after retrofit is done (being the observable).

UPDATE:
ok i changed it to disposables. now i'd like to store the disposable that i get back but its not working.

protected abstract Observable buildUseCaseObservable();

    @SuppressWarnings("unchecked")
    public void execute(Observer UseCaseSubscriber){
        this.subscription = this.buildUseCaseObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(UseCaseSubscriber);
    }

    public void unsubscribe(){
        if(!subscription.isUnsubscribed()){
            subscription.unsubscribe();
        }
    }

i am getting the following warning:

The reason i want to store the whole thing in a subscription (or whatever else you recommend) is so i can unsubscribe to it whenever i want.

but from the docs:

Because Reactive-Streams base interface, org.reactivestreams.Publisher defines the subscribe() method as void, Flowable.subscribe(Subscriber) no longer returns any Subscription (or Disposable). The other base reactive types also follow this signature with their respective subscriber types.

so how to save disposable so we can unsubscribe then ?


问:
Get the name of instance as string in Javascript
Im working with Three.js and javascript.
When my code executes this:

```<code>console.log(this.scene.children[1])
</code>```

I get this in my console of Chrome:

How can I get the name of the object ('WidgetsRuler') as a string?
I dont see any attribute that saves this information.

答:
Okay I Solved it using:</p>

```<code>console.log(this.scene.children[1].constructor.name)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im working with Three.js and javascript.
When my code executes this:

console.log(this.scene.children[1])

I get this in my console of Chrome:

How can I get the name of the object ('WidgetsRuler') as a string?
I dont see any attribute that saves this information.

Body:
Okay I Solved it using:

console.log(this.scene.children[1].constructor.name)


问:
Conditional fortran record variable selection
I have a structure defined:

```<code>STRUCTURE /IOA/
  INTEGER*2 ID
  .....
END STRUCTURE
</code>```

I need to create another structure, IOB. IOB contains all the same fields as IOA but with many more.

```<code>STRUCTURE /IOB/
  INTEGER*2 ID
  .....
END STRUCTURE
</code>```

My program currently has:

```<code>RECORD /IOA/ A
RECORD /IOB/ B
</code>```

The program will either use A or B depending on a user input.

Is there any way to have some sort of conditional in the code to use A or B depending on what's required? For example, is it possible to create a placeholder record (variable?) "IO" and define it based on the input?:

```<code>If user input = 1, IO = A
else IO = B
.....

IO.ID = 30
</code>```

Thank you.

答:
That's what polymorphism in modern Fortran (2003 and further) is for.

```<code>   use iso_fortran_env, only: int16

   implicit none

    type IOA
      integer(int16) :: ID
    end type

    type, extends(IOA) :: IOB
      integer :: extendedID
    end type

    class(IOA), allocatable :: IO

    integer :: user_input = 2

    if (user_input == 1) then
      allocate(IOA :: IO)
    else
      allocate(IOB :: IO)
    end if

    IO%ID = 30

    select type (IO)
      type is (IOB)
        IO%extendedID = 42
      class default !just an illustration
        continue
    end select
end
</code>```

You can't do this with the obsolete DEC extensions STRUCTURE and RECORD. A advise against using these extensions. They are not part of standard Fortran.

Body:
I have a structure defined:

STRUCTURE /IOA/
  INTEGER*2 ID
  .....
END STRUCTURE

I need to create another structure, IOB. IOB contains all the same fields as IOA but with many more.

STRUCTURE /IOB/
  INTEGER*2 ID
  .....
END STRUCTURE

My program currently has:

RECORD /IOA/ A
RECORD /IOB/ B

The program will either use A or B depending on a user input.

Is there any way to have some sort of conditional in the code to use A or B depending on what's required? For example, is it possible to create a placeholder record (variable?) "IO" and define it based on the input?:

If user input = 1, IO = A
else IO = B
.....

IO.ID = 30

Thank you.

Body:
That's what polymorphism in modern Fortran (2003 and further) is for.

   use iso_fortran_env, only: int16

   implicit none

    type IOA
      integer(int16) :: ID
    end type

    type, extends(IOA) :: IOB
      integer :: extendedID
    end type

    class(IOA), allocatable :: IO

    integer :: user_input = 2

    if (user_input == 1) then
      allocate(IOA :: IO)
    else
      allocate(IOB :: IO)
    end if

    IO%ID = 30

    select type (IO)
      type is (IOB)
        IO%extendedID = 42
      class default !just an illustration
        continue
    end select
end

You can't do this with the obsolete DEC extensions STRUCTURE and RECORD. A advise against using these extensions. They are not part of standard Fortran.


问:
HornetQ, consumer can't find queue
I'm trying to use ActiveMQ-CPP with HornetQ. I'm using the ActiveMQ-CPP bundled example, but I'm having a hard time with it.
The producer works like a charm, but the consumer gives me the following message:

* BEGIN SERVER-SIDE STACK TRACE

Message: Queue /queue/exampleQueue does not exist
Exception Class

 END SERVER-SIDE STACK TRACE *

FILE: activemq/core/ActiveMQConnection.cpp, LINE: 768

FILE: activemq/core/ActiveMQConnection.cpp, LINE: 774

FILE: activemq/core/ActiveMQSession.cpp, LINE: 350

FILE: activemq/core/ActiveMQSession.cpp, LINE: 281

Time to completion = 0.161 seconds.

The problem is that the queue exists. The code works all right with ActiveMQ+Openwire, but I'm not having the same luck with HornetQ+STOMP.

Any ideas?

答: HornetQ doesn't like the "/queue/" prefix for a SUBSCRIBE.  I took that out of the ToStomp method in StompHelper and everything worked.</p>

ContentLicense: CC BY-SA 2.5

Title: HornetQ, consumer can't find queue


问:
I have error with my android app
I'm new developer in android development i have two apps in play store but my apps now is not working with android 6 & android 7 i get this messages

runtimeException
  and NullPointerException

this my main activity code i have problem with:

```<code>public class Recored extends Activity {

Button rec,stop;
private MediaRecorder myRecords;
private String outputFile = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recored);

    stop = (Button)findViewById(R.id.bStop);
    rec = (Button)findViewById(R.id.bRecord);

    stop.setEnabled(false);
    myRecords = new MediaRecorder();
    myRecords.setAudioSource(MediaRecorder.AudioSource.MIC);
    myRecords.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    myRecords.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    Date createdDate = new Date();
    File myDir = new File(Environment.getExternalStorageDirectory()+"/Recordings");
    if (!myDir.exists()){
        if (myDir.mkdir());
    }
        outputFile = myDir.getAbsolutePath() + "/" + createdDate + ".mp3";
        myRecords.setOutputFile(outputFile);

        rec.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myRecords.prepare();
                    myRecords.start();

                }

                catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                rec.setEnabled(false);
                stop.setEnabled(true);
                Toast.makeText(getApplicationContext(),"Recording started",Toast.LENGTH_LONG).show();
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myRecords.stop();
                myRecords.release();
                myRecords = null;
                stop.setEnabled(false);
                rec.setEnabled(true);
            }
        });

}
</code>```

}

答:
Need to handle runtime permission on android 6 & upper version. You have to ask for permission and manage your code according to permission is denied or accepted.

You can refer below link for runtime permission
https://developer.android.com/training/permissions/requesting.html

Title: I have error with my android app

Body:
I'm new developer in android development i have two apps in play store but my apps now is not working with android 6 & android 7 i get this messages

runtimeException
  and NullPointerException

this my main activity code i have problem with:

public class Recored extends Activity {

Button rec,stop;
private MediaRecorder myRecords;
private String outputFile = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recored);

    stop = (Button)findViewById(R.id.bStop);
    rec = (Button)findViewById(R.id.bRecord);

    stop.setEnabled(false);
    myRecords = new MediaRecorder();
    myRecords.setAudioSource(MediaRecorder.AudioSource.MIC);
    myRecords.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    myRecords.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    Date createdDate = new Date();
    File myDir = new File(Environment.getExternalStorageDirectory()+"/Recordings");
    if (!myDir.exists()){
        if (myDir.mkdir());
    }
        outputFile = myDir.getAbsolutePath() + "/" + createdDate + ".mp3";
        myRecords.setOutputFile(outputFile);

        rec.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myRecords.prepare();
                    myRecords.start();

                }

                catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                rec.setEnabled(false);
                stop.setEnabled(true);
                Toast.makeText(getApplicationContext(),"Recording started",Toast.LENGTH_LONG).show();
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myRecords.stop();
                myRecords.release();
                myRecords = null;
                stop.setEnabled(false);
                rec.setEnabled(true);
            }
        });

}

}


问:
How Yolo calculate P(Object) in the YOLO 9000
Currently I am testing the yolo 9000 model for object detection and in the Paper I understand that the image is splited in 13X13 boxes and in each boxes we calculate P(Object), but How can we calculate that ? how can the model know if there is an object in this boxe or not, please I need help to understand that

I am using tensorflow

Thanks,

答: They train for the confidence score = P(object) * IOU. For the ground truth box they take P(object)=1 and for rest of the grid pixels the ground truth P(object) is zero. You are training your network to tell you if some object in that grid location i.e. output 0 if not object, output IOU if partial object and output 1 if object is present. So at test time, your model has become capable of telling if there is an object at that location.</p>


问:
Running a git command with wildcard works in bash but not through Process
I want to run git check-ignore using sys.process.Process. This works in the shell (bash):

```<code>$ cd /home/me/Documents/Foo
$ git check-ignore *
target
</code>```

There is a directory /home/me/Documents/Foo/target that is being ignored through /home/me/Documents/Foo/.gitignore.

The same doesn't work when I run this through sys.process:

```<code>import scala.sys.process._
val workingDir = new java.io.File("/home/me/Documents/Foo")
Process(Seq("git", "check-ignore", "*"), workingDir).!
</code>```

It gives return code 1, meaning that no file matched. If I specify the particular name, it works:

```<code>Process(Seq("git", "check-ignore", "target"), workingDir).!
</code>```

This prints target and returns code zero.

So why doesn't the wildcard * work here, and how do I make it work (given that I want to list all ignored files and I have no prior knowledge what those files would be)?

答: It seems that * is a wildcard expanded by bash and not directly support by git check-ignored. The way around is instead to list the children of the working directory, and pass them one by one as arguments to git.

Body:
I want to run git check-ignore using sys.process.Process. This works in the shell (bash):

$ cd /home/me/Documents/Foo
$ git check-ignore *
target

There is a directory /home/me/Documents/Foo/target that is being ignored through /home/me/Documents/Foo/.gitignore.

The same doesn't work when I run this through sys.process:

import scala.sys.process._
val workingDir = new java.io.File("/home/me/Documents/Foo")
Process(Seq("git", "check-ignore", "*"), workingDir).!

It gives return code 1, meaning that no file matched. If I specify the particular name, it works:

Process(Seq("git", "check-ignore", "target"), workingDir).!

This prints target and returns code zero.

So why doesn't the wildcard * work here, and how do I make it work (given that I want to list all ignored files and I have no prior knowledge what those files would be)?


问:
How to efficiently build a tree from a flat structure?
I have a bunch of objects in a flat structure. These objects have an ID and a ParentID property so they can be arranged in trees. They are in no particular order.
Each ParentID property does not necessarily matches with an ID in the structure. Therefore their could be several trees emerging from these objects.

How would you process these objects to create the resulting trees ?

I'm not so far from a solution but I'm sure it is far from optimal...

I need to create these trees to then insert Data into a database, in proper order.

There are no circular references. A Node is a RootNode when ParentID == null or when ParentID can't be found in the other objects

答: Are you stuck using only those attributes?  If not, it might be nice to create an array of child nodes, where you can cycle through all these objects once to build such attributes.  From there, select the node with children but no parents and iteratively build your tree from the top down.</p>

OwnerDisplayName: Costo

LastEditorDisplayName: Costo

OwnerDisplayName: Robert Elwell


问:
RoR nested :include to include sub-resources in to_xml/to_json
I have a weird data model situation to start with, so maybe my whole approach is wrong. Here's what I'm doing:

I have a class called Bird and a simple class called Color. Conceptually, each bird has two to_many associations to Color, one for male colors and one for female colors. The way I've handled this is to use a join model called BirdColoration that belongs to a bird and a color and has an additional boolean field to tell if the coloration is for male or female. So each bird actually has a to_many relationship to BirdColoration as well as a to_many to Color :through BirdColoration. If this sounds reasonable, then continue reading. Otherwise, stop and tell me why it's wrong!

I need to be able to dump the birds table as json. Previously, when each bird only had one to_many association to colors, I could just use :include to include each bird's colors in the json dump. Now, I'm including the BirdColorations in the dump, but I still need to get at the color models themselves. I could separately include each bird's colors and colorations and then match them up while parsing, but I would much rather just include each coloration's color directly. Something like

```<code>      format.json  { render :json => @birds.to_json(:include => [{:bird_colorations => :color}, :seasons, :habitats, :image_holders]) }
</code>```

The above doesn't work, however. I think that this should be possible. Can anyone point me in the right direction for how to handle this?

For now, I'll just include each bird's color and colorations separately and match them up in parsing. At least I know that will work.

Thanks!

答:
I found the answer here. The syntax for the :include option in to_xml and to_json is different than that for ActiveRecord's find method. To include nested resources in this way, you pass in a hash instead of an array. The correct method call for me looks like:

```<code>      format.json  { render :json => @birds.to_json(:include => {:bird_colorations => {:include => :color}, :seasons => {}, :habitats => {}, :image_holders => {}}) }
</code>```

Compare to the one in my question to see the difference. For resources for which you don't want to include sub-resources, just pass an empty hash as the value for it's symbolized name.

Live and learn!

Body:
I have a weird data model situation to start with, so maybe my whole approach is wrong. Here's what I'm doing:

I have a class called Bird and a simple class called Color. Conceptually, each bird has two to_many associations to Color, one for male colors and one for female colors. The way I've handled this is to use a join model called BirdColoration that belongs to a bird and a color and has an additional boolean field to tell if the coloration is for male or female. So each bird actually has a to_many relationship to BirdColoration as well as a to_many to Color :through BirdColoration. If this sounds reasonable, then continue reading. Otherwise, stop and tell me why it's wrong!

I need to be able to dump the birds table as json. Previously, when each bird only had one to_many association to colors, I could just use :include to include each bird's colors in the json dump. Now, I'm including the BirdColorations in the dump, but I still need to get at the color models themselves. I could separately include each bird's colors and colorations and then match them up while parsing, but I would much rather just include each coloration's color directly. Something like

      format.json  { render :json => @birds.to_json(:include => [{:bird_colorations => :color}, :seasons, :habitats, :image_holders]) }

The above doesn't work, however. I think that this should be possible. Can anyone point me in the right direction for how to handle this?

For now, I'll just include each bird's color and colorations separately and match them up in parsing. At least I know that will work.

Thanks!

Body:
I found the answer here. The syntax for the :include option in to_xml and to_json is different than that for ActiveRecord's find method. To include nested resources in this way, you pass in a hash instead of an array. The correct method call for me looks like:

      format.json  { render :json => @birds.to_json(:include => {:bird_colorations => {:include => :color}, :seasons => {}, :habitats => {}, :image_holders => {}}) }

Compare to the one in my question to see the difference. For resources for which you don't want to include sub-resources, just pass an empty hash as the value for it's symbolized name.

Live and learn!


问:
jquery can't alert ajax response
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

```<code>    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }
</code>```

However, if the above code was written without

```<code>    if (response == 'false') {

    }
</code>```

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

答:
You can have following options
Use any one from them :

1) As for boolean comparison dont use speech marks so use false instead of 'false'

if (response == false) {

```<code>}
</code>```

2) directly use response for decision making

if (!response) {

```<code>}
</code>```

3) if (response == false)
   alert("whatever you wish to put")

4) if (!response)
   alert("whatever you wish to put")

Title: jquery can't alert ajax response

Body:
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }

However, if the above code was written without

    if (response == 'false') {

    }

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

Body:
You can have following options
Use any one from them :

1) As for boolean comparison dont use speech marks so use false instead of 'false'

if (response == false) {

}

2) directly use response for decision making

if (!response) {

}

3) if (response == false)
   alert("whatever you wish to put")

4) if (!response)
   alert("whatever you wish to put")


问:
PHP / MySQL - Search query
I need help making a search query for comments (it's for a WordPress site).

the comments are retrieved this way- if user is logged in:

```<code>       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));
</code>```

if not:

```<code>       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (comment_author = %s
         AND comment_author_email = %s AND comment_approved = '0'))
       ORDER BY comment_date_gmt",
       $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES),
       $comment_author_email));
</code>```

so I how can I filter comments that contain a specific search string, like $_GET['search_query'] ?

this is WP's database structure. The search string I'm looking for is in comment_content

答:
use LIKE</p>

```<code> $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_content LIKE ('%$_GET['search_query']%')
and comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));
</code>```

Title: PHP / MySQL - Search query

Body:
I need help making a search query for comments (it's for a WordPress site).

the comments are retrieved this way- if user is logged in:

       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));

if not:

       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (comment_author = %s
         AND comment_author_email = %s AND comment_approved = '0'))
       ORDER BY comment_date_gmt",
       $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES),
       $comment_author_email));

so I how can I filter comments that contain a specific search string, like $_GET['search_query'] ?

this is WP's database structure. The search string I'm looking for is in comment_content

Body:
use LIKE

 $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_content LIKE ('%$_GET['search_query']%')
and comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));


问:
LESS: combine properties (rules) with same value
I am using LESS CSS preprocessor. For example if there are two (or more) rules with same value

```<code>.my-class {
    border-top: 2px solid @main-bg-color - #123456;
    border-bottom: 2px solid @main-bg-color - #123456;
}
</code>```

can I combine those two into one somehow like this?

```<code>.my-class {
    border-top, border-bottom: 2px solid @main-bg-color - #123456;
}
</code>```

UPDATE: You shouldn't be concentrated on the props (border) I wrote just as example. I'd like to know if there's any way to combine any multiple props with same value. If there is no way to do so, please say it explicitly.

答: As @seven-phases-max says, there is no way to combine several props with same value in LESS. Use variables or mixins instead.</p>

Body:
I am using LESS CSS preprocessor. For example if there are two (or more) rules with same value

.my-class {
    border-top: 2px solid @main-bg-color - #123456;
    border-bottom: 2px solid @main-bg-color - #123456;
}

can I combine those two into one somehow like this?

.my-class {
    border-top, border-bottom: 2px solid @main-bg-color - #123456;
}

UPDATE: You shouldn't be concentrated on the props (border) I wrote just as example. I'd like to know if there's any way to combine any multiple props with same value. If there is no way to do so, please say it explicitly.


问:
Python: variables assigned before for loop
I'm new to python but not programming in general. Checking "Dive into Python" I have found this example (which works) but I don't get the syntax.

```<code>return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
</code>```

Simply put, it's using variables k and v as strings for the "%s=%s" (nothing weird here) but those variables don't have any value yet. And just like that there is a for loop which iterates and assigns values to k and v. So this is what puzzles me:
1. The for loop is "returning" somehow values k and v to the previous statement (k,v).
2. Both statements (1. "%s=%s" % (k, v) and 2. for k, v in params.items()) can be in the same line with no syntax error.

I have checked the "for" syntax reference and it doesn't even hint in this direction, so I'm sure I have to check somewhere else, but don't know where.

Thank you in advance.

答:
List comprehensions are a tool for transforming one list (any iterable actually) into another list. During this transformation, elements can be conditionally included in the new list and each element can be transformed as needed.

If you’re familiar with functional programming, you can think of list comprehensions as syntactic sugar for a filter followed by a map:

```<code>>>> doubled_odds = map(lambda n: n * 2, filter(lambda n: n % 2 == 1, numbers))
>>> doubled_odds = [n * 2 for n in numbers if n % 2 == 1]
</code>```

Every list comprehension can be rewritten as a for loop but not every for loop can be rewritten as a list comprehension.

If you can rewrite your code to look just like this for loop, you can also rewrite it as a list comprehension:

```<code>new_things = []
for ITEM in old_things:
    if condition_based_on(ITEM):
        new_things.append("something with " + ITEM)
</code>```

You can rewrite the above for loop as a list comprehension like this:

```<code>new_things = ["something with " + ITEM for ITEM in old_things if condition_based_on(ITEM)]
</code>```

Body:
I'm new to python but not programming in general. Checking "Dive into Python" I have found this example (which works) but I don't get the syntax.

return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

Simply put, it's using variables k and v as strings for the "%s=%s" (nothing weird here) but those variables don't have any value yet. And just like that there is a for loop which iterates and assigns values to k and v. So this is what puzzles me:
1. The for loop is "returning" somehow values k and v to the previous statement (k,v).
2. Both statements (1. "%s=%s" % (k, v) and 2. for k, v in params.items()) can be in the same line with no syntax error.

I have checked the "for" syntax reference and it doesn't even hint in this direction, so I'm sure I have to check somewhere else, but don't know where.

Thank you in advance.

Body:
List comprehensions are a tool for transforming one list (any iterable actually) into another list. During this transformation, elements can be conditionally included in the new list and each element can be transformed as needed.

If you’re familiar with functional programming, you can think of list comprehensions as syntactic sugar for a filter followed by a map:

>>> doubled_odds = map(lambda n: n * 2, filter(lambda n: n % 2 == 1, numbers))
>>> doubled_odds = [n * 2 for n in numbers if n % 2 == 1]

Every list comprehension can be rewritten as a for loop but not every for loop can be rewritten as a list comprehension.

If you can rewrite your code to look just like this for loop, you can also rewrite it as a list comprehension:

new_things = []
for ITEM in old_things:
    if condition_based_on(ITEM):
        new_things.append("something with " + ITEM)

You can rewrite the above for loop as a list comprehension like this:

new_things = ["something with " + ITEM for ITEM in old_things if condition_based_on(ITEM)]


问:
how to use drop down widget in kivy with a python class
So, I think there should be at least two ways that I could have a drop down menu on this page, but I can get neither to work.  I am new to kivy and programming in general, but I have read the documentation and it seems that I simply do not understand.

I have created the following example:

```<code>import kivy
kivy.require('1.7.2') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
from kivy.uix.dropdown import DropDown

class CustomDropDown(DropDown):
    pass

class HomeScreen(Screen):
    translateInput = ObjectProperty(None)
    translateButton = ObjectProperty(None)
    translateLabel = ObjectProperty(None)
    top_layout = ObjectProperty(None)
    dd_btn = ObjectProperty(None)
    drop_down = CustomDropDown()
    #notes_dropdown = ObjectProperty(None)

    dropdown = DropDown()
    notes = ['Features', 'Suggestions', 'Abreviations', 'Miscellaneous']
    for note in notes:
        # when adding widgets, we need to specify the height manually (disabling
        # the size_hint_y) so the dropdown can calculate the area it needs.
        btn = Button(text='%r' % note, size_hint_y=None, height=30)

        # for each button, attach a callback that will call the select() method
        # on the dropdown. We'll pass the text of the button as the data of the
        # selection.
        btn.bind(on_release=lambda btn: dropdown.select(btn.text))

        # then add the button inside the dropdown
        dropdown.add_widget(btn)

    # create a big main button
    mainbutton = Button(text='Usage Notes 2', size_hint=(1, 1))

    # show the dropdown menu when the main button is released
    # note: all the bind() calls pass the instance of the caller (here, the
    # mainbutton instance) as the first argument of the callback (here,
    # dropdown.open.).
    mainbutton.bind(on_release=dropdown.open)
    #dd_btn.bind(on_release=dropdown.open)

    # one last thing, listen for the selection in the dropdown list and
    # assign the data to the button text.
    dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
    #dropdown.bind(on_select=lambda instance, x: setattr(dd_btn, 'text', x))

    #top_layout.add_widget(mainbutton)

class dropdApp(App):

    def build(self):

        return HomeScreen()

if __name__ == '__main__':
    dropdApp().run()
</code>```

And this is the corresponding .kv file:

```<code>#:kivy 1.7.2

<CustomDropDown>:
    Button:
        text: 'My first Item'
        size_hint_y: None
        height: 44
        on_release: root.select('item1')
    Label:
        text: 'Unselectable item'
        size_hint_y: None
        height: 44
    Button:
        text: 'My second Item'
        size_hint_y: None
        height: 44
        on_release: root.select('item2')

<HomeScreen>:
    id: home_screen
    translateInput: translateInputID
    translateButton: translateButtonID
    translateLabel: labelID
    top_layout: topLayoutID
    #notes_dropdown: notesDropDownID
    dd_btn: btn_ddID

    orientation: 'vertical'
    FloatLayout:
        size_hint: 1, .95
        TextInput:
            id: translateInputID
            text: 'cove'
            #text: 'ﻰﺸَﻣ'
            font_name: "data/fonts/DejaVuSans.ttf"
            background_color: 1, 1, 1, 1
            size_hint: .75, .1
            multiline: False
            pos_hint: {'x': .125, 'y': .45}
            text_size: self.size
            valign: 'middle'
            halign: 'center'
            padding: 5

        Button:
            id: translateButtonID
            text: 'Translate'
            pos_hint: {'x': .35, 'y': .35}
            size_hint: .3, .08
            valign: 'middle'
            halign: 'center'
            text_size: self.size
            on_release: root.translateButtonPressed()
            #on_press: root.manager.current = 'resultsscreen'

        Label:
            id: labelID
            text: 'Translator'
            text_size: self.size
            valign: 'middle'
            halign: 'center'
            pos_hint: {'x': .3, 'y': .75}
            size_hint: .4, .2
            #font_name: "simpo.ttf"
            #font_name: "5thgradecursive.ttf"
            #font_name: "AGA-Rasheeq-Regular.ttf"
            font_name: "data/fonts/DejaVuSans.ttf"
            font_size: 50

    BoxLayout:
        id: topLayoutID
        #cols: 2
        size_hint: 1, .05
        pos_hint: {'x': 0, 'y': .95}
        Button:
            #id: notesDropDownID
            id: btn_ddID
            text: 'Usage Notes'
            on_release: root.drop_down.open
        Button:
            text: 'About'
</code>```

The first drop-down menu should be attached to the already created button, "Usage Notes", at the bottom of the kv file.  It is attached to the class in python, "CustomDropDown", and the corresponding  in the kv file.  You might notice this example is straight out of the kivy documentation.  I thought by creating the line:

```<code>drop_down = CustomDropDown()
</code>```

it gave me a handle in both python and the kivy side to manipulate it, but as you might notice when you run it and click "Usage Notes", nothing happens.

The second drop-down menu is created in python also following the kivy documentation.  I would think it would create a third button at the top of the app, titled, "Usage Notes 2".  I just get an error when I try to add it.  Right now the line (53 on my file):

```<code>top_layout.add_widget(mainbutton)
</code>```

is commented out or the app wouldn't even run, raising the error:

```<code>AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'add_widget'
</code>```

Which I realize that I did set

```<code>top_layout = ObjectProperty(None)
</code>```

but that is what kivy suggests doing for many widgets, and I have done with many others without this error.

I'm sure one or both of these issues is simple to someone out there.  What am I missing?

答:
I'm posting this here in the hope that it helps other kivy beginners who just want a dropdown button that they can place in a .kv file.</p>
```<code>class DropBut(Button):
    def __init__(self, **kwargs):
        super(DropBut, self).__init__(**kwargs)
        self.drop_list = None
        self.drop_list = DropDown()

        types = ['Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Item6']

        for i in types:
            btn = Button(text=i, size_hint_y=None, height=50)
            btn.bind(on_release=lambda btn: self.drop_list.select(btn.text))

            self.drop_list.add_widget(btn)

        self.bind(on_release=self.drop_list.open)
        self.drop_list.bind(on_select=lambda instance, x: setattr(self, 'text', x))
</code>```

Body:
So, I think there should be at least two ways that I could have a drop down menu on this page, but I can get neither to work.  I am new to kivy and programming in general, but I have read the documentation and it seems that I simply do not understand.

I have created the following example:

import kivy
kivy.require('1.7.2') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
from kivy.uix.dropdown import DropDown

class CustomDropDown(DropDown):
    pass

class HomeScreen(Screen):
    translateInput = ObjectProperty(None)
    translateButton = ObjectProperty(None)
    translateLabel = ObjectProperty(None)
    top_layout = ObjectProperty(None)
    dd_btn = ObjectProperty(None)
    drop_down = CustomDropDown()
    #notes_dropdown = ObjectProperty(None)

    dropdown = DropDown()
    notes = ['Features', 'Suggestions', 'Abreviations', 'Miscellaneous']
    for note in notes:
        # when adding widgets, we need to specify the height manually (disabling
        # the size_hint_y) so the dropdown can calculate the area it needs.
        btn = Button(text='%r' % note, size_hint_y=None, height=30)

        # for each button, attach a callback that will call the select() method
        # on the dropdown. We'll pass the text of the button as the data of the
        # selection.
        btn.bind(on_release=lambda btn: dropdown.select(btn.text))

        # then add the button inside the dropdown
        dropdown.add_widget(btn)

    # create a big main button
    mainbutton = Button(text='Usage Notes 2', size_hint=(1, 1))

    # show the dropdown menu when the main button is released
    # note: all the bind() calls pass the instance of the caller (here, the
    # mainbutton instance) as the first argument of the callback (here,
    # dropdown.open.).
    mainbutton.bind(on_release=dropdown.open)
    #dd_btn.bind(on_release=dropdown.open)

    # one last thing, listen for the selection in the dropdown list and
    # assign the data to the button text.
    dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
    #dropdown.bind(on_select=lambda instance, x: setattr(dd_btn, 'text', x))

    #top_layout.add_widget(mainbutton)

class dropdApp(App):

    def build(self):

        return HomeScreen()

if __name__ == '__main__':
    dropdApp().run()

And this is the corresponding .kv file:

#:kivy 1.7.2

<CustomDropDown>:
    Button:
        text: 'My first Item'
        size_hint_y: None
        height: 44
        on_release: root.select('item1')
    Label:
        text: 'Unselectable item'
        size_hint_y: None
        height: 44
    Button:
        text: 'My second Item'
        size_hint_y: None
        height: 44
        on_release: root.select('item2')

<HomeScreen>:
    id: home_screen
    translateInput: translateInputID
    translateButton: translateButtonID
    translateLabel: labelID
    top_layout: topLayoutID
    #notes_dropdown: notesDropDownID
    dd_btn: btn_ddID

    orientation: 'vertical'
    FloatLayout:
        size_hint: 1, .95
        TextInput:
            id: translateInputID
            text: 'cove'
            #text: 'ﻰﺸَﻣ'
            font_name: "data/fonts/DejaVuSans.ttf"
            background_color: 1, 1, 1, 1
            size_hint: .75, .1
            multiline: False
            pos_hint: {'x': .125, 'y': .45}
            text_size: self.size
            valign: 'middle'
            halign: 'center'
            padding: 5

        Button:
            id: translateButtonID
            text: 'Translate'
            pos_hint: {'x': .35, 'y': .35}
            size_hint: .3, .08
            valign: 'middle'
            halign: 'center'
            text_size: self.size
            on_release: root.translateButtonPressed()
            #on_press: root.manager.current = 'resultsscreen'

        Label:
            id: labelID
            text: 'Translator'
            text_size: self.size
            valign: 'middle'
            halign: 'center'
            pos_hint: {'x': .3, 'y': .75}
            size_hint: .4, .2
            #font_name: "simpo.ttf"
            #font_name: "5thgradecursive.ttf"
            #font_name: "AGA-Rasheeq-Regular.ttf"
            font_name: "data/fonts/DejaVuSans.ttf"
            font_size: 50

    BoxLayout:
        id: topLayoutID
        #cols: 2
        size_hint: 1, .05
        pos_hint: {'x': 0, 'y': .95}
        Button:
            #id: notesDropDownID
            id: btn_ddID
            text: 'Usage Notes'
            on_release: root.drop_down.open
        Button:
            text: 'About'

The first drop-down menu should be attached to the already created button, "Usage Notes", at the bottom of the kv file.  It is attached to the class in python, "CustomDropDown", and the corresponding  in the kv file.  You might notice this example is straight out of the kivy documentation.  I thought by creating the line:

drop_down = CustomDropDown()

it gave me a handle in both python and the kivy side to manipulate it, but as you might notice when you run it and click "Usage Notes", nothing happens.

The second drop-down menu is created in python also following the kivy documentation.  I would think it would create a third button at the top of the app, titled, "Usage Notes 2".  I just get an error when I try to add it.  Right now the line (53 on my file):

top_layout.add_widget(mainbutton)

is commented out or the app wouldn't even run, raising the error:

AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'add_widget'

Which I realize that I did set

top_layout = ObjectProperty(None)

but that is what kivy suggests doing for many widgets, and I have done with many others without this error.

I'm sure one or both of these issues is simple to someone out there.  What am I missing?

Body:
I'm posting this here in the hope that it helps other kivy beginners who just want a dropdown button that they can place in a .kv file.

class DropBut(Button):
    def __init__(self, **kwargs):
        super(DropBut, self).__init__(**kwargs)
        self.drop_list = None
        self.drop_list = DropDown()

        types = ['Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Item6']

        for i in types:
            btn = Button(text=i, size_hint_y=None, height=50)
            btn.bind(on_release=lambda btn: self.drop_list.select(btn.text))

            self.drop_list.add_widget(btn)

        self.bind(on_release=self.drop_list.open)
        self.drop_list.bind(on_select=lambda instance, x: setattr(self, 'text', x))


问:
How do I write the $_SERVER["PHP_SELF"] that's already in a php echo
I have a form that is written in PHP that will call the page upon itself (I don't know if I say this right).

```<code>echo('</table>
<hr>
<h1 id="loadscript_h1">Voeg een loadscript toe</h1>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" enctype="multipart/form-data">
<div><input type="file" name="loadscript" id="loadscript" value="Kies loadscript"/></div>');
echo ('<input type="submit" class="formsubmit" name="upload_loadscript" value="Upload loadscripts" />
</form>');
</code>```

But when I look at my website there is something written like this:

```<code>" method="POST" enctype="multipart/form-data">
</code>```

How can I write this properly?

答:
Using PHP Heredoc

```<code>$action = htmlspecialchars($_SERVER["PHP_SELF"]);
$form = <<<FORM
    </table>
    <hr>
    <h1 id="loadscript_h1">Voeg een loadscript toe</h1>
    <form action="{$action}" method="POST" enctype="multipart/form-data">
    <div><input type="file" name="loadscript" id="loadscript" value="Kies loadscript"/></div>
    <input type="submit" class="formsubmit" name="upload_loadscript" value="Upload loadscripts" />
    </form>
FORM;

echo $form;
</code>```

You can also just leave the action field empty and the form will submit back to itself when posted.

Body:
I have a form that is written in PHP that will call the page upon itself (I don't know if I say this right).

echo('

Voeg een loadscript toe

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" enctype="multipart/form-data">

<input type="file" name="loadscript" id="loadscript" value="Kies loadscript"/>
');
echo ('<input type="submit" class="formsubmit" name="upload_loadscript" value="Upload loadscripts" />
</form>');

But when I look at my website there is something written like this:

" method="POST" enctype="multipart/form-data">

How can I write this properly?

Body:
Using PHP Heredoc

$action = htmlspecialchars($_SERVER["PHP_SELF"]);
$form = <<<FORM
    </table>
    <hr>
    <h1 id="loadscript_h1">Voeg een loadscript toe</h1>
    <form action="{$action}" method="POST" enctype="multipart/form-data">
    <div><input type="file" name="loadscript" id="loadscript" value="Kies loadscript"/></div>
    <input type="submit" class="formsubmit" name="upload_loadscript" value="Upload loadscripts" />
    </form>
FORM;

echo $form;

You can also just leave the action field empty and the form will submit back to itself when posted.


问:
Python: Checking if a key is part of a dictionary
I'm trying to make my own irc bot (for twitch) in Python. I have a dictionary with my commands:

```<code>commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands
</code>```

Then I have a function to check if the message that was send is indeed a command:

```<code>import string

def is_valid_command(command):
    return True if command in commands.keys() else False
</code>```

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong:

```<code>message = "!ping"
print(str(is_valid_command(message)))
>>> False
</code>```

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' and it always says it's False.

Thanks in regards,
Laurens

EDIT:

```<code>def is_valid_command(command):
    for key in commands.keys():
        print(key)
    print("input " + str(command))
    print(command in commands.keys())
    return command in commands.keys()
</code>```

This result in this:

```<code>!ping
!random
input !ping
False
</code>```

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return False

```<code>try:
    cmd = commands[command]
    print ('Try True')
    return True
except KeyError:
    print('Try False')
    return False
</code>```

EDIT3: u'!ping' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding?

答:
Yes, there is a function to convert a string to unicode. Use unicode function e.g. unicode('my_string').

For example if your message from irc is stored in a variable message_from_irc then you can convert it as unicode(message_from_irc).

I suggest you switch keyboard language to English when coding, in order to avoid this types of unexpected behaviors of code.

Body:
I'm trying to make my own irc bot (for twitch) in Python. I have a dictionary with my commands:

commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands

Then I have a function to check if the message that was send is indeed a command:

import string

def is_valid_command(command):
    return True if command in commands.keys() else False

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong:

message = "!ping"
print(str(is_valid_command(message)))
>>> False

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' and it always says it's False.

Thanks in regards,
Laurens

EDIT:

def is_valid_command(command):
    for key in commands.keys():
        print(key)
    print("input " + str(command))
    print(command in commands.keys())
    return command in commands.keys()

This result in this:

!ping
!random
input !ping
False

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return False

try:
    cmd = commands[command]
    print ('Try True')
    return True
except KeyError:
    print('Try False')
    return False

EDIT3: u'!ping' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding?


问:
HTML Table : Overflow-x scroll if no of columns are more
I have a table with certain columns. If I add columns then the table div should scroll horizontally.

Let say I have 10 columns and I add 2 more columns.

so I want there is no scroll up to 10 columns and If there are 2 more columns , then There should be overflow-x:scroll.

.horizontal_scroll_div{

}

.horizontal_scroll_div .scroll_table_div{
  overflow-x: scroll !important;
}

.horizontal_scroll_div .scroll_table_div .table_section{
  width:1200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="horizontal_scroll_div">
    <div class="scroll_table_div b">
      <div class="table_section">
      <div class="row m-l-none m-r-none " >
          <div class="col-sm-12 col-md-12 set_padding_0">
                <div class="table-responsive m-b-none no_border">
                <table class="table b-t b-b no-footer">
                  <thead class="bg-white">
                  <tr>
                    <th>column 1</th>
                    <th>column 2</th>
                    <th>column 3</th>
                    <th>column 4</th>
                    <th>column 5</th>
                    <th>column 6</th>
                    <th>column 7</th>
                    <th>column 8</th>
                    <th>column 9</th>
                    <th>column 10</th>
                    <th>column 11</th>
                    <th>column 12</th>

                  </tr>
                  </thead>
                  <tbody>
                  <tr>
                    <td>value 1</td>
                    <td>value 2</td>
                    <td>value 3</td>
                    <td>value 4</td>
                    <td>value 5</td>
                    <td>value 6</td>
                    <td>value 7</td>
                    <td>value 8</td>
                    <td>value 9</td>
                    <td>value 10</td>
                    <td>value 11</td>
                    <td>value 12</td>
                  </tr>
                  </tbody>
                  </table>
               </div>
          </div>
       </div>
  </div>
  </div>
  </div></code>```

Any help would be great.
Thank You.

答:
Ok. I think you should manually set css change.
For example. 10 columns 100 width without scroll, 12 - with scroll</p>

```<code>    .column{width: 100px;} #its 10x100 = 1000px

     @media screen and (min-width: 1001px)  {
         .table {overflow-x: scroll;}
    }
</code>```

Body:
I have a table with certain columns. If I add columns then the table div should scroll horizontally.

Let say I have 10 columns and I add 2 more columns.

so I want there is no scroll up to 10 columns and If there are 2 more columns , then There should be overflow-x:scroll.

.horizontal_scroll_div{

}

.horizontal_scroll_div .scroll_table_div{
  overflow-x: scroll !important;
}

.horizontal_scroll_div .scroll_table_div .table_section{
  width:1200px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

                    column 1
                    column 2
                    column 3
                    column 4
                    column 5
                    column 6
                    column 7
                    column 8
                    column 9
                    column 10
                    column 11
                    column 12

                    value 1
                    value 2
                    value 3
                    value 4
                    value 5
                    value 6
                    value 7
                    value 8
                    value 9
                    value 10
                    value 11
                    value 12

Any help would be great.
Thank You.

Body:
Ok. I think you should manually set css change.
For example. 10 columns 100 width without scroll, 12 - with scroll

    .column{width: 100px;} #its 10x100 = 1000px

     @media screen and (min-width: 1001px)  {
         .table {overflow-x: scroll;}
    }


问:
Jest: cannot find module required inside module to be tested (relative path)
I have this component:

```<code>import React from 'react';
import VideoTag from './VideoTag';
import JWPlayer from './JWPlayer';

class VideoWrapper extends React.Component {
//... component code
}
</code>```

That based on some logic renders another component inside ( VideoTag or JWPlayer) but when I try to test it in a jest file i get the error:

Cannot find module './VideoTag'

The three coponents are in the same directory that's why it actually works when I transpile it and see it in action in a browser but looks like Jest is having problems resolving those relative paths, this is the jest file:

```<code>jest.dontMock('../src/shared/components/Video/VideoWrapper.jsx');

import React from 'react';
import ReactDOM from 'react-dom';
TestUtils from 'react-addons-test-utils';

import VideoWrapper from '../src/shared/components/Video/VideoWrapper.jsx';

describe('VideoWrapper tests', () => {
  it('Render JWPlayer', () => {

      let vWrapper = TestUtils.renderIntoDocument(
      < VideoWrapper model={model} />
  );

  });
});
</code>```

The error is at line:

```<code>import VideoWrapper from '../src/shared/components/Video/VideoWrapper.jsx';
</code>```

How do I tell jest how to handle relative paths?

答: You don't need to add moduleFileExtensions in the configuration for these two options since jest uses ['js', 'jsx', 'json', 'node'] as default file extensions. (Unless you want to specifically skip any option that is)</p>

Body:
I have this component:

import React from 'react';
import VideoTag from './VideoTag';
import JWPlayer from './JWPlayer';

class VideoWrapper extends React.Component {
//... component code
}

That based on some logic renders another component inside ( VideoTag or JWPlayer) but when I try to test it in a jest file i get the error:

Cannot find module './VideoTag'

The three coponents are in the same directory that's why it actually works when I transpile it and see it in action in a browser but looks like Jest is having problems resolving those relative paths, this is the jest file:

jest.dontMock('../src/shared/components/Video/VideoWrapper.jsx');

import React from 'react';
import ReactDOM from 'react-dom';
TestUtils from 'react-addons-test-utils';

import VideoWrapper from '../src/shared/components/Video/VideoWrapper.jsx';

describe('VideoWrapper tests', () => {
  it('Render JWPlayer', () => {

      let vWrapper = TestUtils.renderIntoDocument(
      < VideoWrapper model={model} />
  );

  });
});

The error is at line:

import VideoWrapper from '../src/shared/components/Video/VideoWrapper.jsx';

How do I tell jest how to handle relative paths?