问:
Unable to authenticate in Sharepoint API on subsite using PHP
I'm trying to authenticate at a SharePoint Subsite, via PHP, in order to use the REST API and I'm getting some weird behavior.

I'm using the vgrem library.

This is the code I am using:

$authCtx = new AuthenticationContext($Settings['Url']);
$authCtx->acquireTokenForUser($Settings['UserName'],$Settings['Password']);

$ctx = new ClientContext($Settings['Url'],$authCtx);
```

<p>The url has the following format: </p>

```https://sharepointSite.sharepoint.com/sites/SubSiteName/
```

<p>The error I'm getting is: </p>

<blockquote>
  <p>External sharing is disabled for <code>https://sharepointSite.sharepoint.com/</code></p>
</blockquote>

<p>By the look of it the SharePoint site itself is not shared externally, but the subsite is.</p>

<p>I can authenticate via browser and execute some simple GET queries.</p>

<p>The library itself automatically tries to authenticate at:</p>

```https://sharepointSite.sharepoint.com/_forms/default.aspx?wa=wsignin1.0
```

<p>I also tried to alter the library itself in order find the subsite auth page with no success. Some examples of what I tried:</p>

```https://sharepointSite.sharepoint.com/sites/SubSiteName/_forms/default.aspx?wa=wsignin1.0

https://sharepointSite.sharepoint.com/sites/_forms/default.aspx?wa=wsignin1.0
```

What I am currently trying with no success is to reproduce the auth done at the sharepoint site itself:

Authenticate at https://login.microsoftonline.com/extSTS.srf (Success)

The page is redirected to https://sharepointSite.sharepoint.com/{token}/login (Fails, cookies missing) It turns out this step wasn't needed by the authentication process.

https://sharepointSite.sharepoint.com/_forms/default.aspx (not reached yet)

I'm adding the cookies but it seems that something else happens on the backend or some cookie is missing.

I would be grateful if someone provides any help whatsoever. In the meantime I am going to keep on trying.

PS: I've searched most of the answers on SO, but they either refer to a different version of Sharepoint and library, or are obsolete (tried them, with no success).

EDIT: Step 2 was not needed in the end.

答:
As it seems the problem was with the library itself. I solved the problem by adding the string

"&Source=/sites/SubSiteName/"

to the url. The line itself became:

```<code>//$subsite = "&Source=https://sharepointSite.sharepoint.com/sites/SubSiteName/"
$response = Requests::post($url.$subsite,null,$token, true, false);
</code>```

inside the function acquireAuthenticationCookies($token). The extra false is a new variable added in order to apply the curl options only on the request in question.

Also I had to mess a little with the cookie settings, because the library was automatically discarding them on redirect. I had to add the following settings to the request:

```<code>curl_setopt($ch, CURLOPT_COOKIESESSION, false);
curl_setopt($ch, CURLOPT_COOKIEFILE, "");
</code>```

EDIT: Forgot to put the file I edited. It as

php-spo/src/Runtime/Auth/SamlTokenProvider.php

Body:
I'm trying to authenticate at a SharePoint Subsite, via PHP, in order to use the REST API and I'm getting some weird behavior.

I'm using the vgrem library.

This is the code I am using:

$authCtx = new AuthenticationContext($Settings['Url']);
$authCtx->acquireTokenForUser($Settings['UserName'],$Settings['Password']);

$ctx = new ClientContext($Settings['Url'],$authCtx);

The url has the following format:

https://sharepointSite.sharepoint.com/sites/SubSiteName/

The error I'm getting is:

External sharing is disabled for https://sharepointSite.sharepoint.com/

By the look of it the SharePoint site itself is not shared externally, but the subsite is.

I can authenticate via browser and execute some simple GET queries.

The library itself automatically tries to authenticate at:

https://sharepointSite.sharepoint.com/_forms/default.aspx?wa=wsignin1.0

I also tried to alter the library itself in order find the subsite auth page with no success. Some examples of what I tried:

https://sharepointSite.sharepoint.com/sites/SubSiteName/_forms/default.aspx?wa=wsignin1.0

https://sharepointSite.sharepoint.com/sites/_forms/default.aspx?wa=wsignin1.0

What I am currently trying with no success is to reproduce the auth done at the sharepoint site itself:

Authenticate at https://login.microsoftonline.com/extSTS.srf (Success)

The page is redirected to https://sharepointSite.sharepoint.com/{token}/login (Fails, cookies missing) It turns out this step wasn't needed by the authentication process.

https://sharepointSite.sharepoint.com/_forms/default.aspx (not reached yet)

I'm adding the cookies but it seems that something else happens on the backend or some cookie is missing.

I would be grateful if someone provides any help whatsoever. In the meantime I am going to keep on trying.

PS: I've searched most of the answers on SO, but they either refer to a different version of Sharepoint and library, or are obsolete (tried them, with no success).

EDIT: Step 2 was not needed in the end.

Body:
As it seems the problem was with the library itself. I solved the problem by adding the string

"&Source=/sites/SubSiteName/"

to the url. The line itself became:

//$subsite = "&Source=https://sharepointSite.sharepoint.com/sites/SubSiteName/"
$response = Requests::post($url.$subsite,null,$token, true, false);

inside the function acquireAuthenticationCookies($token). The extra false is a new variable added in order to apply the curl options only on the request in question.

Also I had to mess a little with the cookie settings, because the library was automatically discarding them on redirect. I had to add the following settings to the request:

curl_setopt($ch, CURLOPT_COOKIESESSION, false);
curl_setopt($ch, CURLOPT_COOKIEFILE, "");

EDIT: Forgot to put the file I edited. It as

php-spo/src/Runtime/Auth/SamlTokenProvider.php


来源: stackexchange

问:
Rvalue Reference is Treated as an Lvalue?
I posted this answer: https://stackoverflow.com/a/28459180/2642059 Which contains the following code:

```<code>void foo(string&& bar){
    string* temp = &bar;

    cout << *temp << " @:" << temp << endl;
}
</code>```

Is bar an rvalue or an lvalue?

I ask because I obviously cannot take the address of an rvalue, yet I can take the address of an rvalue reference as is done here.

If you can perform any operation on an rvalue reference that you can on an lvalue reference what is the point in differentiating between the two with the "&&" instead of just an "&"?

答:
Here in this case named rvalue references are lvalues, while if the input type is const named rvalue references then it will be rvalue, here is a simple example:

```<code>#include <string>
#include <iostream>

void foo(const std::string&& bar) {
    std::string* temp = &bar; // compile error, can't get address
    std::cout << *temp << " @:" << temp << std::endl;
}

int main()
{
    foo("test");
    return 0;
}
</code>```

Hope  this is useful.

ContentLicense: CC BY-SA 3.0

Body:
I posted this answer: https://stackoverflow.com/a/28459180/2642059 Which contains the following code:

void foo(string&& bar){
    string* temp = &bar;

    cout << *temp << " @:" << temp << endl;
}

Is bar an rvalue or an lvalue?

I ask because I obviously cannot take the address of an rvalue, yet I can take the address of an rvalue reference as is done here.

If you can perform any operation on an rvalue reference that you can on an lvalue reference what is the point in differentiating between the two with the "&&" instead of just an "&"?

Body:
Here in this case named rvalue references are lvalues, while if the input type is const named rvalue references then it will be rvalue, here is a simple example:

#include <string>
#include <iostream>

void foo(const std::string&& bar) {
    std::string* temp = &bar; // compile error, can't get address
    std::cout << *temp << " @:" << temp << std::endl;
}

int main()
{
    foo("test");
    return 0;
}

Hope  this is useful.


问:
String to html element in email
I have a string which includes html elements. For example:

var thisString = "This string has html elements like bold and underline";

I am trying to use this string in an email so that the word bold is actually bold and underline is underlined, rather than displayed as a string.

gs script file:

```<code>var template = HtmlService.createTemplateFromFile('Email');
template.message = thisString;
var message = template.evaluate();
MailApp.sendEmail({
      to: toEmail,
      subject: 'Subject',
      htmlBody: message.getContent()
});
</code>```

html file:

```<code><html>
<?=message?>
</html>
</code>```

The email is sent with body exactly as the string.

答:
You should use force-printing to prevent Apps Script from escaping HTML.</p>

```<code><html>
<?!= message ?>
</html>
</code>```

Title: String to html element in email

Body:
I have a string which includes html elements. For example:

var thisString = "This string has html elements like bold and underline";

I am trying to use this string in an email so that the word bold is actually bold and underline is underlined, rather than displayed as a string.

gs script file:

var template = HtmlService.createTemplateFromFile('Email');
template.message = thisString;
var message = template.evaluate();
MailApp.sendEmail({
      to: toEmail,
      subject: 'Subject',
      htmlBody: message.getContent()
});

html file:

<?=message?>

The email is sent with body exactly as the string.

Body:
You should use force-printing to prevent Apps Script from escaping HTML.

<html>
<?!= message ?>
</html>


问:
Remove a sub-site from SharePoint on a certain date using PowerShell
Hi I am trying to run a PowerShell command that will delete my survey sub-site on January 1st. I have the command to delete the sub-site, but I am unsure how to set it to remove the sub-site on the date.

Any Help would be appreciated

```<code>Remove-SPWeb http://Sharepoint/Survey.com
</code>```

答:
You can run a Powershell script as an action on a scheduled task in Windows Task Scheduler- See here: Use task scheduler to run Powershell Script

Before you do this, and depending on your requirements, you might want to consider retention policies. Specifically site closure and deletion policies- See here: How to set site closure and deletion policies

And here is further information on retention policies to help you understand if this is applicable to you. Overview of retention policies

Body:
Hi I am trying to run a PowerShell command that will delete my survey sub-site on January 1st. I have the command to delete the sub-site, but I am unsure how to set it to remove the sub-site on the date.

Any Help would be appreciated

Remove-SPWeb http://Sharepoint/Survey.com


答:
```<code>SELECT COUNT(*)
FROM(
SELECT DISTINCT object_id
FROM object_table ) as row_count, status_val,id,object_id FROM object_table where row_count = 1;
</code>```

I think you are looking for that

Title: Select Except the duplicate Records from the table in SQL Server

Body:
I have a SQL Server table that has duplicate entries in one of the columns  e.g.:

  +----+-----------+------------+
  | id | object_id | status_val |
  +----+-----------+------------+
  |  1 |         1 |          0 |
  |  2 |         1 |          0 |
  |  3 |         1 |          0 |
  |  4 |         2 |          0 |
  |  5 |         3 |          0 |
  |  6 |         4 |          0 |
  |  7 |         4 |          0 |
  +----+-----------+------------+

I need the output to be like this:

  +----+-----------+------------+
  | id | object_id | status_val |
  +----+-----------+------------+
  |  4 |         2 |          0 |
  |  5 |         3 |          0 |
  +----+-----------+------------+

How to resolve this?

Body:
SELECT COUNT(*)
FROM(
SELECT DISTINCT object_id
FROM object_table ) as row_count, status_val,id,object_id FROM object_table where row_count = 1;

I think you are looking for that


问:
Difference between array of pointers (*A)[] and double pointer **A
With one dimensional arrays (or integers for example) I know how to create pointers both for allocation in the heap and in the stack

-Pointer in the stack and array in the stack

```<code>int a[3];
int *ptr=a;
</code>```

-Pointer in the stack and array in the heap

```<code>int *ptr=new int[3];
</code>```

But for matrix (for example 3x2) the pointer can be created as an array of pointers int (*A)[3] or as a double pointer int **A.

I would like to know the main difference between these two way to create a pointer to a multidimensional array.

In particular I've seen the array of pointers used to create pointer to a matrix array stored in the stack as:

```<code>int A[2][3];
int (*ptr)[3]=A;
</code>```

And I've seen the double pointer used for matrices allocated in the heap

```<code>int **ptr= new *[3];
for(int i=0; i<=3; i++) int ptr[i]=new [2];
</code>```

But is it also possible to use the array of pointer for the heap and the double pointer for the stack?

And again, more generally, what are the main difference between the array of pointers and the double pointer?

答:
From the C++ (2017) Standard (7.2 Array-to-pointer conversion)

1 An lvalue or rvalue of type “array of N T” or “array of unknown
  bound of T” can be converted to a prvalue of type “pointer to T”. The
  temporary materialization conversion (7.4) is applied. The result is
  a pointer to the first element of the array.

Thus let's assume that you have an array like this

```<code>T A[N1][N2]...[Nn];
</code>```

where T is some type and [N1][N2]...[Nn] is an informal record of dimensions of the array. Then this declaration can be written also like

```<code>T ( A[N1] )[N2]...[Nn];
</code>```

To declare a pojnter to the first element of the array all you beed is to substitute ( A[N1] ) for ( *ptr ) in the declaration.

```<code>T ( A[N1] )[N2]...[Nn];
T ( *ptr  )[N2]...[Nn] = A;
</code>```

For example taking the declaration from the question

```<code>int A[2][3];
</code>```

you can rewrite it like

```<code>int ( A[2] )[3];
</code>```

Now it is easy to declare a pointer to the first element of the array

```<code>int ( *ptr )[3] = A;
</code>```

Dereferencing the pointer you get the first "row" of the type int[3] of the two-dimensional array

On the other hand, if you have a declaration of an array of pointers like

```<code>int * A[3];
</code>```

which can be rewritten like

```<code>int * ( A[3] );
</code>```

then to get a declaration of a pointer you can write

```<code>int * ( *ptr ) = A;
</code>```

that is the same as

```<code>int **ptr = A;
</code>```

So dereferencing the pointer you will get an object of the type int * that is in turn a pointer.

So for this declaration

```<code>int ( *ptr )[3] = A;
</code>```

the pointed object is a one-dimensional array. For example you can write

```<code>std::cout << sizeof( *ptr ) << std::endl;
</code>```

and you will get a value that is equal to sizeof( int[3] ) that is equal to 3 * sizeof( int )

As for this declaration

```<code>int * A[3];
int **ptr = A;
</code>```

the pointed object is a pointer of the type int *. If to write for this pointer

```<code>std::cout << sizeof( *ptr ) << std::endl;
</code>```

then you will get a value that is equal to sizeof( int * )

Let's consider this code snippet

```<code>int **ptr = new int *[2];
for( int i = 0; i < 2; i++ ) ptr[i] = new int[3];
</code>```

In the first statement there is dynamically allocated a one-dimensional array of the type int *[2].

Then in the loop there are dynamically created 2 arrays of the type int[3] and pointers to first elements of the arrays are assigned to elements of the previously allocated one-dimensional array.

So in whole there are dynamically allocated 3 arrays: one of the type int *[2] and two of the type int [3]. That is there are allocated three separate extents of memory.

Instead you could write

```<code>int ( *ptr )[3] = new int[2][3];
</code>```

In this case there is allocated dynamically only one two-dimensional array and the declared pointer ptr points to the first "row" of the array. That is there is allocated only one extent of memory.

Body:
With one dimensional arrays (or integers for example) I know how to create pointers both for allocation in the heap and in the stack

-Pointer in the stack and array in the stack

int a[3];
int *ptr=a;

-Pointer in the stack and array in the heap

int *ptr=new int[3];

But for matrix (for example 3x2) the pointer can be created as an array of pointers int (*A)[3] or as a double pointer int **A.

I would like to know the main difference between these two way to create a pointer to a multidimensional array.

In particular I've seen the array of pointers used to create pointer to a matrix array stored in the stack as:

int A[2][3];
int (*ptr)[3]=A;

And I've seen the double pointer used for matrices allocated in the heap

int **ptr= new *[3];
for(int i=0; i<=3; i++) int ptr[i]=new [2];

But is it also possible to use the array of pointer for the heap and the double pointer for the stack?

And again, more generally, what are the main difference between the array of pointers and the double pointer?

Body:
From the C++ (2017) Standard (7.2 Array-to-pointer conversion)

1 An lvalue or rvalue of type “array of N T” or “array of unknown
  bound of T” can be converted to a prvalue of type “pointer to T”. The
  temporary materialization conversion (7.4) is applied. The result is
  a pointer to the first element of the array.

Thus let's assume that you have an array like this

T A[N1][N2]...[Nn];

where T is some type and [N1][N2]...[Nn] is an informal record of dimensions of the array. Then this declaration can be written also like

T ( A[N1] )[N2]...[Nn];

To declare a pojnter to the first element of the array all you beed is to substitute ( A[N1] ) for ( *ptr ) in the declaration.

T ( A[N1] )[N2]...[Nn];
T ( *ptr  )[N2]...[Nn] = A;

For example taking the declaration from the question

int A[2][3];

you can rewrite it like

int ( A[2] )[3];

Now it is easy to declare a pointer to the first element of the array

int ( *ptr )[3] = A;

Dereferencing the pointer you get the first "row" of the type int[3] of the two-dimensional array

On the other hand, if you have a declaration of an array of pointers like

int * A[3];

which can be rewritten like

int * ( A[3] );

then to get a declaration of a pointer you can write

int * ( *ptr ) = A;

that is the same as

int **ptr = A;

So dereferencing the pointer you will get an object of the type int * that is in turn a pointer.

So for this declaration

int ( *ptr )[3] = A;

the pointed object is a one-dimensional array. For example you can write

std::cout << sizeof( *ptr ) << std::endl;

and you will get a value that is equal to sizeof( int[3] ) that is equal to 3 * sizeof( int )

As for this declaration

int * A[3];
int **ptr = A;

the pointed object is a pointer of the type int *. If to write for this pointer

std::cout << sizeof( *ptr ) << std::endl;

then you will get a value that is equal to sizeof( int * )

Let's consider this code snippet

int **ptr = new int *[2];
for( int i = 0; i < 2; i++ ) ptr[i] = new int[3];

In the first statement there is dynamically allocated a one-dimensional array of the type int *[2].

Then in the loop there are dynamically created 2 arrays of the type int[3] and pointers to first elements of the arrays are assigned to elements of the previously allocated one-dimensional array.

So in whole there are dynamically allocated 3 arrays: one of the type int *[2] and two of the type int [3]. That is there are allocated three separate extents of memory.

Instead you could write

int ( *ptr )[3] = new int[2][3];

In this case there is allocated dynamically only one two-dimensional array and the declared pointer ptr points to the first "row" of the array. That is there is allocated only one extent of memory.


问:
React-Native Local Notifications using Headless JS
I am trying to send local notifications in the react native for android. By googling i saw that one way is to use Headless JS, but does anyone know how it can be achieved exactly? And I need local notifications everyday at a specific time</p>

答:
you can achieve this by using

https://github.com/zo0r/react-native-push-notification#scheduled-notifications

https://github.com/zo0r/react-native-push-notification#repeating-notifications

```<code>PushNotification.localNotificationSchedule({
  message: "My Notification Message", // (required)
  date: new Date(Date.now() + (60 * 1000)) // in 60 secs
});
</code>```

Edit 1

```<code>PushNotification.localNotificationSchedule({
    message: "My Notification Message",
    date: new Date(fireDate),
    repeatType: 'time',
    repeatTime: 3600000
  });
</code>```

Body:
you can achieve this by using

https://github.com/zo0r/react-native-push-notification#scheduled-notifications

https://github.com/zo0r/react-native-push-notification#repeating-notifications

PushNotification.localNotificationSchedule({
  message: "My Notification Message", // (required)
  date: new Date(Date.now() + (60 * 1000)) // in 60 secs
});

Edit 1

PushNotification.localNotificationSchedule({
    message: "My Notification Message",
    date: new Date(fireDate),
    repeatType: 'time',
    repeatTime: 3600000
  });


问:
how to import export docker compose?
I am still new in docker and all container things.
I have server with full access at
1.1.1.1 and I installed docker there. (without docker compose)
In the other place my friend have server 2.2.2.2 and he installed docker and docker compose there.

At 2.2.2.2 server, my friend build 3 container : container A (Git), container B(unknown), container C(unknown).
I can access content of container A (Git) with browsers.

My question is: can I import container A to my server in 1.1.1.1? I have user access to download Git, but what I want is to import the container, not Git (content inside the container).
Any hint? what should I do? Or it is impossible to do if I don't have access to the command console?

答:
A running container can be exported into a tar archive which can be copied to a different machine and them be imported back.

On the machine where the container is running, do the following:

```<code>docker export --output "A.tar" <container-A>
</code>```

Next copy the generated archive A.tar to your machine, and import it:

```<code>docker import A.tar <container-A-image>
</code>```

This will create an image on your machine which can be then started using docker run ...

Title: how to import export docker compose?

Body:
A running container can be exported into a tar archive which can be copied to a different machine and them be imported back.

On the machine where the container is running, do the following:

docker export --output "A.tar" <container-A>

Next copy the generated archive A.tar to your machine, and import it:

docker import A.tar <container-A-image>

This will create an image on your machine which can be then started using docker run ...


问:
spring: Context initialization failed even after well defining the classpath

Hi Guys, i tried to shift servlet-context.xml from /WEB-INF/spring folder to src/main/resources -> XML -> servlet-context.xml as shown in the picture above

Also, changed the contextConfigLocation but i am still getting following set of errors.I am also attaching my xml files as follows:

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:XML/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

servlet-context.xml

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

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="in.hkcl.hipa" />

    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory" />
    </beans:bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <aop:aspectj-autoproxy />

    <mvc:annotation-driven />

    <beans:bean id="baseDataDao" class="in.hkcl.dao.impl.BaseDataDaoImpl"></beans:bean>

</beans:beans>
</code>```

Error-Log:

```<code>INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Tue Dec 05 15:26:11 PST 2017]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:612)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:513)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
    at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
    ... 25 more
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Tue Dec 05 15:26:11 PST 2017]; root of context hierarchy
WARN : org.springframework.web.context.support.XmlWebApplicationContext - Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext: startup date [Tue Dec 05 15:26:11 PST 2017]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:416)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:997)
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:956)
    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:581)
    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:116)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4776)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5390)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
</code>```

Plz help, i am a novice in this field.

答:
Since in your web.xml you are using the ContextLoaderListener class like this one:

```<code><listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</code>```

You should tell the ContextLoaderListener where to load the spring context files or it will try to load the applicationContext.xml file

You can do in this way:

```<code><context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    classpath:application-context.xml
</param-value>
</context-param>
</code>```

I hope this can be useful

Angelo

Body:
Hi Guys, i tried to shift servlet-context.xml from /WEB-INF/spring folder to src/main/resources -> XML -> servlet-context.xml as shown in the picture above

Also, changed the contextConfigLocation but i am still getting following set of errors.I am also attaching my xml files as follows:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:XML/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

servlet-context.xml

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

    <annotation-driven />

    <resources mapping="/resources/**" location="/resources/" />

    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="in.hkcl.hipa" />

    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory" />
    </beans:bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <aop:aspectj-autoproxy />

    <mvc:annotation-driven />

    <beans:bean id="baseDataDao" class="in.hkcl.dao.impl.BaseDataDaoImpl"></beans:bean>

</beans:beans>

Error-Log:

INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Tue Dec 05 15:26:11 PST 2017]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:612)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:513)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
    at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
    ... 25 more
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Tue Dec 05 15:26:11 PST 2017]; root of context hierarchy
WARN : org.springframework.web.context.support.XmlWebApplicationContext - Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext: startup date [Tue Dec 05 15:26:11 PST 2017]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:416)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:997)
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:956)
    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:581)
    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:116)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4776)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5390)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Plz help, i am a novice in this field.

Body:
Since in your web.xml you are using the ContextLoaderListener class like this one:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You should tell the ContextLoaderListener where to load the spring context files or it will try to load the applicationContext.xml file

You can do in this way:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    classpath:application-context.xml
</param-value>
</context-param>

I hope this can be useful

Angelo


问:
Proximity state not changing after receiving notification
I am having a problem with the proximity sensor on the iPhone. It seems that when the idle timer is disabled and the proximity monitoring is enabled the screen (sometimes) will turn on when receiving a notification. After this the proximity state is reported incorrectly and the screen won't turn off again.

I provided a sample project to illustrate the problem. But the steps to reproduce are quite simple. I tested this on multiple phones (4S, 5, 6, 6+) with multiple iOS versions (7.0.3 and 8.3). It seems to occur most reliably when the phone is not connected to a power source or debugger.

The code in my only ViewController is (the view is created in a storyboard):

```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var checkingToggleButton: UIButton!
    @IBOutlet weak var debugLabel: UILabel!
    @IBOutlet weak var screenDebugLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.checkingToggleButton.setTitle("Start checking", forState: UIControlState.Normal)
        self.debugLabel.text = "Not checking"

        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("proximityChanged:"), name: "UIDeviceProximityStateDidChangeNotification", object: nil)
    }

    @IBAction func handleCheckingToggle(sender: AnyObject) {

        let enabled = !UIDevice.currentDevice().proximityMonitoringEnabled
        if enabled {
            self.debugLabel.text = "Checking"
            self.checkingToggleButton.setTitle("Stop checking", forState: UIControlState.Normal)
        } else {
            self.debugLabel.text = "Not checking"
            self.checkingToggleButton.setTitle("Start checking", forState: UIControlState.Normal)
        }
        UIApplication.sharedApplication().idleTimerDisabled = enabled
        UIDevice.currentDevice().proximityMonitoringEnabled = enabled
    }

    func proximityChanged(notification:NSNotification)
    {
        if UIDevice.currentDevice().proximityState{
            self.screenDebugLabel.text = "Proximity true"
            println("Proximity true")
        } else {
            self.screenDebugLabel.text = "Proximity false"
            println("Proximity false")
        }
    }
}
</code>```

Steps to reproduce:

Build the provided sample project on a device and run the App on the the device disconnected from power and the debugger (this seems to make some difference).

Enable proximityMonitoring and disable the idle timer by pressing the "Start checking" button.

Cover the proximity sensor, this turns the screen off.

Wait approximately 2 minutes (this also makes a difference, doing it too soon won't reproduce the problem)

Send yourself a notification (for instance an iMessage)

The screen will turn on and won't turn off again. We also created a label that shows the current proximityState, the state is (incorrectly) reported as false.

Link to sample project on GitHub:
https://github.com/TimPelgrim/ProximityTest

答:
There is actually workaround..
UIDevice.current.proximityState is changing as it should change. but the problem is with the UIDeviceProximityStateDidChange notification.
So the workaround is to create timer that check every x time if UIDevice.current.proximityState changed and that it. just don't use UIDeviceProximityStateDidChange.

Body:
I am having a problem with the proximity sensor on the iPhone. It seems that when the idle timer is disabled and the proximity monitoring is enabled the screen (sometimes) will turn on when receiving a notification. After this the proximity state is reported incorrectly and the screen won't turn off again.

I provided a sample project to illustrate the problem. But the steps to reproduce are quite simple. I tested this on multiple phones (4S, 5, 6, 6+) with multiple iOS versions (7.0.3 and 8.3). It seems to occur most reliably when the phone is not connected to a power source or debugger.

The code in my only ViewController is (the view is created in a storyboard):

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var checkingToggleButton: UIButton!
    @IBOutlet weak var debugLabel: UILabel!
    @IBOutlet weak var screenDebugLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.checkingToggleButton.setTitle("Start checking", forState: UIControlState.Normal)
        self.debugLabel.text = "Not checking"

        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("proximityChanged:"), name: "UIDeviceProximityStateDidChangeNotification", object: nil)
    }

    @IBAction func handleCheckingToggle(sender: AnyObject) {

        let enabled = !UIDevice.currentDevice().proximityMonitoringEnabled
        if enabled {
            self.debugLabel.text = "Checking"
            self.checkingToggleButton.setTitle("Stop checking", forState: UIControlState.Normal)
        } else {
            self.debugLabel.text = "Not checking"
            self.checkingToggleButton.setTitle("Start checking", forState: UIControlState.Normal)
        }
        UIApplication.sharedApplication().idleTimerDisabled = enabled
        UIDevice.currentDevice().proximityMonitoringEnabled = enabled
    }

    func proximityChanged(notification:NSNotification)
    {
        if UIDevice.currentDevice().proximityState{
            self.screenDebugLabel.text = "Proximity true"
            println("Proximity true")
        } else {
            self.screenDebugLabel.text = "Proximity false"
            println("Proximity false")
        }
    }
}

Steps to reproduce:

Build the provided sample project on a device and run the App on the the device disconnected from power and the debugger (this seems to make some difference).

Enable proximityMonitoring and disable the idle timer by pressing the "Start checking" button.

Cover the proximity sensor, this turns the screen off.

Wait approximately 2 minutes (this also makes a difference, doing it too soon won't reproduce the problem)

Send yourself a notification (for instance an iMessage)

The screen will turn on and won't turn off again. We also created a label that shows the current proximityState, the state is (incorrectly) reported as false.

Link to sample project on GitHub:
https://github.com/TimPelgrim/ProximityTest


问:
Replacing keyword in string that is HTML page using Java
I have following string:

```<code><html>
<head><meta>...</meta><head>
<body>
   <div id="foo">
     Text I want to search & replace occurrences
     of keywords such as Foo or foo while ignoring case
   </div>
</body>
</html>
</code>```

What I want to end up with is:

```<code><html>
<head><meta>...</meta><head>
<body>
   <div id="foo">
     Text I want to search & replace occurrences
     of keywords such as <b>Foo</b> or <b>foo</b> while ignoring case
   </div>
</body>
</html>
</code>```

So pretty much I'd like to search for and replace foo with foo or Foo. It is important to retain the case of the string that is being replace but match it with keyword foo while ignoring the case of the matches.

Another important thing is that the replacement ignores all html tags and their content. Notice that
 stays like it is.

I drafted this but didn't test it yet

```<code> text = text.replace("(?i)"+keyword+"(?!([^<]+)?>)", "<b>"+keyword+"</b>");
</code>```

The problem with the above is that it doesn't remember the case of word that is being replaced and just puts in the keyword.

ContentLicense: CC BY-SA 2.5

Body:
I have following string:

<meta>...</meta>

     Text I want to search & replace occurrences
     of keywords such as Foo or foo while ignoring case

What I want to end up with is:

<meta>...</meta>

     Text I want to search & replace occurrences
     of keywords such as Foo or foo while ignoring case

So pretty much I'd like to search for and replace foo with foo or Foo. It is important to retain the case of the string that is being replace but match it with keyword foo while ignoring the case of the matches.

Another important thing is that the replacement ignores all html tags and their content. Notice that
 stays like it is.

I drafted this but didn't test it yet

 text = text.replace("(?i)"+keyword+"(?!([^<]+)?>)", ""+keyword+"");

The problem with the above is that it doesn't remember the case of word that is being replaced and just puts in the keyword.

Body: text.replaceAll("(?i)(" + keyword + ")(?!([^<]+)?>)", "<b>$1</b>")


答:
You need to put the context file as you mentioned it in web.xml file.
Usually context file should place under WEB-INF folder
So, do the following.

web.xml

```<code>....
<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
...
</code>```

Then put the servlet-context.xml file to WEB-INF folder

Title: spring: Context initialization failed even after well defining the classpath

Body:
You need to put the context file as you mentioned it in web.xml file.
Usually context file should place under WEB-INF folder
So, do the following.

web.xml

....
<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
...

Then put the servlet-context.xml file to WEB-INF folder


问:
Optimize sql Query which take too long to execute
The following sql query is taking to much to return a result

```<code>SELECT count(*)
FROM List_declarations
WHERE  Id_antenne IN (
   SELECT id
   FROM Service
   WHERE id_direction IN (
      SELECT id_dr
      FROM affectation_service_dr
      WHERE id_service = 15
   )
)
</code>```

How I can do better  ?

答:
Try this:

```<code>SELECT count(*)
FROM
  List_declarations d
  INNER JOIN Service
  ON d.Id_antenne = s.id

  INNER JOIN affectation_service_dr a
  s.id_direction = a.id_dr

WHERE
  a.id_service = 15
</code>```

it might make a difference, it might not (but it's generally a better way to write a query of this nature)

Of inestimable importance, is to ensure the following are indexed:

```<code>affectation_service_dr.id_service
Service.id_direction
List_declarations.Id_antenne
</code>```

If there are still performance issues that cannot be easily explained by a huge number of rows (e.g. it's taking 38s but it IS returning a count of 20348957389956845) then I recommend you modify your question to include the plan explanation ( https://dev.mysql.com/doc/workbench/en/wb-performance-explain.html )

Body:
The following sql query is taking to much to return a result

SELECT count(*)
FROM List_declarations
WHERE  Id_antenne IN (
   SELECT id
   FROM Service
   WHERE id_direction IN (
      SELECT id_dr
      FROM affectation_service_dr
      WHERE id_service = 15
   )
)

How I can do better  ?

Body:
Try this:

SELECT count(*)
FROM
  List_declarations d
  INNER JOIN Service
  ON d.Id_antenne = s.id

  INNER JOIN affectation_service_dr a
  s.id_direction = a.id_dr

WHERE
  a.id_service = 15

it might make a difference, it might not (but it's generally a better way to write a query of this nature)

Of inestimable importance, is to ensure the following are indexed:

affectation_service_dr.id_service
Service.id_direction
List_declarations.Id_antenne

If there are still performance issues that cannot be easily explained by a huge number of rows (e.g. it's taking 38s but it IS returning a count of 20348957389956845) then I recommend you modify your question to include the plan explanation ( https://dev.mysql.com/doc/workbench/en/wb-performance-explain.html )


问:
How can I store the text entered into a html textarea into a javascript variable?
I want to store the text users enter into a textarea in a website into a javascript variable in order to compare it to another variable already defined.

How would you do it? Any hints? Thanks in advance!

答:
Use following code

```<code>var textareaValue = document.getElementById('textAreadID').value
</code>```

Replace textAreadID with your textarea id.

Body:
Use following code

var textareaValue = document.getElementById('textAreadID').value

Replace textAreadID with your textarea id.


问:
OCaml directed graphs vertex module
I have seen some graphs vertex signatures and even come up with my own:

```<code>module type VERTEX = sig
    type t
    type label

    val equal : t -> t -> bool
    val create : label -> t
    val label : t -> label
end
</code>```

But I have completely no idea how to implement it as a module. What types should t and label be? How can I create a t based on a label? And how do I get the label from a t?

答:
Implementing a module based on a signature is like a mini puzzle. Here's how I would analyze it:

The first remark I have when reading that signature, is that there is no way in that signature to build values of type label. So, our implementation will need to be a bit larger, maybe by specifying type label = string.

Now, we have:

```<code>val create : label -> t
val label : t -> label
</code>```

Which is a bijection (the types are "equivalent"). The simplest way to implement that is by defining type t = label, so that it's really only one type, but from the exterior of the module you don't know that.

The rest is

```<code>type t
val equal: t -> t -> bool
</code>```

We said that label = string, and t = label. So t = string, and equal is the string equality.

Boom! here we are:

```<code>module String_vertex : VERTEX with type label = string = struct
  type label = string
  type t = string

  let equal = String.equal

  let create x = x
  let label x = x
end
</code>```

The VERTEX with type label = string part is just if you want to define it in the same file. Otherwise, you can do something like:

```<code>(* string_vertex.ml *)
type label = string
type t = string

let equal = String.equal

let create x = x
let label x = x
</code>```

and any functor F that takes a VERTEX can be called with F(String_vertex).
It would be best practice to create string_vertex.mli with contents include VERTEX with type label = string, though.

Title: OCaml directed graphs vertex module

Body:
I have seen some graphs vertex signatures and even come up with my own:

module type VERTEX = sig
    type t
    type label

    val equal : t -> t -> bool
    val create : label -> t
    val label : t -> label
end

But I have completely no idea how to implement it as a module. What types should t and label be? How can I create a t based on a label? And how do I get the label from a t?

Body:
Implementing a module based on a signature is like a mini puzzle. Here's how I would analyze it:

The first remark I have when reading that signature, is that there is no way in that signature to build values of type label. So, our implementation will need to be a bit larger, maybe by specifying type label = string.

Now, we have:

val create : label -> t
val label : t -> label

Which is a bijection (the types are "equivalent"). The simplest way to implement that is by defining type t = label, so that it's really only one type, but from the exterior of the module you don't know that.

The rest is

type t
val equal: t -> t -> bool

We said that label = string, and t = label. So t = string, and equal is the string equality.

Boom! here we are:

module String_vertex : VERTEX with type label = string = struct
  type label = string
  type t = string

  let equal = String.equal

  let create x = x
  let label x = x
end

The VERTEX with type label = string part is just if you want to define it in the same file. Otherwise, you can do something like:

(* string_vertex.ml *)
type label = string
type t = string

let equal = String.equal

let create x = x
let label x = x

and any functor F that takes a VERTEX can be called with F(String_vertex).
It would be best practice to create string_vertex.mli with contents include VERTEX with type label = string, though.


问:
Launch app from Android Studio stopped to work
There is very weird issue... One time I opened my project and noticed that I don't have opportunity to launch app from studio... Triangle sing cover with black color like it disable

But if I build the apk file and install it with adb command adb install -r path_to_apk it does work.

I have already tried to delete and download new android studio, but nothing changed...

And one more, if I am connecting my device and trying to attach debugger to android process so, android studio doesn't see my device as well as virtual device...

What I need to check? It look like some studio configuration broke or I don't know

Fell free to ask

My plugins

My configuration

答: Go to settings from file option available in android studio and check for necessary plugins that are required and after that make sure you installed plugins and then check your project.</p>


问:
Iteration over the dictionary and extracting values
I have a dictionary (result_dict) as follows.

```<code>{'11333216@N05': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 3,
   'iconserver': '2214',
   'id': '11333216@N05',
   'ispro': 0,
   'location': {'_content': ''},
   'mbox_sha1sum': {'_content': '8eb2e248cbad94e2b4a5aae75eb653c7e061a90c'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=11327876'},
   'nsid': '11333216@N05',
   'path_alias': 'kishansamarasinghe',
   'photos': {'count': {'_content': 442},
    'firstdate': {'_content': '1193073180'},
    'firstdatetaken': {'_content': '2000-01-01 00:49:17'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/kishansamarasinghe/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/kishansamarasinghe/'},
   'realname': {'_content': 'Kishan Samarasinghe'},
   'timezone': {'label': 'Sri Jayawardenepura',
    'offset': '+06:00',
    'timezone_id': 'Asia/Colombo'},
   'username': {'_content': 'Three Sixty Five Degrees'}},
  'stat': 'ok'},
 '117692977@N08': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '0',
   'iconfarm': 1,
   'iconserver': '404',
   'id': '117692977@N08',
   'ispro': 0,
   'location': {'_content': 'Almere, The Nederlands'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=117600164'},
   'nsid': '117692977@N08',
   'path_alias': 'meijsvo',
   'photos': {'count': {'_content': 3237},
    'firstdate': {'_content': '1392469161'},
    'firstdatetaken': {'_content': '2013-06-23 14:39:30'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/meijsvo/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/meijsvo/'},
   'realname': {'_content': 'Markéta Eijsvogelová'},
   'timezone': {'label': 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'offset': '+01:00',
    'timezone_id': 'Europe/Amsterdam'},
   'username': {'_content': 'meijsvo'}},
  'stat': 'ok'},
 '21539776@N02': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 0,
   'iconserver': '0',
</code>```

This contains more than 150 usernames (e.g. 11333216@N05) . I want to extract 'mobileurl' for each user and create a dataframe containing username and mobileurl columns. I couldn't find a way to iterate each user and extract his mobileurl as indexing is impossible. However, I have extract the mobileurl for one of the users as follows.

```<code>result_dict['76617062@N08']["person"]["mobileurl"]['_content']

'https://m.flickr.com/photostream.gne?id=76524249'
</code>```

Would be grateful if someone can help, as I'm a bit new to python.

答:
Iterate through the dictionarys list of keys which in this case are the usernames, then use each one to access each top level dict and from there dive through all the other layers to find the exact data you need. The mobileurl in your example.

Once you have these 2 variables, add them to your dataframe.

```<code># Iterate through list of users
for user in result_dict.keys():

    # use each username to find the mobileurl you need within
    mobileurl = result_dict[user]["person"]["mobileurl"]["_content"]

    # Add the variables 'user' and 'mobileurl' to dataframe as you see fit
</code>```

Body:
I have a dictionary (result_dict) as follows.

{'11333216@N05': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 3,
   'iconserver': '2214',
   'id': '11333216@N05',
   'ispro': 0,
   'location': {'_content': ''},
   'mbox_sha1sum': {'_content': '8eb2e248cbad94e2b4a5aae75eb653c7e061a90c'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=11327876'},
   'nsid': '11333216@N05',
   'path_alias': 'kishansamarasinghe',
   'photos': {'count': {'_content': 442},
    'firstdate': {'_content': '1193073180'},
    'firstdatetaken': {'_content': '2000-01-01 00:49:17'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/kishansamarasinghe/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/kishansamarasinghe/'},
   'realname': {'_content': 'Kishan Samarasinghe'},
   'timezone': {'label': 'Sri Jayawardenepura',
    'offset': '+06:00',
    'timezone_id': 'Asia/Colombo'},
   'username': {'_content': 'Three Sixty Five Degrees'}},
  'stat': 'ok'},
 '117692977@N08': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '0',
   'iconfarm': 1,
   'iconserver': '404',
   'id': '117692977@N08',
   'ispro': 0,
   'location': {'_content': 'Almere, The Nederlands'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=117600164'},
   'nsid': '117692977@N08',
   'path_alias': 'meijsvo',
   'photos': {'count': {'_content': 3237},
    'firstdate': {'_content': '1392469161'},
    'firstdatetaken': {'_content': '2013-06-23 14:39:30'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/meijsvo/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/meijsvo/'},
   'realname': {'_content': 'Markéta Eijsvogelová'},
   'timezone': {'label': 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'offset': '+01:00',
    'timezone_id': 'Europe/Amsterdam'},
   'username': {'_content': 'meijsvo'}},
  'stat': 'ok'},
 '21539776@N02': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 0,
   'iconserver': '0',

This contains more than 150 usernames (e.g. 11333216@N05) . I want to extract 'mobileurl' for each user and create a dataframe containing username and mobileurl columns. I couldn't find a way to iterate each user and extract his mobileurl as indexing is impossible. However, I have extract the mobileurl for one of the users as follows.

result_dict['76617062@N08']["person"]["mobileurl"]['_content']

'https://m.flickr.com/photostream.gne?id=76524249'

Would be grateful if someone can help, as I'm a bit new to python.

Body:
Iterate through the dictionarys list of keys which in this case are the usernames, then use each one to access each top level dict and from there dive through all the other layers to find the exact data you need. The mobileurl in your example.

Once you have these 2 variables, add them to your dataframe.

# Iterate through list of users
for user in result_dict.keys():

    # use each username to find the mobileurl you need within
    mobileurl = result_dict[user]["person"]["mobileurl"]["_content"]

    # Add the variables 'user' and 'mobileurl' to dataframe as you see fit


问:
Loop through column A and copy values in matching sheet on different workbook
I have 2 workbooks, where workbook 1 has a list of names in column A and each name has a row of values.
Workbook 2 has worksheets labeled with names as well. Some of these name are the same as the list of names in column A of workbook 1.

What I am trying to achieve is to check if the name in column A matches the worksheet name. If yes, I want to copy the values in that row and paste them into specific cells in the sheet on workbook 2.
The code I have below works fine if every name in column A has a corresponding sheet in workbook 2 in the same order. However, I want it to be able to skip blank spaces or skip names that do not have a sheet in workbook 2. So I have added an if statement to see if that solves the problem, but that did not work. I'm getting the error: 'Application-defined or object-defined error', highlighting the if statement.

The original working code didn't have the IF statement. It worked as long as there were no spaces in the column A and every single name had a matching sheet in the same order.

I have also tried adding the error resume next lines but that just stopped triggering the error code. It copy/pasted the first row into the correct cells, but then nothing for the rest.

```<code>Sub Measures()

Dim wb1 As Workbook
Dim Sht As Worksheet
Dim Rng, Rng2 As Range
Dim wb2 As Workbook
Dim cell As Range
Dim ws As Worksheet

Set wb1 = ThisWorkbook
Set wb2 = Workbooks("November Stream 1 v2.xlsm")
Set Sht = wb1.Worksheets("Summary")
Set Rng = Sht.Range("A7:A" & Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row)

For Each cell In Rng
Set ws = wb2.Sheets(cell.Text)

If wb1.Sheets("Summary").Range("A" & i) = wb2.Sheet.Name Then

   Select Case ws.Range("A4").Value
        Case "green"  '
        ws.Range("B29").Value = cell.Offset(0, 1).Value
        ws.Range("B33").Value = cell.Offset(0, 2).Value
        ws.Range("B37").Value = cell.Offset(0, 3).Value
        ws.Range("B40").Value = cell.Offset(0, 4).Value
        ws.Range("B44").Value = cell.Offset(0, 5).Value

        Case "red"
        ws.Range("B47").Value = cell.Offset(0, 6).Value
        ws.Range("B51").Value = cell.Offset(0, 7).Value
        ws.Range("B54").Value = cell.Offset(0, 8).Value
        ws.Range("B60").Value = cell.Offset(0, 9).Value
        ws.Range("B65").Value = cell.Offset(0, 11).Value

        Case "blue"
        ws.Range("B68").Value = cell.Offset(0, 12).Value
        ws.Range("B74").Value = cell.Offset(0, 14).Value
        ws.Range("B76").Value = cell.Offset(0, 15).Value
      End Select
        End If

    Next cell

End Sub
</code>```

答:
I think what you want to be testing for is sheet existence rather then whether the sheet matches the name that you set it to. Have a look at the following, I've tidied it up a bit and used error handling to 'test' if the sheet that you set the name to exists</p>

```<code>Sub Measures()
    Dim wb2 As Workbook
    Dim ws As Worksheet
    Dim Rng, Rng2 As Range
    Dim cell

    Set wb2 = Workbooks("November Stream 1 v2.xlsm")
    With ThisWorkbook.Worksheets("Summary")
        Set Rng = .Range("A7:A" & .cells(.Rows.Count, "A").End(xlUp).Row)
    End With

    For Each cell In Rng
        On Error Resume Next
        Set ws = Nothing
        Set ws = wb2.Sheets(cell.Value2)
        On Error GoTo 0

        If Not ws Is Nothing Then
            Select Case ws.Range("A4").Value2
                Case "green"
                    ws.Range("B29").Value = cell.Offset(0, 1).Value
                    ws.Range("B33").Value = cell.Offset(0, 2).Value
                    ws.Range("B37").Value = cell.Offset(0, 3).Value
                    ws.Range("B40").Value = cell.Offset(0, 4).Value
                    ws.Range("B44").Value = cell.Offset(0, 5).Value

                Case "red"
                    ws.Range("B47").Value = cell.Offset(0, 6).Value
                    ws.Range("B51").Value = cell.Offset(0, 7).Value
                    ws.Range("B54").Value = cell.Offset(0, 8).Value
                    ws.Range("B60").Value = cell.Offset(0, 9).Value
                    ws.Range("B65").Value = cell.Offset(0, 11).Value

                Case "blue"
                    ws.Range("B68").Value = cell.Offset(0, 12).Value
                    ws.Range("B74").Value = cell.Offset(0, 14).Value
                    ws.Range("B76").Value = cell.Offset(0, 15).Value
            End Select
        End If
    Next cell
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 2 workbooks, where workbook 1 has a list of names in column A and each name has a row of values.
Workbook 2 has worksheets labeled with names as well. Some of these name are the same as the list of names in column A of workbook 1.

What I am trying to achieve is to check if the name in column A matches the worksheet name. If yes, I want to copy the values in that row and paste them into specific cells in the sheet on workbook 2.
The code I have below works fine if every name in column A has a corresponding sheet in workbook 2 in the same order. However, I want it to be able to skip blank spaces or skip names that do not have a sheet in workbook 2. So I have added an if statement to see if that solves the problem, but that did not work. I'm getting the error: 'Application-defined or object-defined error', highlighting the if statement.

The original working code didn't have the IF statement. It worked as long as there were no spaces in the column A and every single name had a matching sheet in the same order.

I have also tried adding the error resume next lines but that just stopped triggering the error code. It copy/pasted the first row into the correct cells, but then nothing for the rest.

Sub Measures()

Dim wb1 As Workbook
Dim Sht As Worksheet
Dim Rng, Rng2 As Range
Dim wb2 As Workbook
Dim cell As Range
Dim ws As Worksheet

Set wb1 = ThisWorkbook
Set wb2 = Workbooks("November Stream 1 v2.xlsm")
Set Sht = wb1.Worksheets("Summary")
Set Rng = Sht.Range("A7:A" & Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row)

For Each cell In Rng
Set ws = wb2.Sheets(cell.Text)

If wb1.Sheets("Summary").Range("A" & i) = wb2.Sheet.Name Then

   Select Case ws.Range("A4").Value
        Case "green"  '
        ws.Range("B29").Value = cell.Offset(0, 1).Value
        ws.Range("B33").Value = cell.Offset(0, 2).Value
        ws.Range("B37").Value = cell.Offset(0, 3).Value
        ws.Range("B40").Value = cell.Offset(0, 4).Value
        ws.Range("B44").Value = cell.Offset(0, 5).Value

        Case "red"
        ws.Range("B47").Value = cell.Offset(0, 6).Value
        ws.Range("B51").Value = cell.Offset(0, 7).Value
        ws.Range("B54").Value = cell.Offset(0, 8).Value
        ws.Range("B60").Value = cell.Offset(0, 9).Value
        ws.Range("B65").Value = cell.Offset(0, 11).Value

        Case "blue"
        ws.Range("B68").Value = cell.Offset(0, 12).Value
        ws.Range("B74").Value = cell.Offset(0, 14).Value
        ws.Range("B76").Value = cell.Offset(0, 15).Value
      End Select
        End If

    Next cell

End Sub

Body:
I think what you want to be testing for is sheet existence rather then whether the sheet matches the name that you set it to. Have a look at the following, I've tidied it up a bit and used error handling to 'test' if the sheet that you set the name to exists

Sub Measures()
    Dim wb2 As Workbook
    Dim ws As Worksheet
    Dim Rng, Rng2 As Range
    Dim cell

    Set wb2 = Workbooks("November Stream 1 v2.xlsm")
    With ThisWorkbook.Worksheets("Summary")
        Set Rng = .Range("A7:A" & .cells(.Rows.Count, "A").End(xlUp).Row)
    End With

    For Each cell In Rng
        On Error Resume Next
        Set ws = Nothing
        Set ws = wb2.Sheets(cell.Value2)
        On Error GoTo 0

        If Not ws Is Nothing Then
            Select Case ws.Range("A4").Value2
                Case "green"
                    ws.Range("B29").Value = cell.Offset(0, 1).Value
                    ws.Range("B33").Value = cell.Offset(0, 2).Value
                    ws.Range("B37").Value = cell.Offset(0, 3).Value
                    ws.Range("B40").Value = cell.Offset(0, 4).Value
                    ws.Range("B44").Value = cell.Offset(0, 5).Value

                Case "red"
                    ws.Range("B47").Value = cell.Offset(0, 6).Value
                    ws.Range("B51").Value = cell.Offset(0, 7).Value
                    ws.Range("B54").Value = cell.Offset(0, 8).Value
                    ws.Range("B60").Value = cell.Offset(0, 9).Value
                    ws.Range("B65").Value = cell.Offset(0, 11).Value

                Case "blue"
                    ws.Range("B68").Value = cell.Offset(0, 12).Value
                    ws.Range("B74").Value = cell.Offset(0, 14).Value
                    ws.Range("B76").Value = cell.Offset(0, 15).Value
            End Select
        End If
    Next cell
End Sub


问:
How can i use requestBody to upload an image as binary in phoenix/Elixir
So far i have been using

```<code>    swagger_path :create_tag do
    post "/tag"
    produces "application/json"
    description "register Tags"
    consumes "multipart/form-data"
    parameters do
    image :formData, :file,  "The file to upload.", required: true
    end
    response 200, "Success"
end
</code>```

However i would like to use requestBody to get the binary data of the image, with above i am getting the image path, and have to work on Plug.Upload in controller.

would like to know the syntax using the requestBody of swagger in phoenix

答:
Binary file uploads are not supported in the swagger 2.0 spec used in phoenix_swagger:

Uploads where the payload is just the raw file contents are not supported in Swagger 2.0, because they are not multipart/form-data. That is, Swagger 2.0 does not support something like:

```<code>curl --upload-file archive.zip http://example.com/upload
</code>```

The open_api_spex package targets swagger 3.0, which supports binary requestBody operations.

Body:
So far i have been using

    swagger_path :create_tag do
    post "/tag"
    produces "application/json"
    description "register Tags"
    consumes "multipart/form-data"
    parameters do
    image :formData, :file,  "The file to upload.", required: true
    end
    response 200, "Success"
end

However i would like to use requestBody to get the binary data of the image, with above i am getting the image path, and have to work on Plug.Upload in controller.

would like to know the syntax using the requestBody of swagger in phoenix

Body:
Binary file uploads are not supported in the swagger 2.0 spec used in phoenix_swagger:

Uploads where the payload is just the raw file contents are not supported in Swagger 2.0, because they are not multipart/form-data. That is, Swagger 2.0 does not support something like:

curl --upload-file archive.zip http://example.com/upload

The open_api_spex package targets swagger 3.0, which supports binary requestBody operations.


答:
In jQuery:</p>

```<code>var str = "compare with me",
value = $('textarea[name="yourareaname"]').val();

if(str == value) {
    alert('hell yeah');
}
</code>```

Title: How can I store the text entered into a html textarea into a javascript variable?

Body:
I want to store the text users enter into a textarea in a website into a javascript variable in order to compare it to another variable already defined.

How would you do it? Any hints? Thanks in advance!

Body:
In jQuery:

var str = "compare with me",
value = $('textarea[name="yourareaname"]').val();

if(str == value) {
    alert('hell yeah');
}


问:
Logback config in tomcat
I'm running two web applications in a Tomcat 7.

The Tomcat has a logback-access.xml, which defines two appenders.

I can see that it's being picked up when starting tomcat, and the appender config is parsed correctly.

My question is, how do I let the webapp use the appenders defined in there?

I tried putting <logger> and <root> elements in the logback-access file, but that generates an error:

no applicable action for [logger], current ElementPath  is [[configuration][logger]]

, and similar for root and appender-ref.

I tried putting a logback.xml file in my war files, both WEB-INF/classes and just WEB-INF, but it doesn't seem to be picked up.

So, how am I supposed to properly configure this?

The logback-access.xml in Tomcat:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <append>true</append>
        <file>${catalina.base}/logs/my=app.log</file>
        <encoder>
            <pattern>combined</pattern>
        </encoder>
    </appender>

    <appender name="STASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>localhost:5044</destination>

        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>

            </providers>
        </encoder>
    </appender>
</configuration>
```

<p>The <code>logback.xml</code> in <code>WEB-INF/classes</code>:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <logger name="my.package" level="DEBUG"/>
    <logger name="com.amazonaws" level="INFO"/>
<!-- and several more loggers like this -->

    <root level="DEBUG">
        <appender-ref ref="FILE"/>
    </root>
    <root level="TRACE">
        <appender-ref ref="STASH"/>
    </root>
</configuration>
</code>```

答:
I'll just leave this here if someone has similar problems.

First of all, you don't need a logback-access.xml or Valve in tomcat's server.xml at all. Log incoming requests using filters in your app.

Then, if you need your appender(s) to be configured on the server instead of in the app, design a single logback.xml and put it in tomcat's lib folder (usually /usr/share/java/tomcat). You won't need a logback.xml in your app(s). The logback-common jar can be either in your war, or in the tomcat lib folder, whichever you prefer.

This way, the app will find the generic logback.xml on the tomcat shared classpath, and use that as if it were included in the war.

Title: Logback config in tomcat

Body:
I'm running two web applications in a Tomcat 7.

The Tomcat has a logback-access.xml, which defines two appenders.

I can see that it's being picked up when starting tomcat, and the appender config is parsed correctly.

My question is, how do I let the webapp use the appenders defined in there?

I tried putting <logger> and <root> elements in the logback-access file, but that generates an error:

no applicable action for [logger], current ElementPath  is [[configuration][logger]]

, and similar for root and appender-ref.

I tried putting a logback.xml file in my war files, both WEB-INF/classes and just WEB-INF, but it doesn't seem to be picked up.

So, how am I supposed to properly configure this?

The logback-access.xml in Tomcat:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <append>true</append>
        <file>${catalina.base}/logs/my=app.log</file>
        <encoder>
            <pattern>combined</pattern>
        </encoder>
    </appender>

    <appender name="STASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>localhost:5044</destination>

        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>

            </providers>
        </encoder>
    </appender>
</configuration>

The logback.xml in WEB-INF/classes:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <logger name="my.package" level="DEBUG"/>
    <logger name="com.amazonaws" level="INFO"/>

    <root level="DEBUG">
        <appender-ref ref="FILE"/>
    </root>
    <root level="TRACE">
        <appender-ref ref="STASH"/>
    </root>
</configuration>


答:
Use HAVING and GROUP BY

```<code>SELECT MIN(id) id, object_id, MIN(status_val) status_val
FROM yourtable
GROUP BY object_id
HAVING COUNT(object_id) = 1
</code>```

Output

```<code>id  object_id status_val
4   2         0
5   3         0
</code>```

SQL Fiddle: http://sqlfiddle.com/#!6/7f643f/9/0

Body:
I have a SQL Server table that has duplicate entries in one of the columns  e.g.:

  +----+-----------+------------+
  | id | object_id | status_val |
  +----+-----------+------------+
  |  1 |         1 |          0 |
  |  2 |         1 |          0 |
  |  3 |         1 |          0 |
  |  4 |         2 |          0 |
  |  5 |         3 |          0 |
  |  6 |         4 |          0 |
  |  7 |         4 |          0 |
  +----+-----------+------------+

I need the output to be like this:

  +----+-----------+------------+
  | id | object_id | status_val |
  +----+-----------+------------+
  |  4 |         2 |          0 |
  |  5 |         3 |          0 |
  +----+-----------+------------+

How to resolve this?

Body:
Use HAVING and GROUP BY

SELECT MIN(id) id, object_id, MIN(status_val) status_val
FROM yourtable
GROUP BY object_id
HAVING COUNT(object_id) = 1

Output

id  object_id status_val
4   2         0
5   3         0

SQL Fiddle: http://sqlfiddle.com/#!6/7f643f/9/0


问:
How do I call a database function using SQLAlchemy in Flask?
I want to call a function that I created in my PostgreSQL database. I've looked at the official SQLAlchemy documentation as well as several questions here on SO, but nobody seems to explain how to set up the function in SQLAlchemy.

I did find this question, but am unsure how to compile the function as the answer suggests. Where does that code go? I get errors when I try to put this in both my view and model scripts.

Edit 1 (8/11/2016)

As per the community's requests and requirements, here are all the details I left out:

I have a table called books whose columns are arranged with information regarding the general book (title, author(s), publication date...).

I then have many tables all of the same kind whose columns contain information regarding all the chapters in each book (chapter name, length, short summary...). It is absolutely necessary for each book to have its own table. I have played around with one large table of all the chapters, and found it ill suited to my needs, not too mention extremely unwieldy.

My function that I'm asking about queries the table of books for an individual book's name, and casts the book's name to a regclass. It then queries the regclass object for all its data, returns all the rows as a table like the individual book tables, and exits. Here's the raw code:

```<code>CREATE OR REPLACE FUNCTION public.get_book(bookName character varying)
 RETURNS TABLE(/*columns of individual book table go here*/)
 LANGUAGE plpgsql
AS $function$
declare
    _tbl regclass;
begin
    for _tbl in
        select name::regclass
        from books
        where name=bookName
    loop
        return query execute '
        select * from ' ||_tbl;
    end loop;
end;
$function$
</code>```

This function has been tested several times in both the command line and pgAdmin. It works as expected.

My intention is to have a view in my Flask app whose route is @app.route('/book/<string:bookName>') and calls the above function before rendering the template. The exact view is as follows:

```<code>@app.route('/book/<string:bookName>')
def book(bookName):
  chapterList = /*call function here*/
  return render_template('book.html', book=bookName, list=chapterList)
</code>```

This is my question: how do I set up my app in such a way that SQLAlchemy knows about and can call the function I have in my database? I am open to other suggestions of achieving the same result as well.

P.S. I only omitted this information with the intention of keeping my question as abstract as possible, not knowing that the rules of the forum dictate a requirement for a very specific question. Please forgive me my lack of knowledge.

答:
If you want to do it without raw sql, you can use func from sqlalchemy:

```<code>from sqlalchemy import func

data = db.session.query(func.your_schema.your_function_name()).all()
</code>```

Body:
I want to call a function that I created in my PostgreSQL database. I've looked at the official SQLAlchemy documentation as well as several questions here on SO, but nobody seems to explain how to set up the function in SQLAlchemy.

I did find this question, but am unsure how to compile the function as the answer suggests. Where does that code go? I get errors when I try to put this in both my view and model scripts.

Edit 1 (8/11/2016)

As per the community's requests and requirements, here are all the details I left out:

I have a table called books whose columns are arranged with information regarding the general book (title, author(s), publication date...).

I then have many tables all of the same kind whose columns contain information regarding all the chapters in each book (chapter name, length, short summary...). It is absolutely necessary for each book to have its own table. I have played around with one large table of all the chapters, and found it ill suited to my needs, not too mention extremely unwieldy.

My function that I'm asking about queries the table of books for an individual book's name, and casts the book's name to a regclass. It then queries the regclass object for all its data, returns all the rows as a table like the individual book tables, and exits. Here's the raw code:

CREATE OR REPLACE FUNCTION public.get_book(bookName character varying)
 RETURNS TABLE(/*columns of individual book table go here*/)
 LANGUAGE plpgsql
AS $function$
declare
    _tbl regclass;
begin
    for _tbl in
        select name::regclass
        from books
        where name=bookName
    loop
        return query execute '
        select * from ' ||_tbl;
    end loop;
end;
$function$

This function has been tested several times in both the command line and pgAdmin. It works as expected.

My intention is to have a view in my Flask app whose route is @app.route('/book/<string:bookName>') and calls the above function before rendering the template. The exact view is as follows:

@app.route('/book/<string:bookName>')
def book(bookName):
  chapterList = /*call function here*/
  return render_template('book.html', book=bookName, list=chapterList)

This is my question: how do I set up my app in such a way that SQLAlchemy knows about and can call the function I have in my database? I am open to other suggestions of achieving the same result as well.

P.S. I only omitted this information with the intention of keeping my question as abstract as possible, not knowing that the rules of the forum dictate a requirement for a very specific question. Please forgive me my lack of knowledge.

Body:
If you want to do it without raw sql, you can use func from sqlalchemy:

from sqlalchemy import func

data = db.session.query(func.your_schema.your_function_name()).all()


问:
PHP Regular Expression to match `name[50]` to the "name" and "50" values
I'm looking for some more regular expression help, to work with the PHP function preg_match. I need to match the following strings;

string[50]

string

Ideally the array returned would be something like this;

string, 50

string

Any help would be appreciated :-)
This was what I came up with but it doesn't remotely do what I expected with my little regex knowledge! /([a-z])+(\[[0-9]\])?/i

答:
You need to put the + within the () (otherwise you'll match the full string only the last character of the string will be in the result group). Also add another + after [0-9]. Move the \[\] outside the () to return only 50 (not [50]) and use (?:)? to make the [50] optional without yielding a group.

```<code>/([a-z]+)(?:\[([0-9]+)\])?/i
</code>```

Play with it on rubular

Body:
You need to put the + within the () (otherwise you'll match the full string only the last character of the string will be in the result group). Also add another + after [0-9]. Move the \[\] outside the () to return only 50 (not [50]) and use (?:)? to make the [50] optional without yielding a group.

/([a-z]+)(?:\[([0-9]+)\])?/i

Play with it on rubular


问:
Null array of buttons supposed to be set
I don't understand why in my code I get a :

null reference object

when i try to click on my buttons.

```<code>buttonMenuOption = findViewById(R.id.buttonOption);
Button[] buttonsOption = new Button[nbObjects];
buttonsOption[0] = findViewById(R.id.buttonOption0);
buttonsOption[1] = findViewById(R.id.buttonOption1);
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        setContentView(R.layout.graph_option);
            for (int i = 0; i < nbObjects; i++) {
                final int j = i;
                    buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            //Do stuff
                          }
                    });
             }
     });
</code>```

To resume my code, there is an option button in my main activity, when I press it, it changes the layout then there are multiples buttons to activate a color picker.

Why is my buttonsOption[0] a null reference?

Update

```<code>buttonMenuOption = findViewById(R.id.buttonOption)
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
     setContentView(R.layout.graph_option);
     Button[] buttonsOption = new Button[nbObjects];
        for (int i = 0; i < nbObjects; i++) {
            final int j = i;
            buttonsOption[0] = findViewById(R.id.buttonOption0);
            buttonsOption[1] = findViewById(R.id.buttonOption1);
            buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //Do stuff
                      }
                });
         }
 });
</code>```

答:
You are using findViewById before you setContentView(), there is no view to find other view in. You need to first set your XML as your activity's view then you can call findViewById

Or you can do things a bit differently, like that

```<code>buttonMenuOption = findViewById(R.id.buttonOption);
Button[] buttonsOption = new Button[nbObjects];
final View newContentView = LayoutInflater.from(this).inflate(R.layout.graph_option, null);
buttonsOption[0] = newContentView.findViewById(R.id.buttonOption0);
buttonsOption[1] = newContentView.findViewById(R.id.buttonOption1);
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        setContentView(newContentView);
            for (int i = 0; i < nbObjects; i++) {
                final int j = i;
                    buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            //Do stuff
                          }
                    });
             }
     });
</code>```

Body:
I don't understand why in my code I get a :

null reference object

when i try to click on my buttons.

buttonMenuOption = findViewById(R.id.buttonOption);
Button[] buttonsOption = new Button[nbObjects];
buttonsOption[0] = findViewById(R.id.buttonOption0);
buttonsOption[1] = findViewById(R.id.buttonOption1);
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        setContentView(R.layout.graph_option);
            for (int i = 0; i < nbObjects; i++) {
                final int j = i;
                    buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            //Do stuff
                          }
                    });
             }
     });

To resume my code, there is an option button in my main activity, when I press it, it changes the layout then there are multiples buttons to activate a color picker.

Why is my buttonsOption[0] a null reference?

Update

buttonMenuOption = findViewById(R.id.buttonOption)
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
     setContentView(R.layout.graph_option);
     Button[] buttonsOption = new Button[nbObjects];
        for (int i = 0; i < nbObjects; i++) {
            final int j = i;
            buttonsOption[0] = findViewById(R.id.buttonOption0);
            buttonsOption[1] = findViewById(R.id.buttonOption1);
            buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //Do stuff
                      }
                });
         }
 });

Body:
You are using findViewById before you setContentView(), there is no view to find other view in. You need to first set your XML as your activity's view then you can call findViewById

Or you can do things a bit differently, like that

buttonMenuOption = findViewById(R.id.buttonOption);
Button[] buttonsOption = new Button[nbObjects];
final View newContentView = LayoutInflater.from(this).inflate(R.layout.graph_option, null);
buttonsOption[0] = newContentView.findViewById(R.id.buttonOption0);
buttonsOption[1] = newContentView.findViewById(R.id.buttonOption1);
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        setContentView(newContentView);
            for (int i = 0; i < nbObjects; i++) {
                final int j = i;
                    buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            //Do stuff
                          }
                    });
             }
     });


问:
Prolog, find friend of friend
I'm new to Prolog. I'm trying to write a query to check if a person is the friend or friend of friend of another person.

I have some facts like this:

```<code>friends(joe, [john, ann, pete, ellen,
          maria, jose, bruno, ali, jing, yang]).
friends(john, [rick]).
friends(ellen, [mia, xing, jun, maria]).
friends(maria, [pete, ellen, zhang, jose, serena]).
friends(serena, [ali, rick, zhang, mia]).
friends(jose, [maria, jose, bruno, ali, jing]).
</code>```

My target is to write a query like this:

```<code>visible(joe, ann).
true
</code>```

I have made something like this:

```<code>visible(X,Y) :- friends(X,[Y|T]); member(Y,T).
visible(X,Y) :- visible(X,Z), visible(Z,Y).

member(X,[X|T]).
member(X,[H|T]) :- member(X,T).
</code>```

But it becomes an infinite loop. I don't know how to write the base case.

The relationship is a graph with loop. Is there anyway to recursively find the friend of friend, transitively?

答:
```<code>visible(X,Y):- friends(X,YS), member(Y,YS).
visible(X,Y):- friends(X,XF), friends(Y,YF), member(Z,XF), member(Z,YF).
</code>```

The first line checks if two people are directly friends (Y is in the list of friends of X). The second line checks if two peolpe are friend of friends (an element Z is both in the list of friends of X and Y. If you also want to know wich is the friend in common you could add write(Z)). In this case, for instance, joe is friend of john but no viceversa. If you want also this property you should add

```<code>visible(X,Y):- friends(Y,XS), member(X,XS).
</code>```

Queries:

```<code>?-visible(john,serena).
true.

?-visible(joe,john).
true.

?-visible(john,joe).
true. (only if you add the third line of code).
</code>```

Title: Prolog, find friend of friend

Body:
I'm new to Prolog. I'm trying to write a query to check if a person is the friend or friend of friend of another person.

I have some facts like this:

friends(joe, [john, ann, pete, ellen,
          maria, jose, bruno, ali, jing, yang]).
friends(john, [rick]).
friends(ellen, [mia, xing, jun, maria]).
friends(maria, [pete, ellen, zhang, jose, serena]).
friends(serena, [ali, rick, zhang, mia]).
friends(jose, [maria, jose, bruno, ali, jing]).

My target is to write a query like this:

visible(joe, ann).
true

I have made something like this:

visible(X,Y) :- friends(X,[Y|T]); member(Y,T).
visible(X,Y) :- visible(X,Z), visible(Z,Y).

member(X,[X|T]).
member(X,[H|T]) :- member(X,T).

But it becomes an infinite loop. I don't know how to write the base case.

The relationship is a graph with loop. Is there anyway to recursively find the friend of friend, transitively?

Body:
visible(X,Y):- friends(X,YS), member(Y,YS).
visible(X,Y):- friends(X,XF), friends(Y,YF), member(Z,XF), member(Z,YF).

The first line checks if two people are directly friends (Y is in the list of friends of X). The second line checks if two peolpe are friend of friends (an element Z is both in the list of friends of X and Y. If you also want to know wich is the friend in common you could add write(Z)). In this case, for instance, joe is friend of john but no viceversa. If you want also this property you should add

visible(X,Y):- friends(Y,XS), member(X,XS).

Queries:

?-visible(john,serena).
true.

?-visible(joe,john).
true.

?-visible(john,joe).
true. (only if you add the third line of code).