问:
How to report Likelihood Ratio Test results
I am using a Likelihood Ratio Test (in R) to look for main effects in my model with three fixed factors (site, year, habitat) like this:

```<code>model1<-glm(tot.mass~hab, data=biom, family = Gamma(link = "log"))
anova(model1, test="Chisq")
model2<-glm(tot.mass~year, data=biom, family = Gamma(link = "log"))
anova(model2, test="Chisq")
model3<-glm(tot.mass~site, data=biom, family = Gamma(link = "log"))
anova(model3, test="Chisq")
</code>```

I was told that by using "anova(model3, test="Chisq")" I will find whether (in this example) adding in the term "site" significantly improves the model. From what I understand, since my p value is >0.5, site doesn't have a significant effect on my model (e.g. isn't a main effect for this response variable). My output looks like this:

```<code>     Df Deviance Resid. Df Resid. Dev Pr(>Chi)
NULL                   687     1681.2
site  2   16.543       685     1664.7   0.2884
</code>```

My questions are 1) am I interpreting this correctly and 2) how would I report these results? Would I report the Deviance and pvalue ("Pr(>Chi)")?

Thank you!

答:
Some comments before answering this,

1) Always keep in mind that the order you test the terms in your model plays  significant role in their statistical significance. This happens because you sequentially compare models against each other (i.e. in your case you compared the NULL model (no predictors) against a model with "site" as the only predictor). If you add an extra variable then you comparing the model containing only "site" against a model containing "site" and "some other variable".

2) An easy way to remember that is by thinking of deviance as the "distance" between two models (chisq takes only positive values) so they further apart are two models the more likely is the variable added last to be statistical significant because the last model is more superior compared to the previous one.

3) When I am talking about  first, second, third,..., last model I am talking about the order you see these on the anova table in R.

4) This question is better to be placed in statistics section.

In your question now,

```<code>     Df Deviance Resid. Df Resid. Dev Pr(>Chi)
NULL                   687     1681.2
site  2   16.543       685     1664.7   0.2884
</code>```

1) Given the table above the model containing "site" doesn't provide any significant improvement (compared to NULL model) at the confidence level you mentioned, which might mean that variable "site" is statistical insignificant at the given confidence level, which is close to your interpretation.

However, If you want to be 100% correct what you get from that table is only this: "Given the table above the model containing "site" doesn't provide any significant improvement (compared to NULL model) at the confidence level you mentioned". And I think this is the correct answer to the question.

*Perhaps if you rearrange the variables and add some other variable first and then "site" you might find "site" statistical significant, though I think it unlikely.(Comment 1)

*Also using a different model (i.e. logistic) might give you a different result. So always remember that the thing you are testing is if a model is statistically better compared to another one. For example, a variable might be a good predictor of the response but because the functional form of your model is incorrect you might infer that the variable is statistically insignificant, which is wrong.

This is the way you would interpret this result.

2) You should report the Deviance  16.543 , Degrees of Freedom DF=2and the p-value 0.2884

Body:
I am using a Likelihood Ratio Test (in R) to look for main effects in my model with three fixed factors (site, year, habitat) like this:

model1<-glm(tot.mass~hab, data=biom, family = Gamma(link = "log"))
anova(model1, test="Chisq")
model2<-glm(tot.mass~year, data=biom, family = Gamma(link = "log"))
anova(model2, test="Chisq")
model3<-glm(tot.mass~site, data=biom, family = Gamma(link = "log"))
anova(model3, test="Chisq")

I was told that by using "anova(model3, test="Chisq")" I will find whether (in this example) adding in the term "site" significantly improves the model. From what I understand, since my p value is >0.5, site doesn't have a significant effect on my model (e.g. isn't a main effect for this response variable). My output looks like this:

     Df Deviance Resid. Df Resid. Dev Pr(>Chi)
NULL                   687     1681.2
site  2   16.543       685     1664.7   0.2884

My questions are 1) am I interpreting this correctly and 2) how would I report these results? Would I report the Deviance and pvalue ("Pr(>Chi)")?

Thank you!

Body:
Some comments before answering this,

1) Always keep in mind that the order you test the terms in your model plays  significant role in their statistical significance. This happens because you sequentially compare models against each other (i.e. in your case you compared the NULL model (no predictors) against a model with "site" as the only predictor). If you add an extra variable then you comparing the model containing only "site" against a model containing "site" and "some other variable".

2) An easy way to remember that is by thinking of deviance as the "distance" between two models (chisq takes only positive values) so they further apart are two models the more likely is the variable added last to be statistical significant because the last model is more superior compared to the previous one.

3) When I am talking about  first, second, third,..., last model I am talking about the order you see these on the anova table in R.

4) This question is better to be placed in statistics section.

In your question now,

     Df Deviance Resid. Df Resid. Dev Pr(>Chi)
NULL                   687     1681.2
site  2   16.543       685     1664.7   0.2884

1) Given the table above the model containing "site" doesn't provide any significant improvement (compared to NULL model) at the confidence level you mentioned, which might mean that variable "site" is statistical insignificant at the given confidence level, which is close to your interpretation.

However, If you want to be 100% correct what you get from that table is only this: "Given the table above the model containing "site" doesn't provide any significant improvement (compared to NULL model) at the confidence level you mentioned". And I think this is the correct answer to the question.

*Perhaps if you rearrange the variables and add some other variable first and then "site" you might find "site" statistical significant, though I think it unlikely.(Comment 1)

*Also using a different model (i.e. logistic) might give you a different result. So always remember that the thing you are testing is if a model is statistically better compared to another one. For example, a variable might be a good predictor of the response but because the functional form of your model is incorrect you might infer that the variable is statistically insignificant, which is wrong.

This is the way you would interpret this result.

2) You should report the Deviance  16.543 , Degrees of Freedom DF=2and the p-value 0.2884


来源: stackexchange

问:
Spring MVC Rest App - Best Practice to Loading Properties
Have been assigned to re-assess a Spring 4 MVC Rest app where previous developers
where placing the loading of the configuration properties inside the following places:

WEB-INF/mvc-dispatcher-servlet.xml:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">

    <import resource="classpath:mydatabase.xml" />

    <context:component-scan base-package="com.myapp.rest, com.myapp.config" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <util:properties id="props" location="classpath:prop.properties" />
</beans>
</code>```

src/main/resources/mydatabase.xml:

```<code><bean id="propertyPlaceholder"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="true" />
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="location" value="file:/opt/database.properties">
</property>

<bean id="mydatabase" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName"><value>${db.driver}</value></property>
    <property name="url"><value>${db.url}</value></property>
    <property name="username"><value>${db.username}</value></property>
    <property name="password"><value>${db.password}</value></property>
    <property name="maxIdle" value="10" />
    <property name="maxActive" value="50" />
    <property name="maxWait" value="100" />
    <property name="defaultAutoCommit" value="false" />
    <property name="removeAbandoned" value="true" />
    <property name="removeAbandonedTimeout" value="1" />
    <property name="minIdle" value="0"></property>
    <property name="timeBetweenEvictionRunsMillis" value="1000"></property>
    <property name="minEvictableIdleTimeMillis" value="1000"></property>
</bean>
</code>```

src/main/resources/prop.properties:

```<code>banner = images/banner.png
</code>```

Inside the code, I've been seeing people use the follow way to insert the banner file location:

```<code>private @Value("#{props[banner]}") String banner;
</code>```

My objective is to add a new properties file:

```<code>src/main/resources/config.properties
</code>```

So, I can use the @Value annotation...

Question(s):

What's the BEST way to reorganize some of these config files?

Where would I declare this new config.properties file and what is the declaration?

答:
Put the property files in src/main/resources.

2.

```<code>@Configuration
@PropertySource("classpath:config.properties")
public class PropertiesWithJavaConfig {

   @Bean
   public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
      return new PropertySourcesPlaceholderConfigurer();
   }
}
</code>```

If you want to load multiple files, use PropertySources

PropertyPlaceholderConfigurer is deprecated in favor of PropertySourcesPlaceholderConfigurer for years now. I hope you'll ditch the XML and move to JavaConfig for, if not anything else, type safety.

ContentLicense: CC BY-SA 3.0

Body:
Have been assigned to re-assess a Spring 4 MVC Rest app where previous developers
where placing the loading of the configuration properties inside the following places:

WEB-INF/mvc-dispatcher-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">

    <import resource="classpath:mydatabase.xml" />

    <context:component-scan base-package="com.myapp.rest, com.myapp.config" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <util:properties id="props" location="classpath:prop.properties" />
</beans>

src/main/resources/mydatabase.xml:

<bean id="propertyPlaceholder"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="true" />
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="location" value="file:/opt/database.properties">
</property>

<bean id="mydatabase" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName"><value>${db.driver}</value></property>
    <property name="url"><value>${db.url}</value></property>
    <property name="username"><value>${db.username}</value></property>
    <property name="password"><value>${db.password}</value></property>
    <property name="maxIdle" value="10" />
    <property name="maxActive" value="50" />
    <property name="maxWait" value="100" />
    <property name="defaultAutoCommit" value="false" />
    <property name="removeAbandoned" value="true" />
    <property name="removeAbandonedTimeout" value="1" />
    <property name="minIdle" value="0"></property>
    <property name="timeBetweenEvictionRunsMillis" value="1000"></property>
    <property name="minEvictableIdleTimeMillis" value="1000"></property>
</bean>

src/main/resources/prop.properties:

banner = images/banner.png

Inside the code, I've been seeing people use the follow way to insert the banner file location:

private @Value("#{props[banner]}") String banner;

My objective is to add a new properties file:

src/main/resources/config.properties

So, I can use the @Value annotation...

Question(s):

What's the BEST way to reorganize some of these config files?

Where would I declare this new config.properties file and what is the declaration?

Body:
Put the property files in src/main/resources.

2.

@Configuration
@PropertySource("classpath:config.properties")
public class PropertiesWithJavaConfig {

   @Bean
   public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
      return new PropertySourcesPlaceholderConfigurer();
   }
}

If you want to load multiple files, use PropertySources

PropertyPlaceholderConfigurer is deprecated in favor of PropertySourcesPlaceholderConfigurer for years now. I hope you'll ditch the XML and move to JavaConfig for, if not anything else, type safety.


问:
list.appendChild(TOCEntry) shows type Error: its not a function
```<code>function createTOC(){

    var list = document.getElementsByTagName("ul");
    var headingText;
    var TOCEntry;
    var i;
    for( i=1; i<=10; i++){
        headingText = document.getElementById(i);
        TOCEntry = document.createElement("li");
        TOCEntry = "<a href=#" + i + ">" + headingText + "</a>";
        list.appendChild(TOCEntry);
    }
}
</code>```

list.appendChild(TOCEntry) shows type Error: its not a function.

答:
function createTOC(){

```<code>var list = document.getElementsByTagName("ul")[0];
var headingText;
var TOCEntry;

    var i;
for( i=1; i<=10; i++){
   headingText = document.getElementById(i).innerHTML;
   TOCEntry = document.createElement("li");
   TOCEntryData = "<a href=#" + i + ">" + headingText + "</a>";
   TOCEntry.innerHTML = TOCEntryData;
  list.appendChild(TOCEntry);

}
</code>```

}

Body:
function createTOC(){

    var list = document.getElementsByTagName("ul");
    var headingText;
    var TOCEntry;
    var i;
    for( i=1; i<=10; i++){
        headingText = document.getElementById(i);
        TOCEntry = document.createElement("li");
        TOCEntry = "" + headingText + "";
        list.appendChild(TOCEntry);
    }
}

list.appendChild(TOCEntry) shows type Error: its not a function.

Body:
function createTOC(){

var list = document.getElementsByTagName("ul")[0];
var headingText;
var TOCEntry;

    var i;
for( i=1; i<=10; i++){
   headingText = document.getElementById(i).innerHTML;
   TOCEntry = document.createElement("li");
   TOCEntryData = "<a href=#" + i + ">" + headingText + "</a>";
   TOCEntry.innerHTML = TOCEntryData;
  list.appendChild(TOCEntry);

}

}


问:
How to add time label into the message bubble?
I'm using JSQMessageController in my app and now I want to add time label inside of my bubbles.

I searched in my directories, but did not find image assets folder. But when I'm typing an image/asset name here:

I'm trying this one:

```<code>override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
    let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage
    return JSQMessagesTimestampFormatter.sharedFormatter().attributedTimestampForDate(message.date)
}
</code>```

but this is not what I want. I want to add this label into the message bubble.

Any suggestions, even written in Objective-C?

答: If you want to add a time label, you have to change the xib file of JSQMessagesCollectionViewCellOutgoing and also for the Incoming bubbles.</p>

Body:
I'm using JSQMessageController in my app and now I want to add time label inside of my bubbles.

I searched in my directories, but did not find image assets folder. But when I'm typing an image/asset name here:

I'm trying this one:

override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
    let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage
    return JSQMessagesTimestampFormatter.sharedFormatter().attributedTimestampForDate(message.date)
}

but this is not what I want. I want to add this label into the message bubble.

Any suggestions, even written in Objective-C?


问:
PHP htmlentities not working even with parameters
Of course this has been asked before and have searched for solutions, all which have not worked thus far.  I want to change out the TM symbol and the ampersand to their html equivelents by using htmlentities or htmlspecialchars:

```<code>$TEST = "Kold Locker™ & other stuff";
echo "ORGINIAL: " . $TEST . "<BR/>";

echo "HTML: " . htmlentities($TEST, ENT_COMPAT, 'UTF-8');
</code>```

This displays:

```<code>ORGINIAL: Kold Locker™ & other stuff
HTML:
</code>```

I have also tried it with htmlspecialchars and the second parameter changed with the same result.

What am I missing that others have claimed worked in other solutions?

UPDATE: I tried just displaying utf8_encode($TEST) and it displayed HTML: Kold LockerÂ™ & other stuff

答:
I had almost the same problem (in which somehow it showed the same text every time) and with a combination of different echo´s i got it. It seems that webbrowsers like firefox show the same text every time. That´s because when you echo the htmlentities-text, its being converted back into normal text while echoing. When I echo a script with the variable/text to be console.logged, it actually echo´s the htmlentities text (almost) correctly. Instead of replacing every special char with html-codings, it replaces ´em with some other coding i already saw before (I can´t remember the name). Htmlentities-ing it again, I get the same text echo´d again (remember it converts everything), but echoing it in console.log-version gives to me the expected result. Now, again, as a result:

1. Execute htmlentities two times!

2. Don´t (at least with firefox) echo the htmlentities as normal into the webpage. If you´d like to check if the value is actually correct, echo a script that logs it into console.

I hope this could help other guys with the same problem,

VicStudio

EDIT: 3. If you are using a $_POST formular, don´t forget to add accept-charset="UTF-8" (or some other charset) to the <form> tag.

EVEN MORE EDIT: Only do 2 times htmlentities if you wish to echo your result normal into the page. If you wish to directly send in f.e. a database, only do it once! -> what i said before is partually wrong. :(

Body:
Of course this has been asked before and have searched for solutions, all which have not worked thus far.  I want to change out the TM symbol and the ampersand to their html equivelents by using htmlentities or htmlspecialchars:

$TEST = "Kold Locker™ & other stuff";
echo "ORGINIAL: " . $TEST . "
";

echo "HTML: " . htmlentities($TEST, ENT_COMPAT, 'UTF-8');

This displays:

ORGINIAL: Kold Locker™ & other stuff
HTML:

I have also tried it with htmlspecialchars and the second parameter changed with the same result.

What am I missing that others have claimed worked in other solutions?

UPDATE: I tried just displaying utf8_encode($TEST) and it displayed HTML: Kold LockerÂ™ & other stuff


问:
Is it safe to protect SQL Database (.mdf) by checking the last modified date?
I want to protect the SQL Database (.mdf) file by checking if the last modified date of the database file matches my Application's record. So that if user edit any data from the database it can be identified. So is it safe to use this method? Or is there any better method?

Please don't suggest store .mdf file on different machine and access it by using LAN connection.

答:
The database file modified date does not change when a user performs an update or delete according to this link: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/b7db6744-cd7b-42b5-a84e-5e511a5e8e59/mdf-ldf-files-last-modified-date-not-increasing-as-expected?forum=sqldisasterrecovery

What are you concerned about? Are you concerned about a DBA making modifications or an application user making modifications? If you want to know what users are doing then could you create a table called dbAudit, which contains four fields i.e. ID (Primary Key), Username, datecreated and sqlquery.  You could log all of the sql queries run against the database by the application.

It may also be worth looking into Transparent Data Encryption: https://learn.microsoft.com/en-us/sql/relational-databases/security/encryption/transparent-data-encryption-tde


问:
How do I remove an item from the Intellij default changelist?
Somehow or other a file in the .idea folder has landed on the default changelist and every time I make a commit Intellij is asking me if if I want to include the file in the commit.

I can't figure out why Intellij insists on trying to version control this file or how I can change its mind.

答: Right click on the file in the version control window and select "Ignore...". Then select the relevant option (ignore file, directory or all files matching). </p>


问:
jQuery selecting the top li of a menu
Sorry for the noobish question.

I've got a menu similar to this:

```<code><div id="navigation">
  <ul>
    <li><a href="url">menu item</a></li>
    <li><a href="url">menu item</a>
      <ul>
        <li><a href="url">sub menu item</a></li>
        <li><a href="url">sub menu item</a>
          <ul>
            <li><a href="url">sub sub menu item</a></li>
            <li><a href="url">sub sub menu item</a></li>
            <li><a href="url">sub sub menu item</a></li>
          </ul>
        </li>
        <li><a href="url">sub menu item</a></li>
        <li><a href="url">sub menu item</a></li>
      </ul>
    </li>
    <li><a href="url">menu item</a></li>
    <li><a href="url">menu item</a></li>
  </ul>
</div>
</code>```

I'm trying to change the class for the selected page. I'm part way there with this:

```<code>$(function(){
     var path = location.pathname.substring(1);
     if ( path ){
  $('#navigation a[href$="' + path + '"]').parent().attr('class', 'selected');
  }
  });
</code>```

Which changes the class on the parent li. Cool. But what I really want to do is change the class on top level li. In other words if a "sub sub menu item" is selected goes all the way up the tree and changes the very first li that contains that link.

Would appreciate any help at all.

Thanks,

Andy.

答:
```<code>$('#navigation>ul>li:has(a[href$="' + path + '"])')
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery selecting the top li of a menu

Body:
Sorry for the noobish question.

I've got a menu similar to this:

menu item

menu item

sub menu item

sub menu item

sub sub menu item

sub sub menu item

sub sub menu item

sub menu item

sub menu item

menu item

menu item

I'm trying to change the class for the selected page. I'm part way there with this:

$(function(){
     var path = location.pathname.substring(1);
     if ( path ){
  $('#navigation a[href$="' + path + '"]').parent().attr('class', 'selected');
  }
  });

Which changes the class on the parent li. Cool. But what I really want to do is change the class on top level li. In other words if a "sub sub menu item" is selected goes all the way up the tree and changes the very first li that contains that link.

Would appreciate any help at all.

Thanks,

Andy.


问:
Result is not same which i expect
Now I want to make unfollow button if some one already followed then don't show follow button the browser should be show unfollow button instead of follow button like twitter. I just tested  (Unfollow button is appear) there but not working perfectly . it because when i online from (user1) and follow some one it work and follow button changed to unfollow but when i online from (user2) , want to follow same person which followed by (user1) .. From (user2) timeline it showing already followed(Button) please check the code </p>

```<code>if(isset($_POST['follow']))
        {
            $checkFollow=mysqli_query($con,"SELECT follower_id FROM follower WHERE user_id='$userid'");

            if(mysqli_num_rows($checkFollow)==0)
            {
                $follow=mysqli_query($con,"INSERT INTO follower(user_id,follower_id) VALUES ('$userid','$followerid')");
                echo "You Followed";
            }
            else
            {
                echo "Sorry! You already followed this profile";
            }
            $isFollowing=True;
        }

        $checkFollow=mysqli_query($con,"SELECT follower_id FROM follower WHERE user_id='$userid'");
        if(mysqli_num_rows($checkFollow))
        {
            $isFollowing=True;
        }

    }
</code>```

<p>HTML Code is </p>

```<code>  <form action="<?php echo $username;?>" method="post">
                       <?php
                             if($isFollowing)
                             {
                             echo "<input type='submit' value='Unfollow' name='unfollow' class='unfollow_button'>";
                             }
                             else
                             {
                                echo "<input type='submit' value='Follow' name='follow' class='unfollow_button'>";
                             }

                             ?>
                         </form>
</code>```

答:
I tried guessing your database structure based on your initial code and put up this answer:

```<code>if(isset($_POST['follow']))
{
    $id = $_GET['id'];
    $user_query = mysqli_query($con,"SELECT id FROM user_reg WHERE user_name='$id'");  // ($id) is actually $_GET variable

    if(mysqli_num_rows($user_query) > 0) { //make sure you have at least one result for that $id
        $row = mysqli_fetch_assoc($user_query); //fetch the database result
        $userid = $row['id']; //assign the value to the $userId variable
    } else { // die if no user found with that $id
        die("User id not found");
    }

    $followerid=$idd;  // ($idd) is current session (User Logged in)
    $checkFollow=mysqli_query($con,"SELECT follower_id FROM follower WHERE user_id='$userid'");

    if(mysqli_num_rows($checkFollow) == 0) //check if no rows resulted in the $checkFollow query
    {
        //VERY IMPORTANT!!! make sure the column names are correct. You were using follower_id and user_id in the $checkfollow query and the followerid and userid in the INSERT query
        $follow=mysqli_query($con,"INSERT INTO follower (user_id,follower_id) VALUES ('$userid','$followerid')");
        echo "Followed";
    }
    else
    {
        die("User already followed");
    }
}

?>

<form action="test.php?id=<?php echo $username;?>" method="post">
    <input type="submit" value="Follow" name="follow" class="follow_button">
</form>
</code>```

I hope this helps

Title: Result is not same which i expect

Body:
Now I want to make unfollow button if some one already followed then don't show follow button the browser should be show unfollow button instead of follow button like twitter. I just tested  (Unfollow button is appear) there but not working perfectly . it because when i online from (user1) and follow some one it work and follow button changed to unfollow but when i online from (user2) , want to follow same person which followed by (user1) .. From (user2) timeline it showing already followed(Button) please check the code

if(isset($_POST['follow']))
        {
            $checkFollow=mysqli_query($con,"SELECT follower_id FROM follower WHERE user_id='$userid'");

            if(mysqli_num_rows($checkFollow)==0)
            {
                $follow=mysqli_query($con,"INSERT INTO follower(user_id,follower_id) VALUES ('$userid','$followerid')");
                echo "You Followed";
            }
            else
            {
                echo "Sorry! You already followed this profile";
            }
            $isFollowing=True;
        }

        $checkFollow=mysqli_query($con,"SELECT follower_id FROM follower WHERE user_id='$userid'");
        if(mysqli_num_rows($checkFollow))
        {
            $isFollowing=True;
        }

    }

HTML Code is

  <form action="<?php echo $username;?>" method="post">
                       <?php
                             if($isFollowing)
                             {
                             echo "<input type='submit' value='Unfollow' name='unfollow' class='unfollow_button'>";
                             }
                             else
                             {
                                echo "<input type='submit' value='Follow' name='follow' class='unfollow_button'>";
                             }

                             ?>
                         </form>

Body:
I tried guessing your database structure based on your initial code and put up this answer:

if(isset($_POST['follow']))
{
    $id = $_GET['id'];
    $user_query = mysqli_query($con,"SELECT id FROM user_reg WHERE user_name='$id'");  // ($id) is actually $_GET variable

    if(mysqli_num_rows($user_query) > 0) { //make sure you have at least one result for that $id
        $row = mysqli_fetch_assoc($user_query); //fetch the database result
        $userid = $row['id']; //assign the value to the $userId variable
    } else { // die if no user found with that $id
        die("User id not found");
    }

    $followerid=$idd;  // ($idd) is current session (User Logged in)
    $checkFollow=mysqli_query($con,"SELECT follower_id FROM follower WHERE user_id='$userid'");

    if(mysqli_num_rows($checkFollow) == 0) //check if no rows resulted in the $checkFollow query
    {
        //VERY IMPORTANT!!! make sure the column names are correct. You were using follower_id and user_id in the $checkfollow query and the followerid and userid in the INSERT query
        $follow=mysqli_query($con,"INSERT INTO follower (user_id,follower_id) VALUES ('$userid','$followerid')");
        echo "Followed";
    }
    else
    {
        die("User already followed");
    }
}

?>

<form action="test.php?id=<?php echo $username;?>" method="post">
    <input type="submit" value="Follow" name="follow" class="follow_button">
</form>

I hope this helps


问:
Egit: Right click not showing GIT commands
I can't see the GIT commands when using right click on any files in a GIT repository.

I'm using Eclipse-Luna, A fresh install, afeter trying different versions of EGIT.

Thanks,
Elyahu

Some screen shots of the preferences:

答:
I can't see the GIT commands when using right click on any files in a GIT repository.

You must first share that local project in order to make it recognized as a Git repository.

See "How make Eclipse/EGit recognize existing repository information after update?",but don't forget, once shared, to close/reopen your project.

Then Git will be active on said project.


问:
Recursive thinking
I would like to ask if it is really necessary to track every recursive call when writing it, because I am having troubles if recursive call is inside a loop or inside multiple for loops. I just get lost when I am trying to understand what is happening.
Do you have some advice how to approach recursive problems and how to imagine it. I have already read a lot about it but I havent found a perfect answer yet. I understand for example how factorial works or fibonacci recursion. I get lost for example when I am trying to print all combinations from 1 to 5 length of 3 or all the solutions for n-queen problem</p>

答: I had a similar problem, try drawing a tree like structure that keeps track of each recursive call. Where a node is a function and every child node of that node is a recursive call made from that function. </p>

Title: Recursive thinking


问:
Add a button on the custom UITableViewHeaderFooterView
I am trying to add a button programmatically on the custom UITableViewHeaderFooterView class as follows, it does not appear.

I wonder what I am missing or doing wrong ?

```<code>- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {

        UIButton * clickBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.contentView.bounds.size.width-50, 0, 50, 50)];
        clickBtn.imageView.image = [UIImage imageNamed:@"carat-open.png"];
        [self.contentView addSubview:clickBtn];
    }
    return self;
}
</code>```

答:
To add custom view in Section Footer:

```<code> - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
   {
       return 20;
   }

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return  [self getViewForFooterForSection];
}

- (UIView*)getViewForFooterForSection
{
    UIView *sectionFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    sectionFooterView.backgroundColor = [UIColor redColor];
    return sectionFooterView;
}
</code>```

To add custom view for section footer from custom view file

CustomFooter

```<code>- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if(self)
    {
        self.frame = frame;
        self.backgroundColor = [UIColor blueColor];
    }

    return  self;
}
</code>```

View Controller

```<code>- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return  [self getViewForFooterForSection];
}

- (UIView*)getViewForFooterForSection
{
    CustomFooter *sectionFooterView = [[CustomFooter alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    return sectionFooterView;
}
</code>```

To add custom view in Table footer View

```<code>tbl.tableFooterView = [self getViewForTableView];

- (UIView*)getViewForTableView
{
    UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    tableFooterView.backgroundColor = [UIColor greenColor];
    return tableFooterView;
}
</code>```

Body:
I am trying to add a button programmatically on the custom UITableViewHeaderFooterView class as follows, it does not appear.

I wonder what I am missing or doing wrong ?

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {

        UIButton * clickBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.contentView.bounds.size.width-50, 0, 50, 50)];
        clickBtn.imageView.image = [UIImage imageNamed:@"carat-open.png"];
        [self.contentView addSubview:clickBtn];
    }
    return self;
}

Body:
To add custom view in Section Footer:

 - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
   {
       return 20;
   }

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return  [self getViewForFooterForSection];
}

- (UIView*)getViewForFooterForSection
{
    UIView *sectionFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    sectionFooterView.backgroundColor = [UIColor redColor];
    return sectionFooterView;
}

To add custom view for section footer from custom view file

CustomFooter

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if(self)
    {
        self.frame = frame;
        self.backgroundColor = [UIColor blueColor];
    }

    return  self;
}

View Controller

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return  [self getViewForFooterForSection];
}

- (UIView*)getViewForFooterForSection
{
    CustomFooter *sectionFooterView = [[CustomFooter alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    return sectionFooterView;
}

To add custom view in Table footer View

tbl.tableFooterView = [self getViewForTableView];

- (UIView*)getViewForTableView
{
    UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    tableFooterView.backgroundColor = [UIColor greenColor];
    return tableFooterView;
}


问:
inserting a row of data in sql server 2014 in javafx
i want to insert a row of data into my USERS table...
this is my code

   @FXML
    private void handleRegisterButtonAction() throws SQLException{
        String userName="'"+txt_username.getText()+"'";
        String password="'"+txt_password.getText()+"'";
        String mail="'"+txt_userMail.getText()+"'";
        //for example user id is 22
        int userId=22;

        String insertUser="INSERT INTO USERS(userId,userName,userPassword,userEmail)"
                + " VALUES("+userId+","+userName+","+password+","+mail+");";
        stmt.execute(insertUser);
    }
```

the code runs but table in the database doesn't change

this is because sql doesn't know to apply this query on which database!
But i dont know how to solve this

答:
First of all use PreparedStatements because if the userName or password have illegal characters you will have problems with your database .

Example character ' and boom the insert will not work.

```<code>PreparedStatement statement  = dataBaseConnection.prepareStatement( INSERT INTO '"+tableName+"' (userId,userName,userPassword,userEmail) VALUES(?,?,?,?)");

   //Add the data to the table
   statement.setInt(1,userId); //better to user autoincrement
   statement.setString(2, userName);
   statement.setString(3, password);
   statement.setString(4,userEmail);

   //Execute the update
   statement.executeUpdate();

   //commit in case you have turned autocommit to false
   databaseConnection.commit();
</code>```

Observe carefully the statement cause you can see on the table name i have ' and ' single column before and after the name of the table.

Body:
i want to insert a row of data into my USERS table...
this is my code

   @FXML
    private void handleRegisterButtonAction() throws SQLException{
        String userName="'"+txt_username.getText()+"'";
        String password="'"+txt_password.getText()+"'";
        String mail="'"+txt_userMail.getText()+"'";
        //for example user id is 22
        int userId=22;

        String insertUser="INSERT INTO USERS(userId,userName,userPassword,userEmail)"
                + " VALUES("+userId+","+userName+","+password+","+mail+");";
        stmt.execute(insertUser);
    }

the code runs but table in the database doesn't change

this is because sql doesn't know to apply this query on which database!
But i dont know how to solve this

Body:
First of all use PreparedStatements because if the userName or password have illegal characters you will have problems with your database .

Example character ' and boom the insert will not work.

PreparedStatement statement  = dataBaseConnection.prepareStatement( INSERT INTO '"+tableName+"' (userId,userName,userPassword,userEmail) VALUES(?,?,?,?)");

   //Add the data to the table
   statement.setInt(1,userId); //better to user autoincrement
   statement.setString(2, userName);
   statement.setString(3, password);
   statement.setString(4,userEmail);

   //Execute the update
   statement.executeUpdate();

   //commit in case you have turned autocommit to false
   databaseConnection.commit();

Observe carefully the statement cause you can see on the table name i have ' and ' single column before and after the name of the table.


问:
How to change page url and page content without reload the page?
I want to do that when I clicked on link (for example test.com/page?=test) my tab in the broswer open the link but without reload or refresh the page and change the content to the page content.

How can I start it? I know PHP, but its the first time that I try to do this.

答:
You can use HTML5 History API</p>

```<code>document.body.addEventListener('click', function(event){
    if(event.target.tagName === 'A'){
       event.preventDefault();
       history.replaceState({}, "Page Title", event.target.href);
    }
})
</code>```

Body:
You can use HTML5 History API

document.body.addEventListener('click', function(event){
    if(event.target.tagName === 'A'){
       event.preventDefault();
       history.replaceState({}, "Page Title", event.target.href);
    }
})


问:
API docs generation tool
I have a RESTful API written on RubyOnRails(restfulie gem).
What is the best way to generate api documentation from project sources?</p>

答: rake doc:app will turn your rdoc formatted comments for your methods into properly formatted html

Title: API docs generation tool


答:
Well, i doubt there is any easy way for this.
https://www.w3schools.com/xml/ajax_intro.asp
This might help.</p>

Title: How to change page url and page content without reload the page?

Body:
I want to do that when I clicked on link (for example test.com/page?=test) my tab in the broswer open the link but without reload or refresh the page and change the content to the page content.

How can I start it? I know PHP, but its the first time that I try to do this.


问:
Merging Objects in Javascript for Infinite Loading Ajax Plugin
I am trying to implement infinite scrolling. An ajax request returns an object that includes 10 threads. This ajax request is called every time the user scrolls to the bottom. What I am looking for is a way to merge these objects together.

One object looks like this:

```<code>Article: Object
    page: 1
    last_page: 20
    data: Array[10]
        0: Object
        1: Object
        2: Object
</code>```

Inside of the data array objects are arrays and objects again... So my problem here really is that we're speaking of a quite large object containing a variety of objects and arrays. Any idea how I could manage to do this?

Thank you! <3

答:
To add an array to another you could use the following code:

```<code>// `b` onto `a`:
a.push.apply( a, b );
</code>```

More information on the best way of merging/combining arrays may be found at this link.

In your case it would seem you keep one big pile of data (in the end). That would mean you would push the new article data on top of the pile. Since you know that this pile will be the biggest, it would give a good performance if you used this:

```<code>var articlePile = article.data;
// For every new article push the data onto the pile
articlePile.push.apply( articlePile, article2.data );
</code>```

Body:
I am trying to implement infinite scrolling. An ajax request returns an object that includes 10 threads. This ajax request is called every time the user scrolls to the bottom. What I am looking for is a way to merge these objects together.

One object looks like this:

Article: Object
    page: 1
    last_page: 20
    data: Array[10]
        0: Object
        1: Object
        2: Object

Inside of the data array objects are arrays and objects again... So my problem here really is that we're speaking of a quite large object containing a variety of objects and arrays. Any idea how I could manage to do this?

Thank you! <3

Body:
To add an array to another you could use the following code:

// `b` onto `a`:
a.push.apply( a, b );

More information on the best way of merging/combining arrays may be found at this link.

In your case it would seem you keep one big pile of data (in the end). That would mean you would push the new article data on top of the pile. Since you know that this pile will be the biggest, it would give a good performance if you used this:

var articlePile = article.data;
// For every new article push the data onto the pile
articlePile.push.apply( articlePile, article2.data );


问:
PHP Login with bCrypt Hashed Passwords

Why didn't the other posts help?

      Other posts didn't help because one was asking since none worked, despite there are a lot of similar questions.

More details

    The thing I want to do is to make a user log in using his password. But, the passwords are hashed using bCrypt in the database.

When I try to enter the real password, it doesn't work and says that the password is incorrect.

But, when I try to enter the hashed password. It says: "Successfully logged in".

How to make it log in using the real password not the hash?!

Code

Login.php

```<code><form method="post" action="loginsession.php">//login
    <p>Username <input type="text" name="uid" size="20"> </p>
    <p>Password <input type="password" name="pwd" size="20"> </p>
    <p><input type="submit" value="Login" name="login"></p>
</form>
</code>```

Loginsession.php

```<code>  <?php
   session_start();
   include ('dbhandler.php');
   $uid = $_POST['uid'];
   $pwd = $_POST['pwd'];

   $sql = "SELECT * FROM user WHERE uid='$uid' and pwd='$pwd' ";
   $result = mysqli_query($conn, $sql);
   $row = mysqli_fetch_assoc($result);
   $encrypted_pwd = password_hash($pwd, PASSWORD_DEFAULT);
   $hash = password_verify($pwd,$encrypted_pwd);
   $count = mysqli_num_rows($result);

   if ($count == 1) {
   echo("Logging in...");
   $_SESSION['id'] = $row['id'];
   $_SESSION['uid'] = $row['uid'];
   $_SESSION['pwd'] = $row['pwd'];
   echo("<h1 style='color:green;'>Successfully Logged In");

   }
    else {
           echo "Your Login Name or Password is invalid";
                die();
         }

    ?>
</code>```

答:
You should never use textual user input as a parameter of your query. This leaves you vulnerable to SQL injection. To prevent that, either use PDO or mysqli_* (but in this case use the appropriate functions to escape the parameters), which are both well documented.

You define and execute the query with passing the password as it was. You need to hash the password BEFORE you pass it to the query and pass $encrypted_pwd to the query.

I recommend the usage of limit 0, 1 at the end of your query in this case, as that will specify that you are interested only in the very first corresponding row, if exists, so the query will be stopped if the user is found and not continue searching for users. This will optimize your query.

Since you do not want to load any particular data related to the user, you only want to find out whether the user exists, you could further optimize your query by replacing select * with select 1, which will significantly reduce the size of data your RDBMS will have to send in response, as only a number will be returned and not the whole record, possibly with the user's biography.

Never ever store a user's password in the session. If for some reason $_SESSION will be outputted to the browser, that will be a serious vulnerability.

Title: PHP Login with bCrypt Hashed Passwords

Body:
Why didn't the other posts help?

      Other posts didn't help because one was asking since none worked, despite there are a lot of similar questions.

More details

    The thing I want to do is to make a user log in using his password. But, the passwords are hashed using bCrypt in the database.

When I try to enter the real password, it doesn't work and says that the password is incorrect.

But, when I try to enter the hashed password. It says: "Successfully logged in".

How to make it log in using the real password not the hash?!

Code

Login.php

<form method="post" action="loginsession.php">//login

Username <input type="text" name="uid" size="20">

Password <input type="password" name="pwd" size="20">

<input type="submit" value="Login" name="login">

</form>

Loginsession.php

  <?php
   session_start();
   include ('dbhandler.php');
   $uid = $_POST['uid'];
   $pwd = $_POST['pwd'];

   $sql = "SELECT * FROM user WHERE uid='$uid' and pwd='$pwd' ";
   $result = mysqli_query($conn, $sql);
   $row = mysqli_fetch_assoc($result);
   $encrypted_pwd = password_hash($pwd, PASSWORD_DEFAULT);
   $hash = password_verify($pwd,$encrypted_pwd);
   $count = mysqli_num_rows($result);

   if ($count == 1) {
   echo("Logging in...");
   $_SESSION['id'] = $row['id'];
   $_SESSION['uid'] = $row['uid'];
   $_SESSION['pwd'] = $row['pwd'];
   echo("
Successfully Logged In");

   }
    else {
           echo "Your Login Name or Password is invalid";
                die();
         }

    ?>


问:
Is there a way I can get an Enum value by its number in the sequence?
I have this enum:

```<code>public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}

public static partial class Extensions
{
    public static string Text(this PTI time)
    {
        switch (time)
        {
            case PTI.UserInput: return "User Input";
            case PTI.Ten: return "10 seconds";
            case PTI.Five: return "5 seconds";
            case PTI.Fifteen: return "15 seconds";
        }
        return "";
    }
}
</code>```

It's a simple case but I am using it as an example. In my code I need to pass the value of the enum to a function so I came up with this:

```<code>if (selectedIndex == 1) App.DB.UpdateSetting(Settings.Pti, PTI.UserInput);
if (selectedIndex == 2) App.DB.UpdateSetting(Settings.Pti, PTI.Five);
if (selectedIndex == 3) App.DB.UpdateSetting(Settings.Pti, PTI.Ten);
if (selectedIndex == 4) App.DB.UpdateSetting(Settings.Pti, PTI.Fifteen);
</code>```

It's not ideal.  Maybe a Case would help here but my point is that all I get is a number from 1 to 4 and from this I need to get the ENUM value.

Is there some way that I could get the ENUM value from the value of selectedIndex without an if or case construct?

Background - Here's where the value of selectedIndex comes from. It's from a picker in a Xamarin Form XAML

```<code><Picker x:Name="ptiPicker" IsVisible="false" SelectedIndexChanged="ptiOnPickerSelectedIndexChanged">
                                            <Picker.Items>
                                                <x:String>User input</x:String>
                                                <x:String>5 seconds</x:String>
                                                <x:String>10 seconds</x:String>
                                                <x:String>15 seconds</x:String>
                                            </Picker.Items>
                                        </Picker>
</code>```

Note:

If it was possible I would be happy to add some extension method to the enum if that would help get what I needed. Just not sure how to do that.

答:
I'm not familiar with Xamarin, but may be you should try to fill items with elements of your enum directly?
In WPF It goes simply like this. And if you want to convert enum elements to string and back, you can use ValueConverter
The example below is from WPF!

```<code>        <ComboBox
        // properties here
        SelectedItem="{Binding SelectedItem.EngineType, UpdateSourceTrigger=PropertyChanged}">
        <Model:EEngineType>Diesel</Model:EEngineType>
        <Model:EEngineType>Gas</Model:EEngineType>
        <Model:EEngineType>Biofuel</Model:EEngineType>
        <Model:EEngineType>Electrical</Model:EEngineType>
    </ComboBox>
</code>```

and EEngineType

```<code>public enum EEngineType
{
    Diesel,
    Gas,
    Biofuel,
    Electrical
}
</code>```

May be you should look around something like this, so you won't need to convert anything and just pass selectedItem to your method.

OR
in another way you can try to use something like this

```<code>readonly TCollection _PITCollection;
// ctor here
 _PITCollection = new TCollection<PIT> { PIT.UserInput, PIT.Five, PIT... };
</code>```

Where instead of TCollection you write any collection type you want.
And than you can use binding and call

```<code>App.DB.UpdateSetting(Settings.Pti, myPicker.SelectedItem);
</code>```

or you can use you previous style and call

```<code>App.DB.UpdateSetting(Settings.Pti, _PITCollection[selectedIndex]);
</code>```

Hope this will help you

Body:
I have this enum:

public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}

public static partial class Extensions
{
    public static string Text(this PTI time)
    {
        switch (time)
        {
            case PTI.UserInput: return "User Input";
            case PTI.Ten: return "10 seconds";
            case PTI.Five: return "5 seconds";
            case PTI.Fifteen: return "15 seconds";
        }
        return "";
    }
}

It's a simple case but I am using it as an example. In my code I need to pass the value of the enum to a function so I came up with this:

if (selectedIndex == 1) App.DB.UpdateSetting(Settings.Pti, PTI.UserInput);
if (selectedIndex == 2) App.DB.UpdateSetting(Settings.Pti, PTI.Five);
if (selectedIndex == 3) App.DB.UpdateSetting(Settings.Pti, PTI.Ten);
if (selectedIndex == 4) App.DB.UpdateSetting(Settings.Pti, PTI.Fifteen);

It's not ideal.  Maybe a Case would help here but my point is that all I get is a number from 1 to 4 and from this I need to get the ENUM value.

Is there some way that I could get the ENUM value from the value of selectedIndex without an if or case construct?

Background - Here's where the value of selectedIndex comes from. It's from a picker in a Xamarin Form XAML

<Picker x:Name="ptiPicker" IsVisible="false" SelectedIndexChanged="ptiOnPickerSelectedIndexChanged">
                                            <Picker.Items>
                                                <x:String>User input</x:String>
                                                <x:String>5 seconds</x:String>
                                                <x:String>10 seconds</x:String>
                                                <x:String>15 seconds</x:String>
                                            </Picker.Items>
                                        </Picker>

Note:

If it was possible I would be happy to add some extension method to the enum if that would help get what I needed. Just not sure how to do that.

Body:
I'm not familiar with Xamarin, but may be you should try to fill items with elements of your enum directly?
In WPF It goes simply like this. And if you want to convert enum elements to string and back, you can use ValueConverter
The example below is from WPF!

        <ComboBox
        // properties here
        SelectedItem="{Binding SelectedItem.EngineType, UpdateSourceTrigger=PropertyChanged}">
        <Model:EEngineType>Diesel</Model:EEngineType>
        <Model:EEngineType>Gas</Model:EEngineType>
        <Model:EEngineType>Biofuel</Model:EEngineType>
        <Model:EEngineType>Electrical</Model:EEngineType>
    </ComboBox>

and EEngineType

public enum EEngineType
{
    Diesel,
    Gas,
    Biofuel,
    Electrical
}

May be you should look around something like this, so you won't need to convert anything and just pass selectedItem to your method.

OR
in another way you can try to use something like this

readonly TCollection _PITCollection;
// ctor here
 _PITCollection = new TCollection<PIT> { PIT.UserInput, PIT.Five, PIT... };

Where instead of TCollection you write any collection type you want.
And than you can use binding and call

App.DB.UpdateSetting(Settings.Pti, myPicker.SelectedItem);

or you can use you previous style and call

App.DB.UpdateSetting(Settings.Pti, _PITCollection[selectedIndex]);

Hope this will help you


问:
My working fine PHP scripts aren't working anymore
I've been using this for a long time and now it stopped working. I just don't get why PHP changes on you. Someone help.

The problem is with these two lines:

```<code>$res = mysql_query("SELECT num FROM ywsite WHERE item='sitehits'", $db);
$num = mysql_result($res,0,"num");
</code>```

Here's the rest of the script:

```<code><?php
    $res = mysql_query("SELECT num FROM ywsite WHERE item='sitehits'", $db);
    $num = mysql_result($res,0,"num");
    $equals = $num + 1;
    mysql_query("UPDATE ywsite SET num='$equals' WHERE item='sitehits'");
?>
</code>```

答:
That seems like a rather complicated way to increment a number. Just do this instead:

```<code>UPDATE ywsite SET num = num + 1 WHERE item = 'sitehits'
</code>```

If it fails use mysql_error to see the error. The most likely cause of error is an incorrect table or column name.

Body:
I've been using this for a long time and now it stopped working. I just don't get why PHP changes on you. Someone help.

The problem is with these two lines:

$res = mysql_query("SELECT num FROM ywsite WHERE item='sitehits'", $db);
$num = mysql_result($res,0,"num");

Here's the rest of the script:

<?php
    $res = mysql_query("SELECT num FROM ywsite WHERE item='sitehits'", $db);
    $num = mysql_result($res,0,"num");
    $equals = $num + 1;
    mysql_query("UPDATE ywsite SET num='$equals' WHERE item='sitehits'");
?>

Body:
That seems like a rather complicated way to increment a number. Just do this instead:

UPDATE ywsite SET num = num + 1 WHERE item = 'sitehits'

If it fails use mysql_error to see the error. The most likely cause of error is an incorrect table or column name.


问:
This connection is not secure Mozilla
I have deployed an application build in laravel 5.3. On my login forms I see this warning : This connection is not secure. Logins entered here could be compromised.

This is my form :

```<code>  <form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
                            {{ csrf_field() }}

                            <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                                <label for="email" class="col-md-3 control-label"></label>

                                <div class="col-md-6">
                                    <input id="email" type="email" class="form-control" placeholder="Email" name="email" value="{{ old('email') }}" required autofocus>

                                    @if ($errors->has('email'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('email') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                                <label for="password" class="col-md-3 control-label"></label>

                                <div class="col-md-6">
                                    <input id="password" type="password" placeholder="Password" class="form-control" name="password" required>

                                    @if ($errors->has('password'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('password') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-6 col-md-offset-3">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="remember"> Remember Me
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-8 col-md-offset-3">
                                    <button type="submit" class="btn btn-primary">
                                        Login
                                    </button>

                                    <a class="btn btn-link" href="{{ url('/password/reset') }}">
                                        Forgot Your Password?
                                    </a>
                                </div>
                            </div>
</form>
</code>```

What I'm I missing or how can I fix this warning?

答:
This is a Firefox feature to warn visitors of websites that information they submit is not transferred securely.

The browser shows this warning for pages containing an <input type="password" /> which are delivered through HTTP instead of HTTPS.

To mitigate this, obtain a certificate for your site and install it, so your users are protected against eavesdropping.

Title: This connection is not secure Mozilla

Body:
I have deployed an application build in laravel 5.3. On my login forms I see this warning : This connection is not secure. Logins entered here could be compromised.

This is my form :

  <form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
                            {{ csrf_field() }}

has('email') ? ' has-error' : '' }}">

                                    <input id="email" type="email" class="form-control" placeholder="Email" name="email" value="{{ old('email') }}" required autofocus>

                                    @if ($errors->has('email'))

                                            {{ $errors->first('email') }}

                                    @endif

has('password') ? ' has-error' : '' }}">

                                    <input id="password" type="password" placeholder="Password" class="form-control" name="password" required>

                                    @if ($errors->has('password'))

                                            {{ $errors->first('password') }}

                                    @endif

                                            <input type="checkbox" name="remember"> Remember Me

                                    <button type="submit" class="btn btn-primary">
                                        Login
                                    </button>

                                        Forgot Your Password?

</form>

What I'm I missing or how can I fix this warning?


问:
how to include CC and BCC in email using Go
How to add CC and BCC on my email function in Go.

Here is my code

```<code>err := smtp.SendMail(
 "smtp.zoho.com",
 587,
 config.Email_id,
 config.Email_password,
 []string{email_to},
</code>```

答: That depends on which mail library you're using.  But the short version is:  Just add the Cc: and Bcc: headers as usual, same as you do for any other header, such as Subject: or To:.

Body:
How to add CC and BCC on my email function in Go.

Here is my code

err := smtp.SendMail(
 "smtp.zoho.com",
 587,
 config.Email_id,
 config.Email_password,
 []string{email_to},


问:
Swift: show name in ViewController
I have array with names in TableViewController and I have ViewController. If I click on cell in TableViewController I want to show name from array in ViewController navigation bar title. How to do it?

答:
Try this:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.deselectRow(at: indexPath, animated: true)
    navigationItem.title = myArray[indexPath.row]

}
</code>```

UPDATE:

If you are using storyboards, you can:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.deselectRow(at: indexPath, animated: true)
    let ame = myArray[indexPath.row]
    performSegue(withIdentifier: "ViewController", sender: selectedName)

}
</code>```

then, recover the selectedName in prepareForSegue and set the title for destinationVC there:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let selectedName = sender as? String,
    let viewController = segue.destination as? ViewController {
      detailViewController.navigationItem.title = selectedName
    }
  }
</code>```

Title: Swift: show name in ViewController

Body:
Try this:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.deselectRow(at: indexPath, animated: true)
    navigationItem.title = myArray[indexPath.row]

}

UPDATE:

If you are using storyboards, you can:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.deselectRow(at: indexPath, animated: true)
    let ame = myArray[indexPath.row]
    performSegue(withIdentifier: "ViewController", sender: selectedName)

}

then, recover the selectedName in prepareForSegue and set the title for destinationVC there:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let selectedName = sender as? String,
    let viewController = segue.destination as? ViewController {
      detailViewController.navigationItem.title = selectedName
    }
  }


问:
Indentation in VS Code
I'm a long time Emacs user. I've been trying out VS Code and I like it so far.

One thing I love about Emacs is that it always indents the code correctly when I press tab. I've looked but I can't seem to get that behavior in VS Code. I've tried looking in the settings and searching for an extension but have had no luck.

Can anyone help me on this please? Is there an extension I can/have to install to get it to do what I want?

I code mostly in PHP, HTML, CSS and Javascript.

答: What I do to indent everything properly is put {} brackets around everything or just remove and put the final } around the code, this seems to properly indent all of it, this said I mostly use c# I don't know if this works in other languages</p>

ContentLicense: CC BY-SA 4.0

Title: Indentation in VS Code


问:
REST - java.lang.IllegalStateException: getOutputStream() has already been called for this response
I'm getting the IllegalStateException when I'm trying to invoke GET method and I have no idea what's wrong. You can see the log below.

https://pastebin.com/EC6CABcU - log

```<code>package com.medicalsystem.controller;

import com.medicalsystem.model.Admission;
import com.medicalsystem.service.AdmissionService;
import com.medicalsystem.service.PatientService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class AdmissionController {

    private AdmissionService admissionService;
    private PatientService patientService;

    @RequestMapping(value = "/admission/{admissionId}", method = RequestMethod.GET)
    public ResponseEntity<Admission> getAdmission(@PathVariable("admissionId") int admissionId) {
        if (!admissionService.exists(admissionId)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Admission admission = admissionService.getById(admissionId);
        return new ResponseEntity<>(admission, HttpStatus.OK);
    }

    @RequestMapping(value = "/admission", method = RequestMethod.PUT)
    public ResponseEntity<String> updateAdmission(@RequestBody Admission admission) {
        admissionService.saveOrUpdate(admission);
        return new ResponseEntity<>("Admission successfully added", HttpStatus.OK);
    }
}
</code>```

答:
Seems to me the Admission is an Entity class.

```<code>import com.medicalsystem.model.Admission;

Admission admission = admissionService.getById(admissionId);
</code>```

It is not a good practice to return Entity directly from your web service.
Since entities can be live and managed, any calls to the getter methods specially mapped fields will result in loading the related entities. And since the bean to json serializer will call all getter methods recursively to construct the json string, it will end up in a cyclic call when entities refer to each other. Which you can see clearly in the log (StackOverflowError)

```<code>java.lang.StackOverflowError: null
at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_131]
at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_131]
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_131]
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_131]
at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_131]
at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_131]
at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_131]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_131]
at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_131]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_131]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_131]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_131]
</code>```

Create a Response Bean and define the fields to be returned and transfer the data that you need from the entity to the response bean.

Body:
I'm getting the IllegalStateException when I'm trying to invoke GET method and I have no idea what's wrong. You can see the log below.

https://pastebin.com/EC6CABcU - log

package com.medicalsystem.controller;

import com.medicalsystem.model.Admission;
import com.medicalsystem.service.AdmissionService;
import com.medicalsystem.service.PatientService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class AdmissionController {

    private AdmissionService admissionService;
    private PatientService patientService;

    @RequestMapping(value = "/admission/{admissionId}", method = RequestMethod.GET)
    public ResponseEntity<Admission> getAdmission(@PathVariable("admissionId") int admissionId) {
        if (!admissionService.exists(admissionId)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Admission admission = admissionService.getById(admissionId);
        return new ResponseEntity<>(admission, HttpStatus.OK);
    }

    @RequestMapping(value = "/admission", method = RequestMethod.PUT)
    public ResponseEntity<String> updateAdmission(@RequestBody Admission admission) {
        admissionService.saveOrUpdate(admission);
        return new ResponseEntity<>("Admission successfully added", HttpStatus.OK);
    }
}

Body:
Seems to me the Admission is an Entity class.

import com.medicalsystem.model.Admission;

Admission admission = admissionService.getById(admissionId);

It is not a good practice to return Entity directly from your web service.
Since entities can be live and managed, any calls to the getter methods specially mapped fields will result in loading the related entities. And since the bean to json serializer will call all getter methods recursively to construct the json string, it will end up in a cyclic call when entities refer to each other. Which you can see clearly in the log (StackOverflowError)

java.lang.StackOverflowError: null
at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_131]
at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_131]
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_131]
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_131]
at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_131]
at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_131]
at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_131]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_131]
at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_131]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_131]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_131]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_131]

Create a Response Bean and define the fields to be returned and transfer the data that you need from the entity to the response bean.


问:
Horizontally scrolling gallery - CSS only
Here's a website showing exactly what I need: kelseymcclellan.com

But it's not in CSS.

Here's a website that uses CSS only: olivercurtisphotography.co.uk

But there are several limitations:

- the images are embedded as img

- the width of the gallery must be specified in px

Instead, I need

- the images to be divs

- the gallery to adapt independently to the number of images

Here's how I embed images:

HTML:

```<code><div class="img ratio" style="background-image: url(image.jpg);"></div>
</code>```

CSS:

```<code>.img {
    background-size: cover;
}

.ratio:after {
    content: '';
    display: inline-block;
    padding-top: 66.6666667%;
}
</code>```

I found a lot of answers that achieve something similar to what I need, but none of them is close enough.

How do I create a series of divs scrolling horizontally?

答:
You can use flexbox. Check the following code:

#container{
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
}
.img{
  flex: 0 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
</div></code>```

Body:
Here's a website showing exactly what I need: kelseymcclellan.com

But it's not in CSS.

Here's a website that uses CSS only: olivercurtisphotography.co.uk

But there are several limitations:

- the images are embedded as img

- the width of the gallery must be specified in px

Instead, I need

- the images to be divs

- the gallery to adapt independently to the number of images

Here's how I embed images:

HTML:

CSS:

.img {
    background-size: cover;
}

.ratio:after {
    content: '';
    display: inline-block;
    padding-top: 66.6666667%;
}

I found a lot of answers that achieve something similar to what I need, but none of them is close enough.

How do I create a series of divs scrolling horizontally?

Body:
You can use flexbox. Check the following code:

#container{
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
}
.img{
  flex: 0 0 auto;
}

<div id="container">
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
  <div class="img">
    <img src="http://www.olivercurtisphotography.co.uk/projects/Volte-Face/Volte-face-01.jpg">
  </div>
</div>


问:
str error when replacing values in pandas dataframe
My code scrapes information from the website and puts it into a dataframe. But i'm not certain why the order of the code will give rise to the error: AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

Basically, the data scraped has over 20 rows and 10 columns.

Some values are within brackets ie: (2,333) and I want to change it to: -2333.

Some values have words n.a and I want to change it to numpy.nan

some values are - and I want to change them to numpy.nan too.

Doesn't Work

```<code>for final_df, engine_name in zip((df_foo, df_bar, df_far), (['engine_foo', 'engine_bar', 'engine_far'])):

# Replacing necessary items for final clean up

    final_df.replace('-', numpy.nan, inplace=True)
    final_df.replace('n.a.', numpy.nan, inplace=True)

    for i in final_df.columns:
        final_df[i] = final_df[i].str.replace(')', '')
        final_df[i] = final_df[i].str.replace(',', '')
        final_df[i] = final_df[i].str.replace('(', '-')

    # Appending Code to dataframe
    final_df = final_df.T
    final_df.insert(loc=0, column='Code', value=some_code)

# This produces the error - AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
</code>```

Works

```<code>for final_df, engine_name in zip((df_foo, df_bar, df_far), (['engine_foo', 'engine_bar', 'engine_far'])):

# Replacing necessary items for final clean up

    for i in final_df.columns:
        final_df[i] = final_df[i].str.replace(')', '')
        final_df[i] = final_df[i].str.replace(',', '')
        final_df[i] = final_df[i].str.replace('(', '-')

    final_df.replace('-', numpy.nan, inplace=True)
    final_df.replace('n.a.', numpy.nan, inplace=True)

    # Appending Code to dataframe
    final_df = final_df.T
    final_df.insert(loc=0, column='Code', value=some_code)

# This doesn't give me any errors and returns me what I want.
</code>```

Any thoughts on why this happens?

答:
For me works double replace - first with regex=True for replace substrings and second for all values:

```<code>np.random.seed(23)
df = pd.DataFrame(np.random.choice(['(2,333)','n.a.','-',2.34], size=(3,3)),
                  columns=list('ABC'))
print (df)
      A     B        C
0  2.34     -  (2,333)
1  n.a.     -  (2,333)
2  2.34  n.a.  (2,333)

df1 = df.replace(['\(','\)','\,'], ['-','',''], regex=True).replace(['-','n.a.'], np.nan)
print(df1)
      A   B      C
0  2.34 NaN  -2333
1   NaN NaN  -2333
2  2.34 NaN  -2333

df1 = df.replace(['-','n.a.'], np.nan).replace(['\(','\)','\,'], ['-','',''], regex=True)
print(df1)
      A   B      C
0  2.34 NaN  -2333
1   NaN NaN  -2333
2  2.34 NaN  -2333
</code>```

EDIT:

Your error means you want replace some non string column (e.g. all columns are NaNs in column B) by str.replace:

```<code>df1 = df.apply(lambda x: x.str.replace('\(','-').str.replace('\)','')
                           .str.replace(',','')).replace(['-','n.a.'], np.nan)
print(df1)
      A   B      C
0  2.34 NaN  -2333
1   NaN NaN  -2333
2  2.34 NaN  -2333
</code>```

```<code>df1 = df.replace(['-','n.a.'], np.nan)
       .apply(lambda x: x.str.replace('\(','-')
                         .str.replace('\)','')
                         .str.replace(',',''))
print(df1)
</code>```

AttributeError: ('Can only use .str accessor with string values, which use np.object_ dtype in pandas', 'occurred at index B')

dtype of column B is float64:

```<code>df1 = df.replace(['-','n.a.'], np.nan)
print(df1)
      A   B        C
0  2.34 NaN  (2,333)
1   NaN NaN  (2,333)
2  2.34 NaN  (2,333)

print (df1.dtypes)
A     object
B    float64
C     object
dtype: object
</code>```

Body:
My code scrapes information from the website and puts it into a dataframe. But i'm not certain why the order of the code will give rise to the error: AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

Basically, the data scraped has over 20 rows and 10 columns.

Some values are within brackets ie: (2,333) and I want to change it to: -2333.

Some values have words n.a and I want to change it to numpy.nan

some values are - and I want to change them to numpy.nan too.

Doesn't Work

for final_df, engine_name in zip((df_foo, df_bar, df_far), (['engine_foo', 'engine_bar', 'engine_far'])):

# Replacing necessary items for final clean up

    final_df.replace('-', numpy.nan, inplace=True)
    final_df.replace('n.a.', numpy.nan, inplace=True)

    for i in final_df.columns:
        final_df[i] = final_df[i].str.replace(')', '')
        final_df[i] = final_df[i].str.replace(',', '')
        final_df[i] = final_df[i].str.replace('(', '-')

    # Appending Code to dataframe
    final_df = final_df.T
    final_df.insert(loc=0, column='Code', value=some_code)

# This produces the error - AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

Works

for final_df, engine_name in zip((df_foo, df_bar, df_far), (['engine_foo', 'engine_bar', 'engine_far'])):

# Replacing necessary items for final clean up

    for i in final_df.columns:
        final_df[i] = final_df[i].str.replace(')', '')
        final_df[i] = final_df[i].str.replace(',', '')
        final_df[i] = final_df[i].str.replace('(', '-')

    final_df.replace('-', numpy.nan, inplace=True)
    final_df.replace('n.a.', numpy.nan, inplace=True)

    # Appending Code to dataframe
    final_df = final_df.T
    final_df.insert(loc=0, column='Code', value=some_code)

# This doesn't give me any errors and returns me what I want.

Any thoughts on why this happens?

Body:
For me works double replace - first with regex=True for replace substrings and second for all values:

np.random.seed(23)
df = pd.DataFrame(np.random.choice(['(2,333)','n.a.','-',2.34], size=(3,3)),
                  columns=list('ABC'))
print (df)
      A     B        C
0  2.34     -  (2,333)
1  n.a.     -  (2,333)
2  2.34  n.a.  (2,333)

df1 = df.replace(['\(','\)','\,'], ['-','',''], regex=True).replace(['-','n.a.'], np.nan)
print(df1)
      A   B      C
0  2.34 NaN  -2333
1   NaN NaN  -2333
2  2.34 NaN  -2333

df1 = df.replace(['-','n.a.'], np.nan).replace(['\(','\)','\,'], ['-','',''], regex=True)
print(df1)
      A   B      C
0  2.34 NaN  -2333
1   NaN NaN  -2333
2  2.34 NaN  -2333

EDIT:

Your error means you want replace some non string column (e.g. all columns are NaNs in column B) by str.replace:

df1 = df.apply(lambda x: x.str.replace('\(','-').str.replace('\)','')
                           .str.replace(',','')).replace(['-','n.a.'], np.nan)
print(df1)
      A   B      C
0  2.34 NaN  -2333
1   NaN NaN  -2333
2  2.34 NaN  -2333

df1 = df.replace(['-','n.a.'], np.nan)
       .apply(lambda x: x.str.replace('\(','-')
                         .str.replace('\)','')
                         .str.replace(',',''))
print(df1)

AttributeError: ('Can only use .str accessor with string values, which use np.object_ dtype in pandas', 'occurred at index B')

dtype of column B is float64:

df1 = df.replace(['-','n.a.'], np.nan)
print(df1)
      A   B        C
0  2.34 NaN  (2,333)
1   NaN NaN  (2,333)
2  2.34 NaN  (2,333)

print (df1.dtypes)
A     object
B    float64
C     object
dtype: object


问:
Axios Vue.js throwing Cors error on Heroku Laravel application
I've got a Laravel app that's hosted on Heroku, currently in  staging environment that's password protected. It's accessible via https:// but axios is making requests to http:// and causing a cors error... I've tried adding allow origin headers as middleware on the routes but that doesn't fix the error.

Is there a way to force axios to use https by default? I don't want to pass the full URL to the axios.get()

This doesn't happen on local so could it be something caused by Heroku?

答:
I think the issue is actually related to Heroku but I can't be certain.

The only thing that tells me this is that I moved to an EC2 instance via Laravel Forge and I don't have any problems.

Strangely I also had a couple of files that were being requested without www. And when viewing in browser it forced the css files to the naked domain. What's weird though is other css files loaded with www. And weren't redirected so I think it could also have been a permissions thing.

I solved the file issue by simply changing the file name and the redirect stopped so maybe an overzealous redirect. Either way it was annoying and I think I tried everything so hopefully that information helps somebody else in future.

Cheers


问:
Adding an ACL rule from one user to others in powershell
I'm trying to pull an access rules from one user and apply it to all others. When I run the following it doesn't give an error but it also doesn't add the rule. When I log out $access it is the rule that I want (the fourth one in the list for that user). When I log out $acl it is the acl object for each user in the group. I don't get an error saying the method AddAccessRule doesn't exist.

When I look at the users in Active Directory after running the script there is no change made to them.

Does anyone know what I did wrong here or a better way to accomplish this?

```<code>$users = Get-ADUser -SearchBase “OU=Users,OU=Corporate Office,DC=corp,DC=company DC=com”-filter * | Select-Object -ExpandProperty DistinguishedName
$access = (Get-Acl ‘CN=peron,OU=Users,OU=Corporate Office,DC=corp,DC=company,DC=com’).access[3]
    foreach ($user in $users){
        $acl = (Get-Acl $user)
       echo $acl
       $acl.AddAccessRule(($access))
    }
</code>```

答:
As has been pointed out in the comments, you're not using Set-ACL at any point.

Adding an access rule and then not setting the updated ACL on the target object is comparable to modifying a word document and then not saving the changes.

```<code>foreach ($user in $users){
    $acl = (Get-Acl $user)
    $acl.AddAccessRule(($access))
    Set-Acl -AclObject $acl $user.DistinguishedName
}
</code>```

Body:
I'm trying to pull an access rules from one user and apply it to all others. When I run the following it doesn't give an error but it also doesn't add the rule. When I log out $access it is the rule that I want (the fourth one in the list for that user). When I log out $acl it is the acl object for each user in the group. I don't get an error saying the method AddAccessRule doesn't exist.

When I look at the users in Active Directory after running the script there is no change made to them.

Does anyone know what I did wrong here or a better way to accomplish this?

$users = Get-ADUser -SearchBase “OU=Users,OU=Corporate Office,DC=corp,DC=company DC=com”-filter * | Select-Object -ExpandProperty DistinguishedName
$access = (Get-Acl ‘CN=peron,OU=Users,OU=Corporate Office,DC=corp,DC=company,DC=com’).access[3]
    foreach ($user in $users){
        $acl = (Get-Acl $user)
       echo $acl
       $acl.AddAccessRule(($access))
    }

Body:
As has been pointed out in the comments, you're not using Set-ACL at any point.

Adding an access rule and then not setting the updated ACL on the target object is comparable to modifying a word document and then not saving the changes.

foreach ($user in $users){
    $acl = (Get-Acl $user)
    $acl.AddAccessRule(($access))
    Set-Acl -AclObject $acl $user.DistinguishedName
}


问:
Notepad++ Edit syntax highlighting for PHP?
I'd like to edit the syntax highlighting for PHP in Notepad++:

To have variables starting with $_ in a different color than variables starting with only $

To have operators like {} () [] in different colors than operators like & =

Is it possible to change the highlighting to be this in-depth? How?

答:
This is Possible

In Notepad++, define a new language by clicking View > User-Defined Dialogue...

Give the language a name (e.g. myPHP). Set the ext (file extension abbreviation) to php. Define the color coding for the global variables and for the brackets, braces and parentheses, etc. Close the Dialoague.

That is all. The formatting for myPHP which conflicts with the formatting for PHP will override the formatting for PHP, i.e. if the file has a .php extension.

More information: Notepad++ Wiki


问:
Java: Rounding UP double value in iterative manner
Let's consider below code snippet

```<code>public static void main(String[] args) {
        DecimalFormat twoDForm = new DecimalFormat("#.00");
        double k=4.144456;
        System.out.println(twoDForm.format(k));
    }
</code>```

I was expecting output as 4.15 as if we consider iterative rounding, the answer should be 4.15, but I guess DecimalFormat checks only immediate next digit value while rounding.

Is there any way by which I can achieve iterative rounding output.

答:
The question calls for a unique rounding mode. This answer addresses the general issue of getting special rounding.

The BigDecimal(double) constructor and BigDecimal's toString() method are both exact.

```<code>BigDecimal bd = new BigDecimal(d);
String s = bd.toString();
</code>```

leaves s with an exact, unrounded, String representation of double d. You can then do any required string manipulation to get the value you want. In addition, you can use any of the BigDecimal rounding modes in rounding bd.

Body:
Let's consider below code snippet

public static void main(String[] args) {
        DecimalFormat twoDForm = new DecimalFormat("#.00");
        double k=4.144456;
        System.out.println(twoDForm.format(k));
    }

I was expecting output as 4.15 as if we consider iterative rounding, the answer should be 4.15, but I guess DecimalFormat checks only immediate next digit value while rounding.

Is there any way by which I can achieve iterative rounding output.

Body:
The question calls for a unique rounding mode. This answer addresses the general issue of getting special rounding.

The BigDecimal(double) constructor and BigDecimal's toString() method are both exact.

BigDecimal bd = new BigDecimal(d);
String s = bd.toString();

leaves s with an exact, unrounded, String representation of double d. You can then do any required string manipulation to get the value you want. In addition, you can use any of the BigDecimal rounding modes in rounding bd.


问:
Stop function after some time
I want to make a simple background which changes to the colors of the rainbow every 1400 ms, which I did like this. Here's the code:

```<code>function onload() {
        var color = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
        var body = document.getElementById('body');
        var i = 0;
        function rainbow() {
            if(i == color.length) {i = 0;};
            body.style.backgroundColor = color[i++];
            setTimeout(rainbow, 1400);
        };
        rainbow();
};

onload();
</code>```

But after running this function for 6049 ms, I want the background to change with intervals of 50ms instead of 1400 ms. How would I do that?

答:
Since the initial interval is 1400ms, and you want to change after 6049ms, that would mean the change to 50ms would happen between the 5th and 6th color change (0ms, 1400ms, 2800ms, 4200ms, 5600ms, 7000ms). This means we can use the i index to set the setTimeout interval with (i < 6 ? 1400 : 50).

function onload() {
  var color = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
  var body = document.getElementById('body');
  var i = 0;

  function rainbow() {
    document.body.style.backgroundColor = color[i++ % color.length];
    setTimeout(rainbow, (i < 6 ? 1400 : 50));
  };
  rainbow();
};

onload();```

Title: Stop function after some time

Body:
I want to make a simple background which changes to the colors of the rainbow every 1400 ms, which I did like this. Here's the code:

function onload() {
        var color = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
        var body = document.getElementById('body');
        var i = 0;
        function rainbow() {
            if(i == color.length) {i = 0;};
            body.style.backgroundColor = color[i++];
            setTimeout(rainbow, 1400);
        };
        rainbow();
};

onload();

But after running this function for 6049 ms, I want the background to change with intervals of 50ms instead of 1400 ms. How would I do that?


问:
Why can you call a method before it has been defined?
```<code>public class MainClass {

    public static void main(String[] args) {
        anotherTest();
        test();
    }
    public static void test() {
        System.out.println("Printed from the test method.");
    }
    public static void anotherTest() {
        System.out.println("Printed from the anotherTest method.");
    }
}
</code>```

I would like to know why you can call a method before it has been defined like the code above. The code above shows two methods at the bottom of the page but I am calling them in the main method before they have been loaded. If I were to do something similar in Python I would get an error.

答: That's because Python gets compiled on the run, while in java the compiler handles this problem (it search for the declarations in the whole code)</p>

Body:
public class MainClass {

    public static void main(String[] args) {
        anotherTest();
        test();
    }
    public static void test() {
        System.out.println("Printed from the test method.");
    }
    public static void anotherTest() {
        System.out.println("Printed from the anotherTest method.");
    }
}

I would like to know why you can call a method before it has been defined like the code above. The code above shows two methods at the bottom of the page but I am calling them in the main method before they have been loaded. If I were to do something similar in Python I would get an error.


问:
Command line option to download file in FileZilla
I am using FileZilla (GUI) to download files from an FTP server. Can any one tell me a command line argument to download file from FTP server to local file system?</p>

答:
FileZilla does support some basic command line options for the upload and download of files. Not all options are documented.
You can download a file with the option "-d sourcefile targetdir"

Example (download):

```<code>filezilla.exe -d ftp://user:pass@ftp.myserver.com/folder/* "c:\downloads\"  /overwrite /close
</code>```

Example (upload):

```<code>filezilla.exe -u "c:\temp\samplefile.exe" ftp://user:pass@ftp.myserver.com/folder /overwrite /close
</code>```

/close -- will close the GUI after the download/upload completes

/overwrite -- will overwrite the files in target without prompting the user

You can also connect to a site from the site manager e.g. --site="0/site1".

Below are reference sites with further examples including download links to FileZilla versions (2.32 / 3.1) that supported the feature.

FAQ Link

FileZilla Download link

Body:
FileZilla does support some basic command line options for the upload and download of files. Not all options are documented.
You can download a file with the option "-d sourcefile targetdir"

Example (download):

filezilla.exe -d ftp://user:pass@ftp.myserver.com/folder/* "c:\downloads\"  /overwrite /close

Example (upload):

filezilla.exe -u "c:\temp\samplefile.exe" ftp://user:pass@ftp.myserver.com/folder /overwrite /close

/close -- will close the GUI after the download/upload completes

/overwrite -- will overwrite the files in target without prompting the user

You can also connect to a site from the site manager e.g. --site="0/site1".

Below are reference sites with further examples including download links to FileZilla versions (2.32 / 3.1) that supported the feature.

FAQ Link

FileZilla Download link