问:
PHP header location function not working in form
I'm trying to make a registration form for my website. I'm using the code below. All the error handlers work fine since it's adding the users into my database. I've trid to add ob_start. I removed all white spaces using a plugin for sublime text. I tried to use javascript instead of php (top.window). I also tried to use full url instead of just directories. But when I click submit it doesnt redirect me to the address I put after Location. When I click the button it takes me to this php file but doesnt redirect me back to the registration page which is a seperate file(I know there are a lot of similar questions that have been asked but they dont seem to work for my situation).
Does anyone know how to fix that?

```<code>if (isset($_POST['submit'])){

include_once 'db.php';

$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

//error handlers
//Check for empty fields
if (empty($uid) || empty($pwd) || empty($email)) {

    header("Location : /login/register.php?signup=empty");
    exit();

} else{

    //Check if input characters are valid
    if (!preg_match("/^[a-zA-Z]*$/", $uid)) {

        header('Location: /login/register.php?signup=invalid');
        exit();

    } else {

        //Check if email is valid
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            header('Location : /login/register.php?signup=email');
            exit();
        } else {
            $sql = "SELECT * FROM users WHERE user_uid='$uid'";
            $result = mysqli_query($conn, $sql);
            $resultCheck = mysqli_num_rows($result);

            if ($resultCheck > 0) {
                header('Location : /login/register.php?signup=usertaken');
            exit();
            } else {
                //Hashing the password
                $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
                //Insert the user into the databse
                $sql = "INSERT INTO users (user_uid, user_pwd, user_email) VALUES ('$uid', '$hashedPwd', '$email');";
                mysqli_query($conn, $sql);
                header('Location : /login/register.php?signup=success');
                exit();
            }
        }

    }

}

} else {
    header('Location : /login/register.php');
    exit();
}
</code>```

Solved - Removing space after "location" answer by Nigel Ren

答:
Try to use absolute URI</p>

```<code>$host  = $_SERVER['HTTP_HOST'];
header("Location: ".$host."/login/register.php?signup=empty");
</code>```

Body:
I'm trying to make a registration form for my website. I'm using the code below. All the error handlers work fine since it's adding the users into my database. I've trid to add ob_start. I removed all white spaces using a plugin for sublime text. I tried to use javascript instead of php (top.window). I also tried to use full url instead of just directories. But when I click submit it doesnt redirect me to the address I put after Location. When I click the button it takes me to this php file but doesnt redirect me back to the registration page which is a seperate file(I know there are a lot of similar questions that have been asked but they dont seem to work for my situation).
Does anyone know how to fix that?

if (isset($_POST['submit'])){

include_once 'db.php';

$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

//error handlers
//Check for empty fields
if (empty($uid) || empty($pwd) || empty($email)) {

    header("Location : /login/register.php?signup=empty");
    exit();

} else{

    //Check if input characters are valid
    if (!preg_match("/^[a-zA-Z]*$/", $uid)) {

        header('Location: /login/register.php?signup=invalid');
        exit();

    } else {

        //Check if email is valid
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            header('Location : /login/register.php?signup=email');
            exit();
        } else {
            $sql = "SELECT * FROM users WHERE user_uid='$uid'";
            $result = mysqli_query($conn, $sql);
            $resultCheck = mysqli_num_rows($result);

            if ($resultCheck > 0) {
                header('Location : /login/register.php?signup=usertaken');
            exit();
            } else {
                //Hashing the password
                $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
                //Insert the user into the databse
                $sql = "INSERT INTO users (user_uid, user_pwd, user_email) VALUES ('$uid', '$hashedPwd', '$email');";
                mysqli_query($conn, $sql);
                header('Location : /login/register.php?signup=success');
                exit();
            }
        }

    }

}

} else {
    header('Location : /login/register.php');
    exit();
}

Solved - Removing space after "location" answer by Nigel Ren

Body:
Try to use absolute URI

$host  = $_SERVER['HTTP_HOST'];
header("Location: ".$host."/login/register.php?signup=empty");


来源: stackexchange

问:
Creating apps using the same code with visual studio
I am getting in to developing multi platform apps with xamarin but need to build one main project with lots of other similar apps using some of the same code and screens. Is there a way to share code between projects or add different targets like in Xcode?</p>

答:
1) If you want to share code between a few apps, you can add "Portable Class Library" to your project. That way allows you to write 100% compatible code across any project. Altho, that limits a number of frameworks that you can use. If you want to use more of them, you can add "Shared Project" to your project. That allows you to use more of platform specific code (for example Xamarin Components), but you will need to write code more consciously, because it may not work across all projects. You can read more about code sharing here

2) If you want to build app with different targets follow this instructions

ContentLicense: CC BY-SA 3.0


答:
Make sure you don't have a space after location and before the :...

```<code>header('Location : /login/register.php');
</code>```

should be

```<code>header('Location: /login/register.php');
</code>```

Title: PHP header location function not working in form

Body:
Make sure you don't have a space after location and before the :...

header('Location : /login/register.php');

should be

header('Location: /login/register.php');


问:
Multiple field foreign key in django
I have two models in django with definitions below.
CreativeStatus model :

```<code>class RtbdCreativeStatus(models.Model):
    creative_id = models.CharField(max_length=500, primary_key=True)
    advertiser_id = models.CharField(max_length=100, primary_key=True)
    exposure_level = models.CharField(max_length=125)
    modified_on = models.DateTimeField()
    modified_by = models.CharField(max_length=100)

class RtbdCreative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)
</code>```

(creative_id, advertiser_id ) combination is unique in my CreativeStatus table . I want that combination to be my foreign key for Creative table. I tried adding it but i get this error .

1)How do i achieve this join with two key combination as my foreign key .

2)What should be my query to fetch all the creatives with their status from CreativeStatus table .

UPDATE 1

on reading the answers below , i updated my model as mentioned below :

```<code>class RtbdCreative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus, to_field='advertiser_id', related_name='advertiser', db_column='advertiser_id', on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus, to_field='creative_id', related_name='creative', db_column='creative_id', on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)
</code>```

Now i am getting this error . I have combination of advertiser_id , craetive_id as unique . But django expects both to be unique. What can i do to make it work ?

答:
As mentioned in ERRROS, you need to add related_name as argument, when you want to add more than one foreign key for same Model.</p>

```<code>class Creative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus,
                                      related_name="Advertiser", on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus,
                                    related_name="Creative",
                                    on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(
        max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)
</code>```

Title: Multiple field foreign key in django

Body:
I have two models in django with definitions below.
CreativeStatus model :

class RtbdCreativeStatus(models.Model):
    creative_id = models.CharField(max_length=500, primary_key=True)
    advertiser_id = models.CharField(max_length=100, primary_key=True)
    exposure_level = models.CharField(max_length=125)
    modified_on = models.DateTimeField()
    modified_by = models.CharField(max_length=100)

class RtbdCreative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)

(creative_id, advertiser_id ) combination is unique in my CreativeStatus table . I want that combination to be my foreign key for Creative table. I tried adding it but i get this error .

1)How do i achieve this join with two key combination as my foreign key .

2)What should be my query to fetch all the creatives with their status from CreativeStatus table .

UPDATE 1

on reading the answers below , i updated my model as mentioned below :

class RtbdCreative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus, to_field='advertiser_id', related_name='advertiser', db_column='advertiser_id', on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus, to_field='creative_id', related_name='creative', db_column='creative_id', on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)

Now i am getting this error . I have combination of advertiser_id , craetive_id as unique . But django expects both to be unique. What can i do to make it work ?

Body:
As mentioned in ERRROS, you need to add related_name as argument, when you want to add more than one foreign key for same Model.

class Creative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus,
                                      related_name="Advertiser", on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus,
                                    related_name="Creative",
                                    on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(
        max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)


问:
Return parent workbook range of particular sheet
using vlookup function one workbook to another workbook, this code " & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) return the range from first sheet of the wb2, eventhough have set the rage (Rg) from third sheet of wb2 Set Rg = wb2.Sheets(3).Range("A3:Z10000") .. why the rage (Rg) not returning of the third sheet of wb2 and how to return the rage of specific sheet of wb2 ?

```<code>Sub Vlkuprangcall()
Dim strColumn As String
Dim Rg As Range
Dim wb2 As Workbook

Set wb2 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\IC Raphael\Janalakshmi\MIS\MIS.xlsx")
Set Rg = wb2.Sheets(3).Range("A3:Z10000")

Application.Workbooks(2).Activate
With ActiveSheet
    a = ActiveCell.Column
    lastrow = 100
    strColumn = Split(ActiveCell.Address, "$")(1)
    ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) & ",6,False)"
    ActiveCell.AutoFill Destination:=Range(ActiveCell, Range(strColumn & lastrow))

end Sub
</code>```

答:
You can use the Address with the 4th parameter being xlExternal, it will add the Worksheet object's name, and also the Workbook object's name.

So your FormulaR1C1 line should be:

```<code>ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Address(True, True, xlR1C1, xlExternal) & ",6,False)"
</code>```

Note: your should try to avoid using Activate, ActiveSheet, and ActiveCell, instead use fully qualified Range and Cells objects.

Body:
using vlookup function one workbook to another workbook, this code " & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) return the range from first sheet of the wb2, eventhough have set the rage (Rg) from third sheet of wb2 Set Rg = wb2.Sheets(3).Range("A3:Z10000") .. why the rage (Rg) not returning of the third sheet of wb2 and how to return the rage of specific sheet of wb2 ?

Sub Vlkuprangcall()
Dim strColumn As String
Dim Rg As Range
Dim wb2 As Workbook

Set wb2 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\IC Raphael\Janalakshmi\MIS\MIS.xlsx")
Set Rg = wb2.Sheets(3).Range("A3:Z10000")

Application.Workbooks(2).Activate
With ActiveSheet
    a = ActiveCell.Column
    lastrow = 100
    strColumn = Split(ActiveCell.Address, "$")(1)
    ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) & ",6,False)"
    ActiveCell.AutoFill Destination:=Range(ActiveCell, Range(strColumn & lastrow))

end Sub

Body:
You can use the Address with the 4th parameter being xlExternal, it will add the Worksheet object's name, and also the Workbook object's name.

So your FormulaR1C1 line should be:

ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Address(True, True, xlR1C1, xlExternal) & ",6,False)"

Note: your should try to avoid using Activate, ActiveSheet, and ActiveCell, instead use fully qualified Range and Cells objects.


问:
Connection String in Azure while using Spring Boot
I can see that we can define a secure connection string form portal, and than can access those variables in our application.I found many examples to do it in ASP.NET, like defining the keys in web.config. But i can not find any example focusing on accessing these connection strings defined via portal from Spring Boot app.
Any help in that direction would be useful</p>

答:
If Azure exposes these secure strings as environment variables, you can name them to override application properties using the following format:

Property name my.secret.password can be overriden with environment variable MY_SECRET_PASSWORD.

You can also use them directly in your application.properties

```<code>my.secret.password=${SUPER_SECRET_ENV_VARIABLE}
</code>```

Body:
If Azure exposes these secure strings as environment variables, you can name them to override application properties using the following format:

Property name my.secret.password can be overriden with environment variable MY_SECRET_PASSWORD.

You can also use them directly in your application.properties

my.secret.password=${SUPER_SECRET_ENV_VARIABLE}


问:
Spring not autowiring using annotation a bean declared on the XML
I'm trying to inject a bean that was defined on a XML into an annotated,  It is only annotated and not declared on XML, I think that is just something that I'm missing here is my *context.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
...
<bean id="userBusiness" class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
    <property name="jndiName" value="java:global/app-common/app-common-core/UserBusinessImpl" />
    <property name="businessInterface" value="com.app.common.business.UserBusiness" />
</bean>
...
<context:annotation-config/>
<context:component-scan base-package="com.app.common.jsf" />
</beans>
</code>```

Here's the component:

```<code>@Component
public class AppAuthorization {

    @Autowired
    private UserBusiness userBusiness;

    @Autowired
    private AppLogin sabiusLogin;
...

@Local
public interface UserBusiness {
    User listUserByFilter(User user) throws UserBusinessException;
...

@Stateless
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
@Interceptors({SpringBeanAutowiringInterceptor.class})
public class UserBusinessImpl implements UserBusiness {

    @Autowired
    private ProgramasUsuariosDao programasUsuariosDao;
...
</code>```

When I try to access the AppAuthorization Spring says that:

```<code>Could not autowire field: private com.app.common.business.UserBusiness com.app.common.jsf.AppAuthorization.userBusiness"
</code>```

Seems that the annotated bean can't see the declared one, but search and seems that I only needed to add the annotation-config to the XML, is this right? Hope some can help me.

EDIT

I think that this is the most important part of the stack trace:

```<code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.app.common.business.UserBusiness] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:997)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:867)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:779)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:503)
    ... 201 more
</code>```

Following the steps on the context creation I see no bean registered tha can be seen by annotations just when springs creates the context based on the xml is that I can see all the beans that wre created.

EDIT 2

This is the beanRefContext.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="contexts" class="com.app.common.spring.ClassPathXmlApplicationContext" />
</beans>
</code>```

This is the class that loads the XML context files:

```<code>public class ClassPathXmlApplicationContext extends org.springframework.context.support.ClassPathXmlApplicationContext {

    public ClassPathXmlApplicationContext() {
        super((System.getProperty("module.context.file").split(";")));
    }

}
</code>```

As I said, the annotated beans cannot see the XML ones so, spring cannot autowire them.

EDIT 3

I don't have a @Configuration bean (I'm not using AnnotationConfigApplicationContext), all the config is in the XML and if I try to create one the server doesn't start, it's a legacy system with spring 3.2 and EJB 3.0 and I can't change this aspect now.

Thanks in advance!

答:
I think you missed to specify @Component annotation for the  UserBusiness class

EDIT:

Can you make the component-scan config to com.app.common instead of com.app.common.jsf

Body:
I'm trying to inject a bean that was defined on a XML into an annotated,  It is only annotated and not declared on XML, I think that is just something that I'm missing here is my *context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
...
<bean id="userBusiness" class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
    <property name="jndiName" value="java:global/app-common/app-common-core/UserBusinessImpl" />
    <property name="businessInterface" value="com.app.common.business.UserBusiness" />
</bean>
...
<context:annotation-config/>
<context:component-scan base-package="com.app.common.jsf" />
</beans>

Here's the component:

@Component
public class AppAuthorization {

    @Autowired
    private UserBusiness userBusiness;

    @Autowired
    private AppLogin sabiusLogin;
...

@Local
public interface UserBusiness {
    User listUserByFilter(User user) throws UserBusinessException;
...

@Stateless
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
@Interceptors({SpringBeanAutowiringInterceptor.class})
public class UserBusinessImpl implements UserBusiness {

    @Autowired
    private ProgramasUsuariosDao programasUsuariosDao;
...

When I try to access the AppAuthorization Spring says that:

Could not autowire field: private com.app.common.business.UserBusiness com.app.common.jsf.AppAuthorization.userBusiness"

Seems that the annotated bean can't see the declared one, but search and seems that I only needed to add the annotation-config to the XML, is this right? Hope some can help me.

EDIT

I think that this is the most important part of the stack trace:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.app.common.business.UserBusiness] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:997)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:867)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:779)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:503)
    ... 201 more

Following the steps on the context creation I see no bean registered tha can be seen by annotations just when springs creates the context based on the xml is that I can see all the beans that wre created.

EDIT 2

This is the beanRefContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="contexts" class="com.app.common.spring.ClassPathXmlApplicationContext" />
</beans>

This is the class that loads the XML context files:

public class ClassPathXmlApplicationContext extends org.springframework.context.support.ClassPathXmlApplicationContext {

    public ClassPathXmlApplicationContext() {
        super((System.getProperty("module.context.file").split(";")));
    }

}

As I said, the annotated beans cannot see the XML ones so, spring cannot autowire them.

EDIT 3

I don't have a @Configuration bean (I'm not using AnnotationConfigApplicationContext), all the config is in the XML and if I try to create one the server doesn't start, it's a legacy system with spring 3.2 and EJB 3.0 and I can't change this aspect now.

Thanks in advance!


问:
Changing a element text based on xhttp.readyState on javascript/jquery
I have a button that user clicks and download from a PHP page, since the processing is a little bit long i want to display a text that shows the user that their request is processing, i found the onreadystatechange Property can be accessed so maybe I can use it for the task.

```<code>ready StateHolds the status of the XMLHttpRequest.
     0: request not initialized
     1: server connection established
     2: request received
     3: processing request
     4: request finished and response is ready
</code>```

My code is below, i able the get the readyState == 4 but cannot get the readyState == 3, any advice would be great!

```<code><button type="submit" class="btn btn-primary" id="weekDL">
  <i class="fa fa-download"></i>
  Download
</button>
<p id="please">Generating report, please wait..</p>
</code>```

$('#weekDL').on('click',function(){
  $(this).hide();
  $('#please').show();
  var data = $("#week option:selected").text();

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if(this.readyState == 3) {
      $('#please').text('Request recieved..');
    } else if (this.readyState == 4 && this.status == 200) {
      window.location = "PHPexcel/download.php?week=" + data;
      this.responseText;
      $('#please').hide();
      $('#weekDL').show();
    }
  };
  xhttp.open("GET", "PHPexcel/download.php?week=" + data, true);
  xhttp.send();
});
});
```

答:
Your code is working fine. The issue is because state 3 is only around for a couple of milliseconds before state 4 occurs (depending on the size of the response), therefore your UI update is almost imperceptible.

You can verify this by placing console.log('state: ' + this.readyState); within the onchangereadystate handler. You will then see the output of all 4 states in the console.

Working example

This is of course assuming that the AJAX request is returning a valid response. If there is an error in the request then you would only see states 1 and 4. However in that case the problem is with the logic in the request, not your JS.

Body:
I have a button that user clicks and download from a PHP page, since the processing is a little bit long i want to display a text that shows the user that their request is processing, i found the onreadystatechange Property can be accessed so maybe I can use it for the task.

ready StateHolds the status of the XMLHttpRequest.
     0: request not initialized
     1: server connection established
     2: request received
     3: processing request
     4: request finished and response is ready

My code is below, i able the get the readyState == 4 but cannot get the readyState == 3, any advice would be great!

<button type="submit" class="btn btn-primary" id="weekDL">

  Download
</button>

Generating report, please wait..

$('#weekDL').on('click',function(){
  $(this).hide();
  $('#please').show();
  var data = $("#week option:selected").text();

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if(this.readyState == 3) {
      $('#please').text('Request recieved..');
    } else if (this.readyState == 4 && this.status == 200) {
      window.location = "PHPexcel/download.php?week=" + data;
      this.responseText;
      $('#please').hide();
      $('#weekDL').show();
    }
  };
  xhttp.open("GET", "PHPexcel/download.php?week=" + data, true);
  xhttp.send();
});
});


答:
I think this is an easy way to understand.
Try:

```<code>sed 's/1/0/1' file</code>```

output:

```1 chrX_73833098_73834098
1 chrX_73889652_73890652
1 chrX_91194501_91195501
1 chrX_92000157_92001157
1 chrX_92106500_92107500
```

I want to say that the 's/partten/partten/g', the last 'g' mean the place in a line.

'1' mean the first matched, 'g' means all, also you can use '2g' which means from second to last.

Have a try.

Title: bash substitute first character in every line

Body:
My file looks like this:

  1 chrX_73833098_73834098
  1 chrX_73889652_73890652
  1 chrX_91194501_91195501
  1 chrX_92000157_92001157
  1 chrX_92106500_92107500

I want to replace first character "1" into 0. Wanted output is :

  0 chrX_73833098_73834098
  0 chrX_73889652_73890652
  0 chrX_91194501_91195501
  0 chrX_92000157_92001157
  0 chrX_92106500_92107500

Trying to do it with this:

sed 's/^./0/g' file

But the output is:

0     1 chrX_73833098_73834098
0     1 chrX_73889652_73890652
0     1 chrX_91194501_91195501
0     1 chrX_92000157_92001157
0     1 chrX_92106500_92107500

I believe there is easy way to fix it, but I don't know it.

Body:
I think this is an easy way to understand.
Try:

sed 's/1/0/1' file

output:

1 chrX_73833098_73834098
1 chrX_73889652_73890652
1 chrX_91194501_91195501
1 chrX_92000157_92001157
1 chrX_92106500_92107500

I want to say that the 's/partten/partten/g', the last 'g' mean the place in a line.

'1' mean the first matched, 'g' means all, also you can use '2g' which means from second to last.

Have a try.


问:
How to extract all properties (Paper Size, Format, Producer) of a PDF using java program
I am able to extract PDF properties using java code as below:
But i am confused how to get [Format like "PDF1.3" and page Size like"A4, Portrait (210 × 297 mm)"] properties using java code.

```<code>System.out.println(file.getName());
PdfReader reader = new PdfReader(file.toString());
HashMap<String, String> info = reader.getInfo();
char info1=reader.getPdfVersion();
byte[] b1 = reader.getMetadata();
System.out.println(info);
System.out.println(info1);
</code>```

I have tried PDFbox API also, but i cant find the method for the same,
Is it possible to fetch the following properties using java (i am using ubuntu)

ScreenShot of what i wanted to extract:

答:
You can get document information using PDDocument class in PDFBox api. PDDocumentInformation is used to retrieve author, version, created date, updated date, etc features.

```<code>PDDocument doc = PDDocument.load(new File(filePath));
PDDocumentInformation info = doc.getDocumentInformation();
String author = info.getAuthor();
int pages = doc.getNumberOfPages();
// String creator  = info.getCreator();
Calendar calendar = info.getCreationDate();
System.out.println("Author : " + author);
System.out.println("Created : " + new SimpleDateFormat("dd-MM-yyyy hh:mm:ss aa").format(calendar.getTimeInMillis()));
System.out.println("Total Pages : " + pages);
if(pages > 0) {
    float width = doc.getPage(0).getMediaBox().getWidth();
    float height = doc.getPage(0).getMediaBox().getHeight();
    System.out.println("Page 0 size : " + width + " * " + height);
} else {
    System.err.println("No pages.");
}
</code>```

Edit

Here is link to Get Page Format.

Here is link to Get Page information and Author.

Hope it'll help.

Body:
I am able to extract PDF properties using java code as below:
But i am confused how to get [Format like "PDF1.3" and page Size like"A4, Portrait (210 × 297 mm)"] properties using java code.

System.out.println(file.getName());
PdfReader reader = new PdfReader(file.toString());
HashMap<String, String> info = reader.getInfo();
char info1=reader.getPdfVersion();
byte[] b1 = reader.getMetadata();
System.out.println(info);
System.out.println(info1);

I have tried PDFbox API also, but i cant find the method for the same,
Is it possible to fetch the following properties using java (i am using ubuntu)

ScreenShot of what i wanted to extract:

Body:
You can get document information using PDDocument class in PDFBox api. PDDocumentInformation is used to retrieve author, version, created date, updated date, etc features.

PDDocument doc = PDDocument.load(new File(filePath));
PDDocumentInformation info = doc.getDocumentInformation();
String author = info.getAuthor();
int pages = doc.getNumberOfPages();
// String creator  = info.getCreator();
Calendar calendar = info.getCreationDate();
System.out.println("Author : " + author);
System.out.println("Created : " + new SimpleDateFormat("dd-MM-yyyy hh:mm:ss aa").format(calendar.getTimeInMillis()));
System.out.println("Total Pages : " + pages);
if(pages > 0) {
    float width = doc.getPage(0).getMediaBox().getWidth();
    float height = doc.getPage(0).getMediaBox().getHeight();
    System.out.println("Page 0 size : " + width + " * " + height);
} else {
    System.err.println("No pages.");
}

Edit

Here is link to Get Page Format.

Here is link to Get Page information and Author.

Hope it'll help.


问:
Google OAuth on MVC5 ExternalLoginCallback?error=access_denied
I have set up my Google OAuth

And I have added the code into Startup.Auth.cs

```<code> app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
    {
        // LRC
        ClientId = "xxxxxxxxx",
        ClientSecret = "xxxxx"
        //CallbackPath = new PathString("/signin-google")
    });
</code>```

But after I chose a google account to log in, it redirected me to the login page again,

I checked the network via Chrome and found that the access was denied.

http://www.liferunningclub.com.au/Account/ExternalLoginCallback?error=access_denied

I cannot figure it out.

Update
Now I did something else:

I added an annotation ([RequireHttps]) on the Account Controller

I enabled the SSL for my project.

I updated the url and re-direct url in Google Console to https

Tried to log in with Google, after I selected my Google account, it returned the same access_denied.

It would be better if the response from Google could give more detailed information.

答: I had this problem as well. After I enabled the Google+ API the problem is not solved yet. Turns out I haven't set the 'Authorized JavaScript origins' in my google API console. So I set the authorized javascript origins, and the problem solved.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have set up my Google OAuth

And I have added the code into Startup.Auth.cs

 app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
    {
        // LRC
        ClientId = "xxxxxxxxx",
        ClientSecret = "xxxxx"
        //CallbackPath = new PathString("/signin-google")
    });

But after I chose a google account to log in, it redirected me to the login page again,

I checked the network via Chrome and found that the access was denied.

http://www.liferunningclub.com.au/Account/ExternalLoginCallback?error=access_denied

I cannot figure it out.

Update
Now I did something else:

I added an annotation ([RequireHttps]) on the Account Controller

I enabled the SSL for my project.

I updated the url and re-direct url in Google Console to https

Tried to log in with Google, after I selected my Google account, it returned the same access_denied.

It would be better if the response from Google could give more detailed information.


问:
The left parenthesis '(' found at 'foo.cpp' was not matched correctly
Location of the error is indicated in a comment below. Please help fix this.</p>

```<code>#include<iostream.h>
#include<string.h>
#include<stdlib.h>
class String
{
private:
    enum{sz=80};
    char str[sz];
public:
    String()
    {
        strcpy(str,"");
    }

    String (char s[])
    {
        strcpy(str,s);
    }

    void display() const
    {
        cout<<str;
    }
    String operator +(String ss) const
    {
        String temp;
        if(strlen(str) + (strlen(ss.str) < sz)
        {
            strcpy(temp.str,str);
            strcat(temp.str , ss.str);
        } // Error is reported here!
        else
        {
            cout<<"\nstring overflow";
            exit(1);
        }
        return temp;
    }

};
int main()
{
    String s1="\nMerry christmas";
    String s2="happy new year";
    String s3;

    s1.display();
    s2.display();
    s3.display();

    s3=s1+s2;
    s3.display();
    cout<<endl;
    return 0;
}
</code>```

答:
You are missing a right parenthesis at the end of this line:</p>

```<code>if(strlen(str) + (strlen(ss.str) < sz)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Location of the error is indicated in a comment below. Please help fix this.

#include<iostream.h>
#include<string.h>
#include<stdlib.h>
class String
{
private:
    enum{sz=80};
    char str[sz];
public:
    String()
    {
        strcpy(str,"");
    }

    String (char s[])
    {
        strcpy(str,s);
    }

    void display() const
    {
        cout<<str;
    }
    String operator +(String ss) const
    {
        String temp;
        if(strlen(str) + (strlen(ss.str) < sz)
        {
            strcpy(temp.str,str);
            strcat(temp.str , ss.str);
        } // Error is reported here!
        else
        {
            cout<<"\nstring overflow";
            exit(1);
        }
        return temp;
    }

};
int main()
{
    String s1="\nMerry christmas";
    String s2="happy new year";
    String s3;

    s1.display();
    s2.display();
    s3.display();

    s3=s1+s2;
    s3.display();
    cout<<endl;
    return 0;
}

Body:
You are missing a right parenthesis at the end of this line:

if(strlen(str) + (strlen(ss.str) < sz)


问:
Values in my dataframe are not the same as ones in my database table(R and MySQL))
I am getting tweet_id from a table in my database and storing them in a dataframe in r. The problem is that the tweet_id values are not being added correctly in dataframe.

snapshot of my table:

snapshot of my dataframe in rstudio:

As you can see there is no tweet_id = '882100387989291008'(3rd value in my dataframe) in my database table

my Rscript file:

```<code>#connecting with db
#myDB = dbConnect(MySQL(), user = "root", password = "F33mtHaDD", dbname = "dashboard", host= "127.0.0.1", port="8889")

myDB =dbConnect(MySQL(), user = "root", password ="F33mtHaDD", dbname = "dashboard")

options(scipen=10)
options()$scipen

#running a query and retriving data and saving it in a object
rs = dbSendQuery(myDB, "SELECT tweet_id, sentiment, text FROM dashboard.sen_tweets_twitter WHERE text <> '';")

#getting the result. The function fetch() saves the result in a dataframe
datafetd = fetch(rs, n=-1)

#removing extra whitespaces
#new = stripWhitespace(datafetd$text)
#dataafterclean =data.frame(new)

#converts into one single string
review_text = paste(datafetd$text)
review_id = paste(datafetd$tweet_id)

print(review_id)

rm(tm_tdm)

#find the number of data
tweets_num = length(review_text)

#Disconnect connections
dbdisconnect = lapply(dbListConnections( dbDriver( drv = "MySQL")), dbDisconnect)

#checking if all connection has been closed
dbListConnections(MySQL())
</code>```

The values in my database are the correct ones.How do i solve this problem?

答:
Database tables represent unordered sets of data.  In your table snapshot, it appears that the records are sorted by ID in ascending order.  I postulate that all the data did in fact make it into your data frame, but that data frame has a different order than what you showed when querying your table.  To confirm this, you can try sorting the data frame ascending on the ID:

```<code>datafetd[with(datafetd, order(ID)), ]
</code>```

Body:
I am getting tweet_id from a table in my database and storing them in a dataframe in r. The problem is that the tweet_id values are not being added correctly in dataframe.

snapshot of my table:

snapshot of my dataframe in rstudio:

As you can see there is no tweet_id = '882100387989291008'(3rd value in my dataframe) in my database table

my Rscript file:

#connecting with db
#myDB = dbConnect(MySQL(), user = "root", password = "F33mtHaDD", dbname = "dashboard", host= "127.0.0.1", port="8889")

myDB =dbConnect(MySQL(), user = "root", password ="F33mtHaDD", dbname = "dashboard")

options(scipen=10)
options()$scipen

#running a query and retriving data and saving it in a object
rs = dbSendQuery(myDB, "SELECT tweet_id, sentiment, text FROM dashboard.sen_tweets_twitter WHERE text <> '';")

#getting the result. The function fetch() saves the result in a dataframe
datafetd = fetch(rs, n=-1)

#removing extra whitespaces
#new = stripWhitespace(datafetd$text)
#dataafterclean =data.frame(new)

#converts into one single string
review_text = paste(datafetd$text)
review_id = paste(datafetd$tweet_id)

print(review_id)

rm(tm_tdm)

#find the number of data
tweets_num = length(review_text)

#Disconnect connections
dbdisconnect = lapply(dbListConnections( dbDriver( drv = "MySQL")), dbDisconnect)

#checking if all connection has been closed
dbListConnections(MySQL())

The values in my database are the correct ones.How do i solve this problem?

Body:
Database tables represent unordered sets of data.  In your table snapshot, it appears that the records are sorted by ID in ascending order.  I postulate that all the data did in fact make it into your data frame, but that data frame has a different order than what you showed when querying your table.  To confirm this, you can try sorting the data frame ascending on the ID:

datafetd[with(datafetd, order(ID)), ]


问:
Vagrant: How to upgrade from PHP5 to PHP7?
Currently my playbook.yml contains:

```<code>tasks:
    - include_vars: vars.yml
    - name: install packages
      apt: name={{ item }} update_cache=yes state=latest
      with_items:
      - git
      - nginx
      - php5
      - vim
      - php5-mysqlnd
      - php5-curl
      - php5-xdebug
      - php5-gd
      - php5-fpm
      - php5-intl
      - php-pear
      - php5-imap
      - php5-mcrypt
      - php5-ming
      - php5-ps
      - php5-pspell
      - php5-recode
      - php5-sqlite
      - php5-tidy
      - php5-xmlrpc
      - php5-xsl
      - fail2ban
      - rsync
      - beanstalkd
      - supervisor
      - redis-server
</code>```

答:
Assuming you're running ubuntu, you should replace all the php related with something like

```<code>- name: PHP | Install Ondrej PHP PPA
  apt_repository: repo='ppa:ondrej/php' update_cache=yes

- name: PHP | Install PHP 7.0
  apt: pkg=php7.0 state=latest
  tags: common

- name: PHP | Install PHP Modules
  apt: pkg={{ item }} state=latest
  tags: common
  with_items: "{{php_modules}}"
</code>```

You can search for php7 compatible mode but this is a good starting point

```<code>  vars:
    php_modules:
      - php7.1-mysql
      - php7.1-gd
      - php-apcu
      - php7.1-mcrypt
      - php7.1-curl
      - php7.1-intl
      - php-memcached
      - php7.1-mbstring
      - php7.1-xml
      - php7.1-pgsql
</code>```

Body:
Currently my playbook.yml contains:

tasks:
    - include_vars: vars.yml
    - name: install packages
      apt: name={{ item }} update_cache=yes state=latest
      with_items:
      - git
      - nginx
      - php5
      - vim
      - php5-mysqlnd
      - php5-curl
      - php5-xdebug
      - php5-gd
      - php5-fpm
      - php5-intl
      - php-pear
      - php5-imap
      - php5-mcrypt
      - php5-ming
      - php5-ps
      - php5-pspell
      - php5-recode
      - php5-sqlite
      - php5-tidy
      - php5-xmlrpc
      - php5-xsl
      - fail2ban
      - rsync
      - beanstalkd
      - supervisor
      - redis-server

Body:
Assuming you're running ubuntu, you should replace all the php related with something like

- name: PHP | Install Ondrej PHP PPA
  apt_repository: repo='ppa:ondrej/php' update_cache=yes

- name: PHP | Install PHP 7.0
  apt: pkg=php7.0 state=latest
  tags: common

- name: PHP | Install PHP Modules
  apt: pkg={{ item }} state=latest
  tags: common
  with_items: "{{php_modules}}"

You can search for php7 compatible mode but this is a good starting point

  vars:
    php_modules:
      - php7.1-mysql
      - php7.1-gd
      - php-apcu
      - php7.1-mcrypt
      - php7.1-curl
      - php7.1-intl
      - php-memcached
      - php7.1-mbstring
      - php7.1-xml
      - php7.1-pgsql


问:
Best way to store EditText data to a file/place to be accessed later?
I have created the example code below to explain myself. I have a few EditText fields that need the data stored as "entries" for later use. My question is, what is the best way to store these three variables to be "listed" in another activity. (liAmount, liAccount, and vID). I was just going to use shared preferences, but even with this, I will have multiple entries on the same EditTexts so I don't really know how to properly serialize them...

```<code>float liAmount;
String liAccount;
String vID;

btnSaveLineItem.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if(etLineItemAmount.length() == 0 || etAccountName.length() == 0) {
            Toast.makeText(NewLineActivity.this, "Fill all fields.", Toast.LENGTH_LONG).show();
        } else {
            saveLineItem();
            createVID();
        }

    }
});

public void createVID(){
    vID = String.valueOf(liAccount.charAt(0) + liAccount.charAt(1) + liAccount.charAt(2) + liAmount);
}

public void saveLineItem(){
    liAmount = Float.valueOf(etLineItemAmount.getText().toString());
    liAccount = etAccountName.getText().toString();
}
</code>```

EDIT: I should clarify, I do want these data files to be stored long-term. These are essentially going to be used in a separate activity file to show a list of all previous entries.

答:
You can use your application class for saving data temporarily. Declare a ArrayList if you want to store just a list of strings or a HashMap to store the values as key value pairs. Like this, in your custom application class declare

```<code>private ArrayList<String> temp;

public ArrayList<String> getTemp() {
    return temp;
}

public void setTemp(ArrayList<String> temp) {
    this.temp = temp;
}
</code>```

Then in any activity call ((YourApplication)getActivity()).getTemp() and  add or get data from it.

Body:
I have created the example code below to explain myself. I have a few EditText fields that need the data stored as "entries" for later use. My question is, what is the best way to store these three variables to be "listed" in another activity. (liAmount, liAccount, and vID). I was just going to use shared preferences, but even with this, I will have multiple entries on the same EditTexts so I don't really know how to properly serialize them...

float liAmount;
String liAccount;
String vID;

btnSaveLineItem.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if(etLineItemAmount.length() == 0 || etAccountName.length() == 0) {
            Toast.makeText(NewLineActivity.this, "Fill all fields.", Toast.LENGTH_LONG).show();
        } else {
            saveLineItem();
            createVID();
        }

    }
});

public void createVID(){
    vID = String.valueOf(liAccount.charAt(0) + liAccount.charAt(1) + liAccount.charAt(2) + liAmount);
}

public void saveLineItem(){
    liAmount = Float.valueOf(etLineItemAmount.getText().toString());
    liAccount = etAccountName.getText().toString();
}

EDIT: I should clarify, I do want these data files to be stored long-term. These are essentially going to be used in a separate activity file to show a list of all previous entries.

Body:
You can use your application class for saving data temporarily. Declare a ArrayList if you want to store just a list of strings or a HashMap to store the values as key value pairs. Like this, in your custom application class declare

private ArrayList<String> temp;

public ArrayList<String> getTemp() {
    return temp;
}

public void setTemp(ArrayList<String> temp) {
    this.temp = temp;
}

Then in any activity call ((YourApplication)getActivity()).getTemp() and  add or get data from it.


问:
JUnit test — analysing expected Exceptions
In JUnit, I'm currently using annotation to expect an exception in my tests.

Is there a way to analyse this exception? For example, I expect a CriticalServerException, but I also want to verify the content of the getMessage method.

答:
```<code>try {
    // test code invacation
    fail("Exception not throw!!!");
} catch(CriticalServerException ex) {
    assertTrue("Invalid exception data", ex.toString().contains("error text"));
}
</code>```


问:
How to check whether a given file is a valid video file in C++?
I tried to do it using OpenCV:

```<code>std::string input_name = "<path to file>";
cv::VideoCapture cap(input_name);
if(!cap.isOpened()) printf("Invalid video\n");
</code>```

However, when I try passing a .txt file, VideoCapture reads it successfully for unknown reasons. When I try to find the number of frames in the video,

```<code>if(cap.get(cv::CV_CAP_PROP_FRAME_COUNT) == 0) printf("Invalid video\n");
</code>```

I get a different number of frames each time I execute. I also tried finding the width and height of a frame in the file,

```<code>cv::Mat Frame;
if(!cap.read(Frame)) printf("Cannot read frame\n");
else
{
    printf("Frame width is %d\n", Frame.cols);
    printf("Frame height is %d\n", Frame.rows);
}
</code>```

their values are 640 and 400 respectively. Why is this happening? Is there a way to check if a given file is a valid video file preferably using OpenCV?

答:
you can use the method  VideoCapture::read(), that will return false if:

the video is corrupt

the string path is pointing to an invalid file

example:

```<code>cv::VideoCapture cap(input_name);
auto x = cap.read(im);
</code>```

Body:
I tried to do it using OpenCV:

std::string input_name = "<path to file>";
cv::VideoCapture cap(input_name);
if(!cap.isOpened()) printf("Invalid video\n");

However, when I try passing a .txt file, VideoCapture reads it successfully for unknown reasons. When I try to find the number of frames in the video,

if(cap.get(cv::CV_CAP_PROP_FRAME_COUNT) == 0) printf("Invalid video\n");

I get a different number of frames each time I execute. I also tried finding the width and height of a frame in the file,

cv::Mat Frame;
if(!cap.read(Frame)) printf("Cannot read frame\n");
else
{
    printf("Frame width is %d\n", Frame.cols);
    printf("Frame height is %d\n", Frame.rows);
}

their values are 640 and 400 respectively. Why is this happening? Is there a way to check if a given file is a valid video file preferably using OpenCV?

Body:
you can use the method  VideoCapture::read(), that will return false if:

the video is corrupt

the string path is pointing to an invalid file

example:

cv::VideoCapture cap(input_name);
auto x = cap.read(im);


问:
enum vs separate table for storing roles?
I have to implement a role system in my app for authorization. We have around 5 kind of roles in our system.

To maintain these roles we have 2 options,

Alternative #1

1.Create an enum in rails Role model,

enum role: {super_admin: 1, translator: 2, approver: 3, sales_admin: 4, marketing_admin: 5, guest: 6}

2.In the Roles table , now we will have ID user_id role_id

Alternative #2

1.Create 2 models Role and Role_User.

Role table will only contain ID | role_name and Role_User will contain ID | user_id | role_id

Which should be preferred?

答: I would suggest to go for second approach as if in future there is any possibility of additional role there will be no burden for you to create that additional role. With first approach you have to edit your enum for additional roles which you might want to add in future</p>


答:
The error occurs here:

```<code>if(strlen(str) + (strlen(ss.str) < sz)
</code>```

That probably should be:

```<code>if (strlen(str) + strlen(ss.str) < sz)
</code>```

Title: The left parenthesis '(' found at 'foo.cpp' was not matched correctly

Body:
The error occurs here:

if(strlen(str) + (strlen(ss.str) < sz)

That probably should be:

if (strlen(str) + strlen(ss.str) < sz)


问:
How can I get selected text from webview in android?
I need to get selected text from webview.

For this, I put this:

```<code>webView.loadUrl("javascript:Android.getHtml(window.getSelection().toString())");
</code>```

In my touch event.

touch event works well

Android.getHtml works well (this is javascriptinterface method)

window.getSelection doesn't have any value: it's problem -> in my view, when I touched a word in webview, window.getSelection automatically should contain the text. Am I wrong?

Is there anyone who can have an idea for this?

Very thanks in advance.

Ps: below is my whole code

```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_each_news, container, false);

    //설정된 인자값을 받는다
    String newsAddress = getArguments().getString("newsAddress");

    //Start : 받은 주소로 웹뷰를 띄운다...
    webView = (WebView) rootView.findViewById(R.id.webView);
    //  webView.setWebViewClient(new WebViewClient());

    webView.setWebViewClient(new WebViewClient() {});

    webSettings = webView.getSettings();

    webSettings.setJavaScriptEnabled(true);     //자바스크립트 허용여부
    webSettings.setLoadWithOverviewMode(true);  //웹페이지 웹뷰크기에 맞추기 위한 설정
    webSettings.setUseWideViewPort(true);   //웹페이지 웹뷰크기에 맞추기 위한 설정
    webView.setInitialScale(1); //웹페이지 웹뷰크기에 맞추기 위한 설정

    webView.addJavascriptInterface(new MyJavascriptInterface(), "Android"); //자바스크립트 인터페이스 메소드 등록

    //url 호출
    webView.loadUrl(newsAddress);
    webView.setOnTouchListener(this);
    //End : 받은 주소로 웹뷰를 띄운다...

    return rootView;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {

    switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            //   Toast.makeText(getContext(),"웹뷰클릭",Toast.LENGTH_LONG).show();
            pressStartTime = System.currentTimeMillis();
            pressedX = motionEvent.getX();
            pressedY = motionEvent.getY();
            stayedWithinClickDistance = true;
            break;
        }
        case MotionEvent.ACTION_MOVE: {

            if (stayedWithinClickDistance && getDistance(pressedX, pressedY, motionEvent.getX(), motionEvent.getY()) > MAX_CLICK_DISTANCE) {
                stayedWithinClickDistance = false;
            }
            break;
        }
        case MotionEvent.ACTION_UP: {
            long pressDuration = System.currentTimeMillis() - pressStartTime;
            if (pressDuration < MAX_CLICK_DURATION && stayedWithinClickDistance) {
                // 클릭처리
                webView.evaluateJavascript("(function(){return window.getSelection().toString()})()",
                        new ValueCallback<String>()
                        {
                            @Override
                            public void onReceiveValue(String value)
                            {
                                Log.v(TAG, "SelectedText:" + value);
                            }
                        });
            }
        }
    }
    return false;
}
</code>```

答:
For API >= 19 you can use evaluateJavascript

```<code>mWebview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
    @Override
    public void onReceiveValue(String value)
    {
        Log.v(TAG, "Webview selected text: " + value);
    }
});
</code>```

For API < 19 you can use evaluateJavascript you use the loadUrl method like below:

```<code>mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.addJavascriptInterface(new JavaScriptInterface(), "javascriptinterface");
</code>```

Then when you want to get the selection use the following:

mWebview.loadUrl("javascript:javascriptinterface.callback(window.getSelection().toString())");

And define a WebAppInterface class as below:

```<code>public class JavaScriptInterface
{
    @JavascriptInterface
    public void callback(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
}
</code>```

Body:
I need to get selected text from webview.

For this, I put this:

webView.loadUrl("javascript:Android.getHtml(window.getSelection().toString())");

In my touch event.

touch event works well

Android.getHtml works well (this is javascriptinterface method)

window.getSelection doesn't have any value: it's problem -> in my view, when I touched a word in webview, window.getSelection automatically should contain the text. Am I wrong?

Is there anyone who can have an idea for this?

Very thanks in advance.

Ps: below is my whole code

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_each_news, container, false);

    //설정된 인자값을 받는다
    String newsAddress = getArguments().getString("newsAddress");

    //Start : 받은 주소로 웹뷰를 띄운다...
    webView = (WebView) rootView.findViewById(R.id.webView);
    //  webView.setWebViewClient(new WebViewClient());

    webView.setWebViewClient(new WebViewClient() {});

    webSettings = webView.getSettings();

    webSettings.setJavaScriptEnabled(true);     //자바스크립트 허용여부
    webSettings.setLoadWithOverviewMode(true);  //웹페이지 웹뷰크기에 맞추기 위한 설정
    webSettings.setUseWideViewPort(true);   //웹페이지 웹뷰크기에 맞추기 위한 설정
    webView.setInitialScale(1); //웹페이지 웹뷰크기에 맞추기 위한 설정

    webView.addJavascriptInterface(new MyJavascriptInterface(), "Android"); //자바스크립트 인터페이스 메소드 등록

    //url 호출
    webView.loadUrl(newsAddress);
    webView.setOnTouchListener(this);
    //End : 받은 주소로 웹뷰를 띄운다...

    return rootView;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {

    switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            //   Toast.makeText(getContext(),"웹뷰클릭",Toast.LENGTH_LONG).show();
            pressStartTime = System.currentTimeMillis();
            pressedX = motionEvent.getX();
            pressedY = motionEvent.getY();
            stayedWithinClickDistance = true;
            break;
        }
        case MotionEvent.ACTION_MOVE: {

            if (stayedWithinClickDistance && getDistance(pressedX, pressedY, motionEvent.getX(), motionEvent.getY()) > MAX_CLICK_DISTANCE) {
                stayedWithinClickDistance = false;
            }
            break;
        }
        case MotionEvent.ACTION_UP: {
            long pressDuration = System.currentTimeMillis() - pressStartTime;
            if (pressDuration < MAX_CLICK_DURATION && stayedWithinClickDistance) {
                // 클릭처리
                webView.evaluateJavascript("(function(){return window.getSelection().toString()})()",
                        new ValueCallback<String>()
                        {
                            @Override
                            public void onReceiveValue(String value)
                            {
                                Log.v(TAG, "SelectedText:" + value);
                            }
                        });
            }
        }
    }
    return false;
}

Body:
For API >= 19 you can use evaluateJavascript

mWebview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
    @Override
    public void onReceiveValue(String value)
    {
        Log.v(TAG, "Webview selected text: " + value);
    }
});

For API < 19 you can use evaluateJavascript you use the loadUrl method like below:

mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.addJavascriptInterface(new JavaScriptInterface(), "javascriptinterface");

Then when you want to get the selection use the following:

mWebview.loadUrl("javascript:javascriptinterface.callback(window.getSelection().toString())");

And define a WebAppInterface class as below:

public class JavaScriptInterface
{
    @JavascriptInterface
    public void callback(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
}


问:
Whether progressive web app supports offline on desktop? If no why?
I am interested in developing a progressive web app.I want to know whether it supports offline in desktop.</p>

答:
Because the progressive Web apps on mobile use the local storage mechanism on mobile and it keeps the data updated by asynchronously interacting with actual backend APIs using delta calls.
However on a browser you do not have such facility to keep this much data on local storage. Also you can not enforce a user to install a local mysql per se. . </p>


问:
Json Formatting into plane format
I have my data as in json nested object but want to be formatted into simple json array format with the help of any javascript function. I tried doing it by for-loop but failed.

```<code> var dataModel: [   {
                "phaseName" : "Closure",
                "milestone" : [
                    {
                        "milestoneName" : "Mile-1",
                        "startDate" : ISODate("2017-08-06T18:30:00.000Z"),
                        "endDate" : ISODate("2017-07-06T18:30:00.000Z"),
                        "_id" : ObjectId("595a38e1ceb1973980406b7f")
                    },
                    {
                        "milestoneName" : "Mile-2",
                        "startDate" : ISODate("2017-07-04T18:30:00.000Z"),
                        "endDate" : ISODate("2017-07-13T18:30:00.000Z"),
                        "_id" : ObjectId("595a4394c7a5bb3120126721")
                    }
                ]
            }
]
</code>```

But i want my result should be formated by applying any function that convert the dataModel as

```<code>newModel = [{
         "phaseName":"Closure",
          "MilestoneName":"Mile-1",
          "startDate":"07/07/2017",
          "endDate":"07/15/2017"
},
{
         "phaseName":"Closure",
          "MilestoneName":"Mile-2",
          "startDate":"07/07/2017",
          "endDate":"07/15/2017"
}

]
</code>```

答:
```<code>var newModel = [];
for(var i = 0; i < dataModel.length; i++){
for(var e = 0; e < dataModel[i].milestone.length;e++){
  newModel.push({
    "phase": dataModel[i].phaseName,
    "milestone":dataModel[i].milestone[e].milestoneName,
   "startDate":dataModel[i].milestone[e].startDate,
 "endDate":dataModel[i].milestone[e].endDate,
  })

console.log(newModel)
</code>```

Title: Json Formatting into plane format

Body:
I have my data as in json nested object but want to be formatted into simple json array format with the help of any javascript function. I tried doing it by for-loop but failed.

 var dataModel: [   {
                "phaseName" : "Closure",
                "milestone" : [
                    {
                        "milestoneName" : "Mile-1",
                        "startDate" : ISODate("2017-08-06T18:30:00.000Z"),
                        "endDate" : ISODate("2017-07-06T18:30:00.000Z"),
                        "_id" : ObjectId("595a38e1ceb1973980406b7f")
                    },
                    {
                        "milestoneName" : "Mile-2",
                        "startDate" : ISODate("2017-07-04T18:30:00.000Z"),
                        "endDate" : ISODate("2017-07-13T18:30:00.000Z"),
                        "_id" : ObjectId("595a4394c7a5bb3120126721")
                    }
                ]
            }
]

But i want my result should be formated by applying any function that convert the dataModel as

newModel = [{
         "phaseName":"Closure",
          "MilestoneName":"Mile-1",
          "startDate":"07/07/2017",
          "endDate":"07/15/2017"
},
{
         "phaseName":"Closure",
          "MilestoneName":"Mile-2",
          "startDate":"07/07/2017",
          "endDate":"07/15/2017"
}

]


问:
Echo php with echoed html php
I currently have a php which echo my html template.

However in that HTML template there is another echo which calls from another php script.

Just wondering how do I do that? Because once I echo my html template the other it doesn't seems to echo my content from the other php script.

HTML TEMPLATE

```<code><php? $html = '<span>name:<?php echo $name; ?></span><span>email:<?php echo $email; ?></span>' ?>
</code>```

CONTACT TEMPLATE

```<code><php? $name = "hello world"; $email = "hello@world.com"; ?>
</code>```

答: Change the tags from <php?  ?> to <?php  ?> in your script

Title: Echo php with echoed html php

Body:
I currently have a php which echo my html template.

However in that HTML template there is another echo which calls from another php script.

Just wondering how do I do that? Because once I echo my html template the other it doesn't seems to echo my content from the other php script.

HTML TEMPLATE

<php? $html = 'name:<?php echo $name; ?>email:<?php echo $email; ?>' ?>

CONTACT TEMPLATE

<php? $name = "hello world"; $email = "hello@world.com"; ?>


答:
Just Concatenation  </p>

```<code><?
$html = '<span>name:'.$name.'</span><span>email:'.$email.'</span>';
?>
</code>```

Title: Echo php with echoed html php

Body:
Just Concatenation

<?
$html = '<span>name:'.$name.'</span><span>email:'.$email.'</span>';
?>


问:
Stack is empty error when calling context.Done in child dialog
I have a LuisDialog which makes a forward to another LuisDialog in the "None" intent as some kind of fallback:

```<code>[LuisIntent("None")]
public async Task None(IDialogContext context, IAwaitable<IMessageActivity> message, LuisResult result)
{
    var luisService = new LuisService(new LuisModelAttribute("XXX", "XXX"));
    await context.Forward(new MyChildDialog(luisService), null, await message);

    context.Wait(MessageReceived);
}
</code>```

The method executed in MyChildDialog is like this:

```<code>[LuisIntent("myLuisIntent")]
public async Task MyLuisIntent(IDialogContext context, LuisResult result)
{
    await context.PostAsync("Hi!");
    context.Done(0);
}
</code>```

When the context.Done() is executed, emulator shows an error: "Stack is empty". But, how can it be empty if forward adds the dialog to the stack?

答:
Make sure you have a handler for what to do when the MyChildDialog is fininshed</p>

```<code>    [LuisIntent("None")]
    public async Task None(IDialogContext context, IAwaitable<IMessageActivity> message, LuisResult result)
    {
        var luisService = new LuisService(new LuisModelAttribute("XXX", "XXX"));
        await context.Forward(new MyChildDialog(luisService), WaitForMessageResume, await message);

        context.Wait(MessageReceived);
    }

    private Task WaitForMessageResume(IDialogContext context, IAwaitable<object> result)
    {
        context.Wait(MessageReceived);
        return Task.CompletedTask;
    }
</code>```

Body:
I have a LuisDialog which makes a forward to another LuisDialog in the "None" intent as some kind of fallback:

[LuisIntent("None")]
public async Task None(IDialogContext context, IAwaitable<IMessageActivity> message, LuisResult result)
{
    var luisService = new LuisService(new LuisModelAttribute("XXX", "XXX"));
    await context.Forward(new MyChildDialog(luisService), null, await message);

    context.Wait(MessageReceived);
}

The method executed in MyChildDialog is like this:

[LuisIntent("myLuisIntent")]
public async Task MyLuisIntent(IDialogContext context, LuisResult result)
{
    await context.PostAsync("Hi!");
    context.Done(0);
}

When the context.Done() is executed, emulator shows an error: "Stack is empty". But, how can it be empty if forward adds the dialog to the stack?

Body:
Make sure you have a handler for what to do when the MyChildDialog is fininshed

    [LuisIntent("None")]
    public async Task None(IDialogContext context, IAwaitable<IMessageActivity> message, LuisResult result)
    {
        var luisService = new LuisService(new LuisModelAttribute("XXX", "XXX"));
        await context.Forward(new MyChildDialog(luisService), WaitForMessageResume, await message);

        context.Wait(MessageReceived);
    }

    private Task WaitForMessageResume(IDialogContext context, IAwaitable<object> result)
    {
        context.Wait(MessageReceived);
        return Task.CompletedTask;
    }


问:
I am creating multiple "single" select tags dynamically in html using angularjs. Two columns contain two different select tags. I want the second
I have two columns in which I generate select tags dynamically. So if there are four rows, four select tags for each column. I want that the second select tag of column2 should only be selectable when a particular option in the first select tag has been selected. </p>

```<code><tbody ng-init="count=0">

                    <tr ng-repeat="a in CustomerCallDetails">
                     <td colspan="1">{{a.first_name}} {{a.last_name}}</td>
                        <td colspan="1">{{a.date}}</td>
                        <td colspan="1">{{a.parent_classification_name}}({{a.parent_brand}})</td>
                        <td colspan="1">₹ {{a.customer_revenue | number}}</td>
                        <td colspan="1">{{a.phone}}</td>
                        <td>
                        <select><option ng-click="!disableSelect[count];count=count+1">Called</option><option selected="selected">Not Called</option></select>
                        </td>
                        <td colspan="1">
                         <select ng-disabled="disableSelect[count]"><option>Called</option><option selected="selected">Not Called</option></select>
                        </td>

                    </tr>

                </tbody>
</code>```

<p>This is the code I have tried till now. But it doesnt seem to work. I have a for loop in my controller that defines disabledSelect as true. Where am I going wrong? I am new to angular. Maybe this sounds like a very tiny problem. </p>

答:
You can have a look at this example to infer idea and adapt it on your existing code.

HTML

```<code><div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
        <select
            ng-options="p.id as p.first for p in people"
            ng-model="selectedPerson"></select>
        <select ng-disabled='selectedPerson === 2'
            ng-options="p.id as p.actor for p in actor"
            ng-model="selectedActor"></select>
            selected person id: {{selectedPerson}}
    </fieldset>
</div>
</code>```

Controller

```<code>var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
    $scope.people = [
        { id: 1, first: 'John',  actor: 'Silvester' },
        { id: 2, first: 'Rocky',actor: 'Silvester' },
        { id: 3, first: 'John',actor: 'Arnold' },
        { id: 4, first: 'Ben',actor: 'Arnold' }
    ];

      $scope.actor = [
        { id: 1, actor: 'Silvester' },
        { id: 2, actor: 'Silvester' },
        { id: 3, actor: 'Arnold' },
        { id: 4, actor: 'Arnold' }
    ];
});
</code>```

Here the first select dropdown is for the people and the value for the <option> is the id of the people. So, whenever the people with id:2 is selected the select dropdown for the Actor is disabled.

For your simplicity and further experiment here is the link to JSFIDDLE

Body:
I have two columns in which I generate select tags dynamically. So if there are four rows, four select tags for each column. I want that the second select tag of column2 should only be selectable when a particular option in the first select tag has been selected.

                     {{a.first_name}} {{a.last_name}}
                        {{a.date}}
                        {{a.parent_classification_name}}({{a.parent_brand}})
                        ₹ {{a.customer_revenue | number}}
                        {{a.phone}}

                        <select><option ng-click="!disableSelect[count];count=count+1">Called</option><option selected="selected">Not Called</option></select>

                         <select ng-disabled="disableSelect[count]"><option>Called</option><option selected="selected">Not Called</option></select>

This is the code I have tried till now. But it doesnt seem to work. I have a for loop in my controller that defines disabledSelect as true. Where am I going wrong? I am new to angular. Maybe this sounds like a very tiny problem.

Body:
You can have a look at this example to infer idea and adapt it on your existing code.

HTML

<div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
        <select
            ng-options="p.id as p.first for p in people"
            ng-model="selectedPerson"></select>
        <select ng-disabled='selectedPerson === 2'
            ng-options="p.id as p.actor for p in actor"
            ng-model="selectedActor"></select>
            selected person id: {{selectedPerson}}
    </fieldset>
</div>

Controller

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
    $scope.people = [
        { id: 1, first: 'John',  actor: 'Silvester' },
        { id: 2, first: 'Rocky',actor: 'Silvester' },
        { id: 3, first: 'John',actor: 'Arnold' },
        { id: 4, first: 'Ben',actor: 'Arnold' }
    ];

      $scope.actor = [
        { id: 1, actor: 'Silvester' },
        { id: 2, actor: 'Silvester' },
        { id: 3, actor: 'Arnold' },
        { id: 4, actor: 'Arnold' }
    ];
});

Here the first select dropdown is for the people and the value for the <option> is the id of the people. So, whenever the people with id:2 is selected the select dropdown for the Actor is disabled.

For your simplicity and further experiment here is the link to JSFIDDLE


问:
how to add array values to column using excel VBA
I am using below vba code, I have multiple columns for sample I have provided few.
All I am trying is, if I try to make the changes the same value should restore to the deleted column headers.
Below code is working fine if I make any changes to the range "A1" however if I make any changes other than "A1", code is taking too much of time complete and it is looping too many times.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim headers() As Variant
If Range("A1").Value <> "FIRST" Or Range("B1").Value <> "Second" Or Range("C1").Value <> "Third"  Then
headers() = Array("FIRST", "Second", "Third")
With Sheets("Sheet1")
For i = LBound(headers()) To UBound(headers())
.Cells(1, 1 + i).Value = headers(i)
 Next i
 .Rows(1).Font.Bold = True
End With
End If
</code>```

==============================
Please help me to resolve this issue, appreciate your help in advance.

答:
The issue is that the value change on .Cells(1, 1 + i).Value = headers(i) triggers the event itself. You're basically going into an endless execution chain like this.

You should either Disable the events during execution of this macro, or do a check on each header.

The simplest solution:

```<code>Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim headers() As Variant
Dim i As Integer

Application.EnableEvents = False 'This fixes your issue.

If Range("A1").Value <> "FIRST" Or Range("B1").Value <> "Second" Or Range("C1").Value <> "Third" Then
    headers() = Array("FIRST", "Second", "Third")
    With Sheets("Sheet1")
        For i = LBound(headers()) To UBound(headers())
            .Cells(1, 1 + i).Value = headers(i)
        Next i
        .Rows(1).Font.Bold = True
    End With
End If

Application.EnableEvents = True
End Sub
</code>```

Body:
I am using below vba code, I have multiple columns for sample I have provided few.
All I am trying is, if I try to make the changes the same value should restore to the deleted column headers.
Below code is working fine if I make any changes to the range "A1" however if I make any changes other than "A1", code is taking too much of time complete and it is looping too many times.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim headers() As Variant
If Range("A1").Value <> "FIRST" Or Range("B1").Value <> "Second" Or Range("C1").Value <> "Third"  Then
headers() = Array("FIRST", "Second", "Third")
With Sheets("Sheet1")
For i = LBound(headers()) To UBound(headers())
.Cells(1, 1 + i).Value = headers(i)
 Next i
 .Rows(1).Font.Bold = True
End With
End If

==============================
Please help me to resolve this issue, appreciate your help in advance.

Body:
The issue is that the value change on .Cells(1, 1 + i).Value = headers(i) triggers the event itself. You're basically going into an endless execution chain like this.

You should either Disable the events during execution of this macro, or do a check on each header.

The simplest solution:

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim headers() As Variant
Dim i As Integer

Application.EnableEvents = False 'This fixes your issue.

If Range("A1").Value <> "FIRST" Or Range("B1").Value <> "Second" Or Range("C1").Value <> "Third" Then
    headers() = Array("FIRST", "Second", "Third")
    With Sheets("Sheet1")
        For i = LBound(headers()) To UBound(headers())
            .Cells(1, 1 + i).Value = headers(i)
        Next i
        .Rows(1).Font.Bold = True
    End With
End If

Application.EnableEvents = True
End Sub


问:
C# Get Screen Orientation
How to find the current screen orientation using C#?

I have tried the following code without much success.

```<code>DisplayOrientations currentOrientation =
Windows.Graphics.Display.DisplayProperties.CurrentOrientation;
</code>```

答:
You can take the SystemInformation-object instead and take its ScreenOrientation.

You will get a ScreenOrientation-enumeration back.

```<code>var orientation = SystemInformation.ScreenOrientation;
Console.WriteLine(orientation);
</code>```

Prints 'Angle0' on my system with default orientation

Title: C# Get Screen Orientation

Body:
How to find the current screen orientation using C#?

I have tried the following code without much success.

DisplayOrientations currentOrientation =
Windows.Graphics.Display.DisplayProperties.CurrentOrientation;

Body:
You can take the SystemInformation-object instead and take its ScreenOrientation.

You will get a ScreenOrientation-enumeration back.

var orientation = SystemInformation.ScreenOrientation;
Console.WriteLine(orientation);

Prints 'Angle0' on my system with default orientation


问:
Generate .i file from .c file
I know that gcc does that. But I would want a C program that can do so. The program should accept a .c file and does the preprocessing operations and generate .i file
FYI : this is a project that was assigned to my kin in his college.</p>

答:
If you cannot use external program such as gcc, you have to implement C preprocessor yourself. Whole preprocessor is described in C Programming Language specification in section "Preprocessing directives".

Alternatively, if you cannot use other programs, but you don't want to implement it yourself, you could try using libclang as a library (although, for that you'd need C++).

Title: Generate .i file from .c file


问:
How can I check out a GitHub pull request with git?
I'd like to check out a previously created pull request (created via GitHub web interface). I searched and found different places where a refs/pull or refs/pull/pr

But when I add fetch = +refs/pull/*/head:refs/remotes/origin/pr/* to the git config file and do a git fetch

What I'm doing wrong? Should GitHub create automatically the pull/xyz stuff, or do I have to configure something?

答:
You can use git config command to write a new rule to .git/config to fetch pull requests from the repository:

```<code>$ git config --local --add remote.origin.fetch '+refs/pull/*/head:refs/remotes/origin/pr/*'
</code>```

And then just:

```<code>$ git fetch origin
Fetching origin
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 2), reused 4 (delta 2), pack-reused 0
Unpacking objects: 100% (4/4), done.
From https://github.com/container-images/memcached
 * [new ref]         refs/pull/2/head -> origin/pr/2
 * [new ref]         refs/pull/3/head -> origin/pr/3
</code>```

Body:
You can use git config command to write a new rule to .git/config to fetch pull requests from the repository:

$ git config --local --add remote.origin.fetch '+refs/pull/*/head:refs/remotes/origin/pr/*'

And then just:

$ git fetch origin
Fetching origin
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 2), reused 4 (delta 2), pack-reused 0
Unpacking objects: 100% (4/4), done.
From https://github.com/container-images/memcached
 * [new ref]         refs/pull/2/head -> origin/pr/2
 * [new ref]         refs/pull/3/head -> origin/pr/3


问:
Add strechable space in WPF
I have this XAML:

```<code><Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="400" Width="400" >

    <StackPanel Margin="10, 10, 10, 10">

        <CheckBox Content="CheckBox" Margin="0, 0, 0, 10"/>
        <Button Content="Button" Height="30" Click="OnClick"/>

    </StackPanel>

</Window>
</code>```

which gives this output:

How can I add a stretchable space between the combo box and the button to keep one on the top, and the other on the bottom?

Thanks,
Massimo

答:
Don't use a StackPanel for this because a StackPanel will only fill the space which is needed by it's children.
A Grid is better for this.

Something like this would do it.

```<code><Grid Margin="10, 10, 10, 10">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <CheckBox Content="CheckBox"
              Grid.Row="0"
              Margin="0, 0, 0, 10" />
    <Button Content="Button"
            Height="30"
            Grid.Row="2"
            Click="OnClick" />
</Grid>
</code>```

Title: Add strechable space in WPF

Body:
I have this XAML:

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="400" Width="400" >

    <StackPanel Margin="10, 10, 10, 10">

        <CheckBox Content="CheckBox" Margin="0, 0, 0, 10"/>
        <Button Content="Button" Height="30" Click="OnClick"/>

    </StackPanel>

</Window>

which gives this output:

How can I add a stretchable space between the combo box and the button to keep one on the top, and the other on the bottom?

Thanks,
Massimo

Body:
Don't use a StackPanel for this because a StackPanel will only fill the space which is needed by it's children.
A Grid is better for this.

Something like this would do it.

<Grid Margin="10, 10, 10, 10">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <CheckBox Content="CheckBox"
              Grid.Row="0"
              Margin="0, 0, 0, 10" />
    <Button Content="Button"
            Height="30"
            Grid.Row="2"
            Click="OnClick" />
</Grid>


问:
antlr4 error handling doesn't even compile
I followed the instructions for error handling at the antlr website http://www.antlr2.org/doc/err.html (it says antlr2 but I couldn't find an alternative for antlr4) and wrote the exception handling for my rule as below.

```<code>subStmt :
(visibility WS)? (STATIC WS)? SUB WS? ambiguousIdentifier (WS? argList)? endOfStatement
block?
END_SUB
;
exception
catch [RecognitionException ex] {

}
</code>```

But when I try to generate the Parser for the grammar it fails as below:
java -jar ../Downloads/antlr-4.7-complete.jar vba.g4 -package vba -o out
error(50): vba.g4:500:4: syntax error: 'catch' came as a complete surprise to me while matching rule preamble

Any help is much appreciated.

答:
Antlr4 is quite different to Antlr2. Start by having a look at this question (and the answer):

How to implement error handling in ANTLR4

Update with a simple approach:

For error reporting, the basic approach is to make a class that implements the ANTLRErrorListener interface. BaseErrorListener has empty implementations for all the methods so you only need to implement the ones you care about. You probably care about syntaxError() the most.

On your parser object, call removeErrorListeners() to clear the internal error listener, and then call addErrorListener() with an instance of the class you want to handle your errors.

You will then get syntaxError() calls on that class when errors are encountered during a parse.

The other methods might (or might not) let you do what you want to do; I haven't used this interface to recover from parse errors.

For recovering from particular errors, you can implement a class with the  ANTLRErrorStrategy interface. That gets complicated; see DefaultErrorStrategy for the default implementation.

A very simple approach is to deal with the possible errors in your grammar. Not sure how far you can go with this, but this is likely to be the easiest approach.

Body:
I followed the instructions for error handling at the antlr website http://www.antlr2.org/doc/err.html (it says antlr2 but I couldn't find an alternative for antlr4) and wrote the exception handling for my rule as below.

subStmt :
(visibility WS)? (STATIC WS)? SUB WS? ambiguousIdentifier (WS? argList)? endOfStatement
block?
END_SUB
;
exception
catch [RecognitionException ex] {

}

But when I try to generate the Parser for the grammar it fails as below:
java -jar ../Downloads/antlr-4.7-complete.jar vba.g4 -package vba -o out
error(50): vba.g4:500:4: syntax error: 'catch' came as a complete surprise to me while matching rule preamble

Any help is much appreciated.


问:
How to make an image not scroll?
I would like to know how to make an image not scroll with the rest of the page. However, I want the image to be a certain percentage of width, and the browser automatically figure out the heightto display the image, and the image height automatically configured also determines the parent div's height.

The following code allows me to position the image area nicely and size the actual image nicely:

.popPictureParent {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
  overflow: hidden;
}

.popPicture {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
}

.popPicture img {
  display: block;
  width: 100%;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="popPictureParent" id="picture1">
  <div class="popPicture">
    <img src="./files/painting_scene_smaller.png" alt="painting scene" />
  </div>
</div></code>```

How would I make the image not sccroll similar to this website: https://www.thediyjoint.com/ but have the image size and position the divs how I have it right now? I have other things on the website that it has to not intrude, this isn't the only thing, so.

I've tried the background image thing, using fixed, absolute, but neither work. I need the browser to do some math to make the image look nice based on a width percentage given.

When I try the background, there isn't an option to set the parent's div width to what the background needs. This is really convoluted to me. If more information is needed, please comment.

EDIT: the thing is, I need the image to serve as a width and height placeholder, so the parent div sizes to it. The background image doesn't give a placeholder. Also, I need the image to not show up outside of its parent div.

答:
You would have to use the background-attachment property

fixed This keyword means that the background is fixed with regard to
  the viewport. Even if an element has a scrolling mechanism, a ‘fixed’
  background doesn't move with the element.

Instead of adding the img tag to the HTML, use CSS to add background-image to the wrapper class in this case .popPicture

For example:

```<code>.popPicture{
     background-image: url('/files/painting_scene_smaller.png');
     background-repeat: no-repeat;
     background-attachment: fixed;
}
</code>```

You can read more about this property here: https://developer.mozilla.org/en/docs/Web/CSS/background-attachment

Additionally, depending on your use case you can adjust the background-size property

The background-size CSS property specifies the size of the background
  images. The size of the image can be fully constrained or only
  partially in order to preserve its intrinsic ratio.

Title: How to make an image not scroll?

Body:
I would like to know how to make an image not scroll with the rest of the page. However, I want the image to be a certain percentage of width, and the browser automatically figure out the heightto display the image, and the image height automatically configured also determines the parent div's height.

The following code allows me to position the image area nicely and size the actual image nicely:

.popPictureParent {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
  overflow: hidden;
}

.popPicture {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
}

.popPicture img {
  display: block;
  width: 100%;
  height: auto;
}

How would I make the image not sccroll similar to this website: https://www.thediyjoint.com/ but have the image size and position the divs how I have it right now? I have other things on the website that it has to not intrude, this isn't the only thing, so.

I've tried the background image thing, using fixed, absolute, but neither work. I need the browser to do some math to make the image look nice based on a width percentage given.

When I try the background, there isn't an option to set the parent's div width to what the background needs. This is really convoluted to me. If more information is needed, please comment.

EDIT: the thing is, I need the image to serve as a width and height placeholder, so the parent div sizes to it. The background image doesn't give a placeholder. Also, I need the image to not show up outside of its parent div.

Body:
You would have to use the background-attachment property

fixed This keyword means that the background is fixed with regard to
  the viewport. Even if an element has a scrolling mechanism, a ‘fixed’
  background doesn't move with the element.

Instead of adding the img tag to the HTML, use CSS to add background-image to the wrapper class in this case .popPicture

For example:

.popPicture{
     background-image: url('/files/painting_scene_smaller.png');
     background-repeat: no-repeat;
     background-attachment: fixed;
}

You can read more about this property here: https://developer.mozilla.org/en/docs/Web/CSS/background-attachment

Additionally, depending on your use case you can adjust the background-size property

The background-size CSS property specifies the size of the background
  images. The size of the image can be fully constrained or only
  partially in order to preserve its intrinsic ratio.


问:
converting date format to yyyy-mm-dd sql server c#
I am creating a web app in which i want to convert the date format into yyyy-mm-dd

currently i am getting date in the following format Saturday, July 1, 2017

here is my full select query

```<code>SELECT
    ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
    D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
    M.PART_NO,
    S.D_NAME,
    PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
WHERE
    M.STORE_ID=D.PART_NO_ID
    AND S.D_ID=D.D_STATUS
    AND D_DATE >= CONVERT(VarChar, 'Saturday, July 1, 2017',1)
    AND D_DATE <= CONVERT(VarChar, 'Monday, July 31, 2017',1)
ORDER BY D.D_ID
</code>```

but i am getting the following error

Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
  date and/or time from character string.

NOTE

D_DATE is in Date format and date is being stored as '2011-01-01'

how can i convert the date?

答:
Your string cannot be recognized as a date. Try this:</p>

```<code>declare @mydate varchar(22) = 'Saturday, July 1, 2017'
select cast(substring(@mydate,charindex(',',@mydate)+2,22)as date)
</code>```

Body:
I am creating a web app in which i want to convert the date format into yyyy-mm-dd

currently i am getting date in the following format Saturday, July 1, 2017

here is my full select query

SELECT
    ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
    D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
    M.PART_NO,
    S.D_NAME,
    PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
WHERE
    M.STORE_ID=D.PART_NO_ID
    AND S.D_ID=D.D_STATUS
    AND D_DATE >= CONVERT(VarChar, 'Saturday, July 1, 2017',1)
    AND D_DATE <= CONVERT(VarChar, 'Monday, July 31, 2017',1)
ORDER BY D.D_ID

but i am getting the following error

Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
  date and/or time from character string.

NOTE

D_DATE is in Date format and date is being stored as '2011-01-01'

how can i convert the date?

Body:
Your string cannot be recognized as a date. Try this:

declare @mydate varchar(22) = 'Saturday, July 1, 2017'
select cast(substring(@mydate,charindex(',',@mydate)+2,22)as date)