问:
Reformatting Dates By using Java
This is the question i got in an online interview test

Output format is like

20th Oct 2052 converts to 2052-10-20.

6th Jun 1933 converts to 1933-06-06.

Can any one please write a method to return an array of strings where each index i contains the value of dates converted to the format YYYY-MM-DD.

This is the code to Convert 1st March 1984 to 1984-03-01 By using Java

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormattingTest {

 public void date(String dateString) throws ParseException {

  // This Regular Expression will replace st to blank
  String dateString1 = dateString.replaceFirst("[a-zA-Z]{2}", "");
  //create Date Format and Parse it based on input

  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d MMMM yyyy");
  Date rightNow = simpleDateFormat.parse(dateString1);

  // Now create Date format for output type. and format the input
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  String formattedDate = dateFormat.format(rightNow);
  System.out.println(formattedDate);
 }

 public static void main(String[] args) throws ParseException {
  String dateString = "1st March 1984";
  DateFormattingTest t = new DateFormattingTest();
  t.date(dateString);
 }
}
</code>```

In the above code  input is hard coded  String dateString = "1st March 1984";
it gives the correct output

But according to the question input should be array of strings in the form of  Day Month Year and out put should return an array of strings in the format YYYY-MM-DD. I wrote the dates() method similar to the date() method in the above code. in the solution main method handling IOException it is pre written main method we are supposed to pass our method in main method to return the output but here my method is handling ParseException which is not handled by main method in the given program so i am getting  ParseException handling error so is there any other way of writing function to give the output

答: "d MMMM yyyy" requires month in local language, try to set SimpleDateFormat's Locale to English. Also, theres no need to delete "st", try "d'st' MMMM yyyy"

Title: Reformatting Dates By using Java

Body:
This is the question i got in an online interview test

Output format is like

20th Oct 2052 converts to 2052-10-20.

6th Jun 1933 converts to 1933-06-06.

Can any one please write a method to return an array of strings where each index i contains the value of dates converted to the format YYYY-MM-DD.

This is the code to Convert 1st March 1984 to 1984-03-01 By using Java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormattingTest {

 public void date(String dateString) throws ParseException {

  // This Regular Expression will replace st to blank
  String dateString1 = dateString.replaceFirst("[a-zA-Z]{2}", "");
  //create Date Format and Parse it based on input

  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d MMMM yyyy");
  Date rightNow = simpleDateFormat.parse(dateString1);

  // Now create Date format for output type. and format the input
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  String formattedDate = dateFormat.format(rightNow);
  System.out.println(formattedDate);
 }

 public static void main(String[] args) throws ParseException {
  String dateString = "1st March 1984";
  DateFormattingTest t = new DateFormattingTest();
  t.date(dateString);
 }
}

In the above code  input is hard coded  String dateString = "1st March 1984";
it gives the correct output

But according to the question input should be array of strings in the form of  Day Month Year and out put should return an array of strings in the format YYYY-MM-DD. I wrote the dates() method similar to the date() method in the above code. in the solution main method handling IOException it is pre written main method we are supposed to pass our method in main method to return the output but here my method is handling ParseException which is not handled by main method in the given program so i am getting  ParseException handling error so is there any other way of writing function to give the output


来源: stackexchange

问:
Debugging In SQLDeveloper over SSH Tunnel
I am using SQL Developer over an SSH tunnel to my database server without any problems.  However, it fails when I try to use the debugger.  The debugging window shows:

```<code>Executing PL/SQL: CALL DBMS_DEBUG_JDWP.CONNECT_TCP( '10.72.227.252', '52413' )
</code>```

But then I get the errors:

```<code>ORA-30683: failure establishing connection to debugger
ORA-12535: TNS:operation timed out
ORA-06512: at "SYS.DBMS_DEBUG_JDWP", line 68
ORA-06512: at line 1
</code>```

Is there a special listener that has to be running on the database server in order to debug over the network? It looks like the CONNECT_TCP call is trying to connect to a different port (52413 in the above example) every time I run it.  How do I debug in SQL Developer over an SSH tunnel?

答:
Temporary solution: switch debugger from jdwp to old version.
Add at the end of the ide.properties:

```<code>DatabaseDebuggerDisableJDWP=true
</code>```

This file location:

```<code>C:\Users\username\AppData\Roaming\SQL Developer\system${VERSION}\o.sqldeveloper.${SYSTEM_VERSION}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using SQL Developer over an SSH tunnel to my database server without any problems.  However, it fails when I try to use the debugger.  The debugging window shows:

Executing PL/SQL: CALL DBMS_DEBUG_JDWP.CONNECT_TCP( '10.72.227.252', '52413' )

But then I get the errors:

ORA-30683: failure establishing connection to debugger
ORA-12535: TNS:operation timed out
ORA-06512: at "SYS.DBMS_DEBUG_JDWP", line 68
ORA-06512: at line 1

Is there a special listener that has to be running on the database server in order to debug over the network? It looks like the CONNECT_TCP call is trying to connect to a different port (52413 in the above example) every time I run it.  How do I debug in SQL Developer over an SSH tunnel?

Body:
Temporary solution: switch debugger from jdwp to old version.
Add at the end of the ide.properties:

DatabaseDebuggerDisableJDWP=true

This file location:

C:\Users\username\AppData\Roaming\SQL Developer\system${VERSION}\o.sqldeveloper.${SYSTEM_VERSION}


问:
RestTemplate response.getBody throws exception on 4** and 5** errors for put and post request but works fine for get requests
I am trying to intercept and log all the request-responses. To make requests i am using RestTemplate.exchange().

When i make a GET request and get an 4** error i can call the ClientHttpResponse.getBody() and can access the response body but for PUT and POST requests ClientHttpResponse.getBody() method throws an exception.

What might be causing this and how can i get the response body for POST and PUT requests as well?

This is where i make the request:

```<code>apiResponse = restTemplate.exchange(url, vCloudRequest.getHttpMethod(), entity, responseType);
</code>```

This is the part of the interceptor that gets the exception:

```<code>@Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse response = execution.execute(request, body);

        String requestString = new String(body);

        String responseString = new
// Below line throws exception
String(ByteStreams.toByteArray(response.getBody()), Charset.forName("UTF-8"));
</code>```

This is the stack.

```<code>Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://176.235.57.11/api/admin/org/bd154aaf-2e7c-446d-91be-f0a45138476b/users
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at org.springframework.http.client.SimpleClientHttpResponse.getBody(SimpleClientHttpResponse.java:85)
    at org.springframework.http.client.BufferingClientHttpResponseWrapper.getBody(BufferingClientHttpResponseWrapper.java:69)
    at roma.api_utils.model.Interceptors.RequestLoggingInterceptor.intercept(RequestLoggingInterceptor.java:39)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:86)
    at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:70)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:652)
</code>```

Update :

When i call response.getStatusCode() before calling response.getBody() it doesn't throw IOException.

答:
Basic knowledge:

HttpURLConnection has two similar fields, errorStream and inputStream. When we invoke its getInputSteam method, it checks whether the response has an error code. If so, it throws an IOException and records it- that's why you got the exception. Furthermore, it also copies the contents in inputStream to errorStream, thus we can get its response body by invoking its getErrorStream method. This is exactly what SimpleClientHttpResponse does with its getBody method:

```<code>    @Override
    public InputStream getBody() throws IOException {
        InputStream errorStream = this.connection.getErrorStream();
        this.responseStream =
(errorStream != null ? errorStream : this.connection.getInputStream());
        return this.responseStream;
    }
</code>```

It first checks if errorStream is not null. If true, it returns it. If false, it calls connection.getInputStream() and returns that.

Now here are the answers

Why does calling response.getBody() not throw an IOException after you called response.getStatusCode()? It is because getStatusCode calls getInputStream internally. Thus, errorStream will be not null when getBody is called.

Why does it not throw an exception when the http method is GET?
See method org.springframework.http.client.SimpleBufferingClientHttpRequest#executeInternal.

.

```<code>@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput)
throws IOException {
    addHeaders(this.connection, headers);
    // JDK <1.8 doesn't support getOutputStream with HTTP DELETE
    if (HttpMethod.DELETE == getMethod() && bufferedOutput.length == 0) {
        this.connection.setDoOutput(false);
    }
    if (this.connection.getDoOutput() && this.outputStreaming) {
        this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
    }
    this.connection.connect();
    if (this.connection.getDoOutput()) {
        FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());
    }
    else {
        // Immediately trigger the request in a no-output scenario as well
        this.connection.getResponseCode();
    }
    return new SimpleClientHttpResponse(this.connection);
}
</code>```

It eagerly executes this.connection.getResponseCode(); when the http method is GET.

Body:
I am trying to intercept and log all the request-responses. To make requests i am using RestTemplate.exchange().

When i make a GET request and get an 4** error i can call the ClientHttpResponse.getBody() and can access the response body but for PUT and POST requests ClientHttpResponse.getBody() method throws an exception.

What might be causing this and how can i get the response body for POST and PUT requests as well?

This is where i make the request:

apiResponse = restTemplate.exchange(url, vCloudRequest.getHttpMethod(), entity, responseType);

This is the part of the interceptor that gets the exception:

@Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse response = execution.execute(request, body);

        String requestString = new String(body);

        String responseString = new
// Below line throws exception
String(ByteStreams.toByteArray(response.getBody()), Charset.forName("UTF-8"));

This is the stack.

Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://176.235.57.11/api/admin/org/bd154aaf-2e7c-446d-91be-f0a45138476b/users
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at org.springframework.http.client.SimpleClientHttpResponse.getBody(SimpleClientHttpResponse.java:85)
    at org.springframework.http.client.BufferingClientHttpResponseWrapper.getBody(BufferingClientHttpResponseWrapper.java:69)
    at roma.api_utils.model.Interceptors.RequestLoggingInterceptor.intercept(RequestLoggingInterceptor.java:39)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:86)
    at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:70)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:652)

Update :

When i call response.getStatusCode() before calling response.getBody() it doesn't throw IOException.

Body:
Basic knowledge:

HttpURLConnection has two similar fields, errorStream and inputStream. When we invoke its getInputSteam method, it checks whether the response has an error code. If so, it throws an IOException and records it- that's why you got the exception. Furthermore, it also copies the contents in inputStream to errorStream, thus we can get its response body by invoking its getErrorStream method. This is exactly what SimpleClientHttpResponse does with its getBody method:

    @Override
    public InputStream getBody() throws IOException {
        InputStream errorStream = this.connection.getErrorStream();
        this.responseStream =
(errorStream != null ? errorStream : this.connection.getInputStream());
        return this.responseStream;
    }

It first checks if errorStream is not null. If true, it returns it. If false, it calls connection.getInputStream() and returns that.

Now here are the answers

Why does calling response.getBody() not throw an IOException after you called response.getStatusCode()? It is because getStatusCode calls getInputStream internally. Thus, errorStream will be not null when getBody is called.

Why does it not throw an exception when the http method is GET?
See method org.springframework.http.client.SimpleBufferingClientHttpRequest#executeInternal.

.

@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput)
throws IOException {
    addHeaders(this.connection, headers);
    // JDK <1.8 doesn't support getOutputStream with HTTP DELETE
    if (HttpMethod.DELETE == getMethod() && bufferedOutput.length == 0) {
        this.connection.setDoOutput(false);
    }
    if (this.connection.getDoOutput() && this.outputStreaming) {
        this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
    }
    this.connection.connect();
    if (this.connection.getDoOutput()) {
        FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());
    }
    else {
        // Immediately trigger the request in a no-output scenario as well
        this.connection.getResponseCode();
    }
    return new SimpleClientHttpResponse(this.connection);
}

It eagerly executes this.connection.getResponseCode(); when the http method is GET.

ContentLicense: CC BY-SA 4.0


问:
How to add rows with null data dynamically in result table in SQL Server 2012?

I have this table with 22 rows as above

I am getting a converted table as above

I created following procedure in order to get result table

```<code>ALTER PROCEDURE [dbo].[proc_YS_BAB_IR_Item]
    @UserId int
AS
BEGIN TRAN
    DECLARE @SqlQry NVARCHAR(MAX);
    SET @SqlQry = N''

    DECLARE @Cnt INT = 1, @EndCnt INT = 25,
            @v_UserId INT = CAST(@UserId AS VARCHAR(MAX));

    CREATE TABLE #TempColumns
    (
        Calculate_ItemIdentifier VARCHAR(MAX),
        SeqOrder INT
    )

    WHILE @cnt <= @EndCnt
    BEGIN
        INSERT INTO #TempColumns
            SELECT
                'IR'+ CAST(@Cnt AS VARCHAR(MAX)),
                @Cnt

        SET @Cnt = @Cnt + 1;
    END

    DECLARE @DATA VARCHAR(10), @DATA1 VARCHAR(10) = '000000'
    DECLARE @zero_str VARCHAR(6) = '000000'

    -- Generate table alike to yours
    DECLARE @yourTable TABLE ([value] varchar(max))

    -- convert array to xml
    ;WITH cte AS
    (
        SELECT
            ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn,
            [response],
            CAST('<a>'+REPLACE(SUBSTRING([response],2,LEN([response]) - 2),',','</a><a>')+'</a>' as xml) AS x,
            @v_UserId AS UserId,
            [item_identifier]
        FROM
            #TempColumns
        LEFT JOIN
            YS_BAB_response_dump ON YS_BAB_response_dump.Item_Identifier = #TempColumns.Calculate_ItemIdentifier
                                 AND UserId = CAST(@UserId AS VARCHAR(MAX))
                                 AND TestModel = 'IR'
    )
    -- do the stuff
    SELECT
        c.rn,
        c.[response],
        c.[item_identifier],
        RIGHT(@zero_str +
CAST(SUM(CAST(STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') AS INT)) AS VARCHAR(6)), 6) AS ans,
        c.UserId
    FROM
        cte c
    CROSS APPLY
        x.nodes('/a') AS t(c)
    GROUP BY
        c.rn, c.[response], c.UserId, c.[Item_Identifier]
    ORDER BY
        c.rn

COMMIT TRAN
</code>```

What changes I need to do in above procedure to get 25 records as a result instead of 22, For IR21,IR22 and IR25 I want null data in response and ans columns for that respective userId? May i need to use some other function instead of CROSS APPLY? How it will be?

答: You were almost there. Use OUTER APPLY instead of CROSS APPLY

Body:
I have this table with 22 rows as above

I am getting a converted table as above

I created following procedure in order to get result table

ALTER PROCEDURE [dbo].[proc_YS_BAB_IR_Item]
    @UserId int
AS
BEGIN TRAN
    DECLARE @SqlQry NVARCHAR(MAX);
    SET @SqlQry = N''

    DECLARE @Cnt INT = 1, @EndCnt INT = 25,
            @v_UserId INT = CAST(@UserId AS VARCHAR(MAX));

    CREATE TABLE #TempColumns
    (
        Calculate_ItemIdentifier VARCHAR(MAX),
        SeqOrder INT
    )

    WHILE @cnt <= @EndCnt
    BEGIN
        INSERT INTO #TempColumns
            SELECT
                'IR'+ CAST(@Cnt AS VARCHAR(MAX)),
                @Cnt

        SET @Cnt = @Cnt + 1;
    END

    DECLARE @DATA VARCHAR(10), @DATA1 VARCHAR(10) = '000000'
    DECLARE @zero_str VARCHAR(6) = '000000'

    -- Generate table alike to yours
    DECLARE @yourTable TABLE ([value] varchar(max))

    -- convert array to xml
    ;WITH cte AS
    (
        SELECT
            ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn,
            [response],
            CAST(''+REPLACE(SUBSTRING([response],2,LEN([response]) - 2),',','')+'' as xml) AS x,
            @v_UserId AS UserId,
            [item_identifier]
        FROM
            #TempColumns
        LEFT JOIN
            YS_BAB_response_dump ON YS_BAB_response_dump.Item_Identifier = #TempColumns.Calculate_ItemIdentifier
                                 AND UserId = CAST(@UserId AS VARCHAR(MAX))
                                 AND TestModel = 'IR'
    )
    -- do the stuff
    SELECT
        c.rn,
        c.[response],
        c.[item_identifier],
        RIGHT(@zero_str +
CAST(SUM(CAST(STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') AS INT)) AS VARCHAR(6)), 6) AS ans,
        c.UserId
    FROM
        cte c
    CROSS APPLY
        x.nodes('/a') AS t(c)
    GROUP BY
        c.rn, c.[response], c.UserId, c.[Item_Identifier]
    ORDER BY
        c.rn

COMMIT TRAN

What changes I need to do in above procedure to get 25 records as a result instead of 22, For IR21,IR22 and IR25 I want null data in response and ans columns for that respective userId? May i need to use some other function instead of CROSS APPLY? How it will be?


问:
Magento 2 _theme.less media queries
is there any trick adding styles to _theme.less so they are only in processed styles-m.css or styles-l.css

Normally the styles from _theme.less is processed in both.

答: From how i understood it, styles-m.css would have both desktop and mobile styling while styles-l.css would have desktop only. I have shared a link to a question related to yours see link.</p>

Title: Magento 2 _theme.less media queries


问:
Multiple select queries on the same table in Oracle
I have a table with all my data. I have tried joins, subqueries and unions, but none give me the desired result. I am running Oracle 12g.

This is a sample table:

```<code>FILENAME | VALUE | RAW
AA       | XX    | ZZ
AA       | YY    | WW
DD       | GG    | II
DD       | HH    | JJ
</code>```

The current SQL statement that I use is:

```<code>SELECT FILENAME, VALUE VALUE1 FROM TABLE WHERE FILENAME='AA';
SELECT FILENAME, VALUE VALUE2 FROM TABLE WHERE FILENAME='DD';
</code>```

And I get the following result:

```<code>FILENAME | VALUE1
AA       | XX
AA       | YY
</code>```

and

```<code>FILENAME | VALUE2
DD       | GG
DD       | HH
</code>```

but I need the result to be:

```<code>FILENAME | VALUE1 | VALUE2
AA       | XX     | GG
AA       | YY     | HH
</code>```

It doesn't matter if AA or DD is in the FILENAME. There are no foreign keys or unique values that I can do a simple INNER JOIN. I am not able to add new columns to the table. I was hoping to do sort my data and then use Oracle's ROWNUM as a temp column which I could then use to do a SELF JOIN but Oracle won't let me.

Example:

```<code>SELECT L.FILENAME, L.VALUE VALUE1, R.VALUE VALUE2
FROM TABLE L JOIN TABLE R
ON (L.ROWNUM=R.ROWNUM)
WHERE L.FILENAME IN ('AA','DD');
</code>```

Any help is appreciated.

答:
You may try this:

```<code>select a1, a2, b2
  from ( select row_number() over(order by filename) rn_a, filename a1, value a2 from mytable where filename = 'AA' ) inner join
       ( select row_number() over(order by filename) rn_b, value b2 from mytable filename = 'DD' ) on rn_a = rn_b
 order by a2;
</code>```

where ROW_NUMBER is an analytic function, introduced in ver.8iR2. It assigns a unique number
  to each row to which it is applied (either each row in the partition
  or each row returned by the query). By nesting a subquery using
  ROW_NUMBER inside a query that retrieves the ROW_NUMBER values for a
  specified range, you can find a precise subset of rows from the
  results of the inner query.

Body:
I have a table with all my data. I have tried joins, subqueries and unions, but none give me the desired result. I am running Oracle 12g.

This is a sample table:

FILENAME | VALUE | RAW
AA       | XX    | ZZ
AA       | YY    | WW
DD       | GG    | II
DD       | HH    | JJ

The current SQL statement that I use is:

SELECT FILENAME, VALUE VALUE1 FROM TABLE WHERE FILENAME='AA';
SELECT FILENAME, VALUE VALUE2 FROM TABLE WHERE FILENAME='DD';

And I get the following result:

FILENAME | VALUE1
AA       | XX
AA       | YY

and

FILENAME | VALUE2
DD       | GG
DD       | HH

but I need the result to be:

FILENAME | VALUE1 | VALUE2
AA       | XX     | GG
AA       | YY     | HH

It doesn't matter if AA or DD is in the FILENAME. There are no foreign keys or unique values that I can do a simple INNER JOIN. I am not able to add new columns to the table. I was hoping to do sort my data and then use Oracle's ROWNUM as a temp column which I could then use to do a SELF JOIN but Oracle won't let me.

Example:

SELECT L.FILENAME, L.VALUE VALUE1, R.VALUE VALUE2
FROM TABLE L JOIN TABLE R
ON (L.ROWNUM=R.ROWNUM)
WHERE L.FILENAME IN ('AA','DD');

Any help is appreciated.

Body:
You may try this:

select a1, a2, b2
  from ( select row_number() over(order by filename) rn_a, filename a1, value a2 from mytable where filename = 'AA' ) inner join
       ( select row_number() over(order by filename) rn_b, value b2 from mytable filename = 'DD' ) on rn_a = rn_b
 order by a2;

where ROW_NUMBER is an analytic function, introduced in ver.8iR2. It assigns a unique number
  to each row to which it is applied (either each row in the partition
  or each row returned by the query). By nesting a subquery using
  ROW_NUMBER inside a query that retrieves the ROW_NUMBER values for a
  specified range, you can find a precise subset of rows from the
  results of the inner query.


问:
Maven: mvn test gives error + Cannot find class in classpath
Running testng.xml directly from eclipse IDE, test suite gets executed but on executing testng.xml from maven gives error.

Running mvn compile, it says BUILD SUCCESS. But on running mvn testit gives error.

On running maven script through mvn test I am receiving below error:

```<code>[INFO]
[INFO] --- maven-compiler-plugin:3.3:testCompile (default-testCompile) @ XXX
--
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.18:test (default-test) @ XXX---
[INFO] No tests to run.
[INFO] Surefire report directory: \XXX\target\surefire-reports
Running TestSuite
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.295 s
[INFO] Finished at: 2015-11-09T17:34:34+05:30
[INFO] Final Memory: 17M/208M

--------------------
-----------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.
18:test (default-test) on project XXX: Exception in provider:
[ERROR] Cannot find class in classpath: com.XXX.tests.XXXX.classtoexecute
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal o
rg.apache.maven.plugins:maven-surefire-plugin:2.18:test (default-test) on project XXX: Exception in provider
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor
.java:212)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor
.java:153)
</code>```

Please help.

Below is POM.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.xx.tests</groupId>
  <artifactId>XXX</artifactId>
  <version>1.0-SNAPSHOT</version>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.18</version>
        <configuration>
          <forkCount>0</forkCount>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.46.0</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.8.5</version>
    </dependency>
    <dependency>
        <groupId>atu.testng</groupId>
        <artifactId>reports</artifactId>
        <version>5.0</version>
    </dependency>
  </dependencies>
</project>
</code>```

TestNg is as belwo:

<

```<code>?xml version="1.0" encoding="UTF-8"?>
<suite name="XXXX" parallel="none" >
    <listeners>
        <listener class-name="atu.testng.reports.listeners.ATUReportsListener"></listener>
        <listener class-name="atu.testng.reports.listeners.ConfigurationListener"></listener>
        <listener class-name="atu.testng.reports.listeners.MethodListener"></listener>
    </listeners>
  <test name="test1" >
    <classes>
      <class name="com.XXX.tests.XXXX.classtoexecute"/>
    </classes>
 </test>
</suite>
</code>```

The project structure is as below:

答:
i had same error,

Move your src folder to Main > Java

it should be "src > Main > Java"  >

```<code>com.something.test.something

com.something.test.sometest2
</code>```

now compile/run in maven

Body:
Running testng.xml directly from eclipse IDE, test suite gets executed but on executing testng.xml from maven gives error.

Running mvn compile, it says BUILD SUCCESS. But on running mvn testit gives error.

On running maven script through mvn test I am receiving below error:

[INFO]
[INFO] --- maven-compiler-plugin:3.3:testCompile (default-testCompile) @ XXX
--
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.18:test (default-test) @ XXX---
[INFO] No tests to run.
[INFO] Surefire report directory: \XXX\target\surefire-reports
Running TestSuite
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.295 s
[INFO] Finished at: 2015-11-09T17:34:34+05:30
[INFO] Final Memory: 17M/208M

--------------------
-----------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.
18:test (default-test) on project XXX: Exception in provider:
[ERROR] Cannot find class in classpath: com.XXX.tests.XXXX.classtoexecute
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal o
rg.apache.maven.plugins:maven-surefire-plugin:2.18:test (default-test) on project XXX: Exception in provider
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor
.java:212)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor
.java:153)

Please help.

Below is POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.xx.tests</groupId>
  <artifactId>XXX</artifactId>
  <version>1.0-SNAPSHOT</version>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.18</version>
        <configuration>
          <forkCount>0</forkCount>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.46.0</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.8.5</version>
    </dependency>
    <dependency>
        <groupId>atu.testng</groupId>
        <artifactId>reports</artifactId>
        <version>5.0</version>
    </dependency>
  </dependencies>
</project>

TestNg is as belwo:

<

?xml version="1.0" encoding="UTF-8"?>
<suite name="XXXX" parallel="none" >
    <listeners>
        <listener class-name="atu.testng.reports.listeners.ATUReportsListener"></listener>
        <listener class-name="atu.testng.reports.listeners.ConfigurationListener"></listener>
        <listener class-name="atu.testng.reports.listeners.MethodListener"></listener>
    </listeners>
  <test name="test1" >
    <classes>
      <class name="com.XXX.tests.XXXX.classtoexecute"/>
    </classes>
 </test>
</suite>

The project structure is as below:

Body:
i had same error,

Move your src folder to Main > Java

it should be "src > Main > Java"  >

com.something.test.something

com.something.test.sometest2

now compile/run in maven


问:
remove red rectangle around combobox
i need to remove red rectangle around combobox. I have setup combobox in xaml like (below) this and i`m trying to override of the Validation.ErrorTemplate.

```<code>        <ComboBox x:Name="comboPodkategoria"
                            Margin="0,3,0,0"
                            IsSynchronizedWithCurrentItem="False"
                            IsEditable="False"
                            ItemsSource="{Binding Source={StaticResource PodKategoriaLookup}, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                            SelectedValue="{Binding IDPodKategoria}"
                            DisplayMemberPath="kat_popis" SelectedValuePath="IDPodkat" TabIndex="5" Style="{StaticResource combostyle}">
                            <Validation.ErrorTemplate>
                                <ControlTemplate>
                                </ControlTemplate>
                            </Validation.ErrorTemplate>
            </ComboBox>
</code>```

And style for removing red rectangle, but a have some error in xaml saying that Visibility property is not recognized or is not accessible. Style definition is below.

```<code><Style x:Key="combostyle">
<Style.Triggers>
    <Trigger Property="Validation.HasError" Value="True">
        <Setter Property="Visibility" TargetName="NotValid" Value="Visible"/>
    </Trigger>
</Style.Triggers>
</code>```

Any idea? :(

答: Add your Combobox, Validation.ErrorTemplate="{x:Null}" ; this code is ignore errors.

ContentLicense: CC BY-SA 2.5

Title: remove red rectangle around combobox

Body:
i need to remove red rectangle around combobox. I have setup combobox in xaml like (below) this and i`m trying to override of the Validation.ErrorTemplate.

        <ComboBox x:Name="comboPodkategoria"
                            Margin="0,3,0,0"
                            IsSynchronizedWithCurrentItem="False"
                            IsEditable="False"
                            ItemsSource="{Binding Source={StaticResource PodKategoriaLookup}, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                            SelectedValue="{Binding IDPodKategoria}"
                            DisplayMemberPath="kat_popis" SelectedValuePath="IDPodkat" TabIndex="5" Style="{StaticResource combostyle}">
                            <Validation.ErrorTemplate>
                                <ControlTemplate>
                                </ControlTemplate>
                            </Validation.ErrorTemplate>
            </ComboBox>

And style for removing red rectangle, but a have some error in xaml saying that Visibility property is not recognized or is not accessible. Style definition is below.

Any idea? :(


问:
System.out.println(); is printing two lines
I've recently started studying Java and I already had my first problem. Currently I'm making a text adventure game (written in Java) and I can't continue because the program is printing out two lines but that I don't want it to. I don't how I can make it print out only one line.

In the last bit of the program there is a system.out.print("hello")

```<code>import java.util.Scanner;

public class TextAd2 {

Scanner sc = new Scanner(System.in);

//Name
String Pname;

public static void main(String[] args) {

    //connection
    TextAd2 con;
    con = new TextAd2();

    con.info();
    con.start1();
}

public void info() {

System.out.println("Hello!");
System.out.println("Your Name? ");
Pname = sc.nextLine();

System.out.println("Hello " + Pname);
System.out.println("Wana Start The Game or Stop?");
String text1 = sc.nextLine();

    switch (text1) {
    case "Start":
        start1();
        break;

    case "Stop":
        System.exit(0);
        break;
    default:
        System.out.println("Unknown Command.");
    }
}
public void start1()
{
    //it starts to print this twice
    System.out.println("hello");
}
}
</code>```

I actually don't think that the system.out.print is the problem, maybe the program is just reading the 'start1()' twice that's why it's printing "hello" two times. I did this in an if else statement and it's doing the same thing too. I don't know the code to how to prevent this either way. I am doing something wrong but I don't know what is the probelm

答:
You can calling twice con.start1();

Once in your main():

```<code>con.info();
con.start1();
</code>```

And the second time in your switch:

```<code>   case "Start":
        start1();
        break;
</code>```

Body:
I've recently started studying Java and I already had my first problem. Currently I'm making a text adventure game (written in Java) and I can't continue because the program is printing out two lines but that I don't want it to. I don't how I can make it print out only one line.

In the last bit of the program there is a system.out.print("hello")

import java.util.Scanner;

public class TextAd2 {

Scanner sc = new Scanner(System.in);

//Name
String Pname;

public static void main(String[] args) {

    //connection
    TextAd2 con;
    con = new TextAd2();

    con.info();
    con.start1();
}

public void info() {

System.out.println("Hello!");
System.out.println("Your Name? ");
Pname = sc.nextLine();

System.out.println("Hello " + Pname);
System.out.println("Wana Start The Game or Stop?");
String text1 = sc.nextLine();

    switch (text1) {
    case "Start":
        start1();
        break;

    case "Stop":
        System.exit(0);
        break;
    default:
        System.out.println("Unknown Command.");
    }
}
public void start1()
{
    //it starts to print this twice
    System.out.println("hello");
}
}

I actually don't think that the system.out.print is the problem, maybe the program is just reading the 'start1()' twice that's why it's printing "hello" two times. I did this in an if else statement and it's doing the same thing too. I don't know the code to how to prevent this either way. I am doing something wrong but I don't know what is the probelm

Body:
You can calling twice con.start1();

Once in your main():

con.info();
con.start1();

And the second time in your switch:

   case "Start":
        start1();
        break;


问:
Install intel python fails in anaconda due to http connection error
I am new to Anaconda. HTTP connection error is occurring while installing Intel Python under Anaconda.

condaHTTPError: HTTP 000 CONNECTION FAILED for url".

Please help me to solve this issue.

Figure shows the error message when I try to install intel python under anaconda.

答:
It may due to proxy:

try configuring proxy according to documentation:

https://conda.io/docs/user-guide/configuration/use-condarc.html#configure-conda-for-use-behind-a-proxy-server-proxy-servers


问:
Get index from subset in R
I would like to access the row index of a subset of a data frame in R, but I have not been able to find a way to access the information. For example, if I had the data frame:

```<code>a <- c(1, 2, 3, 4, 5)
b <- c(2, 3, 4, 5, 6)
c <- data.frame(a, b)
</code>```

And I grab the second row:

```<code>d <- c[2,]
</code>```

If I print d I get:

```<code>print(d)
  a b
2 2 3
</code>```

So I assume that R somehow stores the row that d was in the original data frame! But if I go:

```<code>str(d)
'data.frame':   1 obs. of  2 variables:
 $ a: num 2
 $ b: num 3
</code>```

I can't see where that 2(for the row) is stored. Is there a way to access that value?

And yes, I am aware that in this example I already have the row number from subsetting. However, most of the time I am subsetting logically, and in any case I would like to avoid separately finding the row index and also passing it to a function.

答:
```<code>a <- c(1, 2, 3, 4, 5)
b <- c(2, 3, 4, 5, 6)
c <- data.frame(a, b)
d <- c[2,]
rownames(d) # "2"; class(rownames(d)) = "character"
as.numeric(rownames(d)) # 2; class(as.numeric(rownames(d))) = "numeric"
</code>```

Title: Get index from subset in R

Body:
I would like to access the row index of a subset of a data frame in R, but I have not been able to find a way to access the information. For example, if I had the data frame:

a <- c(1, 2, 3, 4, 5)
b <- c(2, 3, 4, 5, 6)
c <- data.frame(a, b)

And I grab the second row:

d <- c[2,]

If I print d I get:

print(d)
  a b
2 2 3

So I assume that R somehow stores the row that d was in the original data frame! But if I go:

str(d)
'data.frame':   1 obs. of  2 variables:
 $ a: num 2
 $ b: num 3

I can't see where that 2(for the row) is stored. Is there a way to access that value?

And yes, I am aware that in this example I already have the row number from subsetting. However, most of the time I am subsetting logically, and in any case I would like to avoid separately finding the row index and also passing it to a function.


问:
Button with both background image and color WPF
I have a button in my wpf app, looking like :

```<code>    <Button x:Name="button" Content="" HorizontalAlignment="Left" Margin="402,10,0,0" VerticalAlignment="Top" Width="26" Height="28" BorderBrush="{x:Null}" Grid.Column="1" Foreground="White">
     <Button.Background>
            <ImageBrush ImageSource="cls_blk_btn.png" Stretch="None"/>
        </Button.Background>
    </Button>

</code>```

Now as you can see the button has a background image, is it possible to have a background color keeping the image also ??

What i am trying to do is change the button's background color(keeping the image as it is) on mouse enter with this :

```<code>      <Button.Style>
            <Style TargetType="Button">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="Button.MouseEnter">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetProperty="Color" To="#FF484A4D" Duration="0:0:0.1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="Button.MouseLeave">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Color" To="#FF57626C" Duration="0:0:0.1" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
            </Button.Style>
</code>```

The problem is, as the background is an image, i get exceptions while trying to change the color...Any help in keeping the image as it is and changing the backColor ???

THIS IS WHAT I JUST TRIED

```<code>    <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Background">
                    <Setter.Value>
                        <ImageBrush ImageSource="resources\c_ml.bmp" Stretch="Fill"/>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background">
                            <Setter.Value>
                                <ImageBrush ImageSource="Resources\c_mo.bmp" Stretch="Fill"/>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
</code>```

But it gives me 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' in line 45.The lines throwing the exceptions are:

```<code>   <Style TargetType="{x:Type Button}">
                <Setter Property="Background">
                    <Setter.Value>
                        <ImageBrush ImageSource="resources\c_ml.png" Stretch="Fill"/>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
</code>```

Any idea how to fix it ?

I FIXED MY SECOND ERROR BUT HAVE A NEW PROBLEM

The second error occured because i didn't include the pictures in my project.After including, i have a new problem. Now , on mouse over, The button becomes white, i mean it changes it's Background color instead of changing the image...What's wrong ?

答:
Do you have to put the Image in background? If you just want to show an Image with background in the button, it will be lot easier to put the Image in Button.Content and animate the background, e.g.:</p>

```<code><Button x:Name="button" HorizontalAlignment="Left" Margin="402,10,0,0" VerticalAlignment="Top" Width="260" Height="280" BorderBrush="{x:Null}" Foreground="White">
    <Button.Content>
        <Image  Source="image.png" Stretch="None" />
    </Button.Content>
    <Button.Background>
        <SolidColorBrush Color="#FF57626C" />
    </Button.Background>
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}" >
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <EventTrigger RoutedEvent="Button.MouseEnter">
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation Storyboard.TargetProperty="Background.Color" To="#FF484A4D" Duration="0:0:0.1" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="Button.MouseLeave">
                    <BeginStoryboard>
                        <Storyboard>
                            <ParallelTimeline  >
                                <ColorAnimation Storyboard.TargetProperty="Background.Color" To="#FF57626C" Duration="0:0:0.1" />
                            </ParallelTimeline>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

Body:
I have a button in my wpf app, looking like :

    <Button x:Name="button" Content="" HorizontalAlignment="Left" Margin="402,10,0,0" VerticalAlignment="Top" Width="26" Height="28" BorderBrush="{x:Null}" Grid.Column="1" Foreground="White">
     <Button.Background>
            <ImageBrush ImageSource="cls_blk_btn.png" Stretch="None"/>
        </Button.Background>
    </Button>

Now as you can see the button has a background image, is it possible to have a background color keeping the image also ??

What i am trying to do is change the button's background color(keeping the image as it is) on mouse enter with this :

      <Button.Style>

            </Style>
            </Button.Style>

The problem is, as the background is an image, i get exceptions while trying to change the color...Any help in keeping the image as it is and changing the backColor ???

THIS IS WHAT I JUST TRIED

    <Button.Style>

            </Style>
        </Button.Style>

But it gives me 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' in line 45.The lines throwing the exceptions are:

Body:
Do you have to put the Image in background? If you just want to show an Image with background in the button, it will be lot easier to put the Image in Button.Content and animate the background, e.g.:

<Button x:Name="button" HorizontalAlignment="Left" Margin="402,10,0,0" VerticalAlignment="Top" Width="260" Height="280" BorderBrush="{x:Null}" Foreground="White">
    <Button.Content>
        <Image  Source="image.png" Stretch="None" />
    </Button.Content>
    <Button.Background>
        <SolidColorBrush Color="#FF57626C" />
    </Button.Background>
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}" >
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <EventTrigger RoutedEvent="Button.MouseEnter">
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation Storyboard.TargetProperty="Background.Color" To="#FF484A4D" Duration="0:0:0.1" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="Button.MouseLeave">
                    <BeginStoryboard>
                        <Storyboard>
                            <ParallelTimeline  >
                                <ColorAnimation Storyboard.TargetProperty="Background.Color" To="#FF57626C" Duration="0:0:0.1" />
                            </ParallelTimeline>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>


问:
I have some problems about lists Python 2.7
Could you tell me what's wrong here?

For some reason there's nothing added into the list.

```<code>textarea = raw_input()
n=0
txa = []
string =""

while(n < len(textarea)):
    if(textarea[n] != ' ' or textarea[n] != ','):

        string += textarea[n]
        n=n+1
        print (string)

    else:
        print "For some reason I'm never here."

        if(string == ' ' or string == ','):
            string = ""
        else:
            txa.append(string)
            string = ""
            n=n+1
print(txa)
</code>```

Sorry for my english.

答:
First, you need to change or in your 1st if with and.

Second, if-else block in the 1st else is redundant. Try deleting it, but retaining the code in the 2nd else block.

Third, add an append just after the while so that the last word that is stored in the string variable also gets into the txa list.

Your code will pretty much, look like this -

```<code>while(n < len(textarea)):
    if(textarea[n] != ' ' and textarea[n] != ','):
        string += textarea[n]
        n=n+1
        print (string)

    else:
        print ("For some reason I'm never here.")
        txa.append(string)
        string = ""
        n=n+1

txa.append(string)
print(txa)
</code>```

Tip: Moreover, you can try using in-built functions to do splitting for you.

```<code>txa = str(raw_input()).replace(',', ' ').split()
</code>```

This one-liner works just fine.

Body:
Could you tell me what's wrong here?

For some reason there's nothing added into the list.

textarea = raw_input()
n=0
txa = []
string =""

while(n < len(textarea)):
    if(textarea[n] != ' ' or textarea[n] != ','):

        string += textarea[n]
        n=n+1
        print (string)

    else:
        print "For some reason I'm never here."

        if(string == ' ' or string == ','):
            string = ""
        else:
            txa.append(string)
            string = ""
            n=n+1
print(txa)

Sorry for my english.

Body:
First, you need to change or in your 1st if with and.

Second, if-else block in the 1st else is redundant. Try deleting it, but retaining the code in the 2nd else block.

Third, add an append just after the while so that the last word that is stored in the string variable also gets into the txa list.

Your code will pretty much, look like this -

while(n < len(textarea)):
    if(textarea[n] != ' ' and textarea[n] != ','):
        string += textarea[n]
        n=n+1
        print (string)

    else:
        print ("For some reason I'm never here.")
        txa.append(string)
        string = ""
        n=n+1

txa.append(string)
print(txa)

Tip: Moreover, you can try using in-built functions to do splitting for you.

txa = str(raw_input()).replace(',', ' ').split()

This one-liner works just fine.


问:
Plsql oracle apex
i am using this loop in my procedure and taking the email ids in i but when i am trying to run i am getting no data found error, so i want to check the values storing in i

code used:

```<code>  for i in ( select EMAIL
              into l_user_mail
              from employee A CONNECT BY PRIOR lower(EMAIL) = lower(MANAGER_EMAIL)
                                START WITH lower(GUID) in  (select replace(lower(group_name),'_org_slack')
                                                              from dynamic_group where id = '81')
           ) loop

    l_user_mail:=l_user_mail || i.EMAIL;
  end loop;
</code>```

how to check the return value of i in sql command prompt.

i want to see the values getting in i

答:
i want to see the values getting in i

Your FOR LOOP syntax is not correct. INTO clause should not be used in For Loop. See below how you can do that.

```<code> FOR I IN
          (SELECT     EMAIL
                 FROM EMPLOYEE A
           CONNECT BY PRIOR LOWER (EMAIL) = LOWER (MANAGER_EMAIL)
           START WITH LOWER (GUID) IN (
                             SELECT REPLACE (LOWER (GROUP_NAME), '_org_slack')
                               FROM DYNAMIC_GROUP
                              WHERE ID = '81') )
     LOOP
          -- l_user_mail:=:P60_IDP_GROUPS;
          L_USER_MAIL := L_USER_MAIL || I.EMAIL;
          -- To display value of I
          DBMS_OUTPUT.PUT_LINE (I.EMAIL);
     END LOOP;
</code>```

Demo:

```<code>SQL> DECLARE
  2       L_USER_MAIL                   VARCHAR2 (10);
  3  BEGIN
  4       FOR I IN (SELECT     LEVEL
  5                       FROM DUAL
  6                 CONNECT BY LEVEL < 10)
  7       LOOP
  8            -- l_user_mail:=:P60_IDP_GROUPS;
  9            L_USER_MAIL := L_USER_MAIL || I.level;
 10            DBMS_OUTPUT.PUT_LINE (I.level);
 11       END LOOP;
 12  END;
 13  /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.
</code>```

Title: Plsql oracle apex

Body:
i am using this loop in my procedure and taking the email ids in i but when i am trying to run i am getting no data found error, so i want to check the values storing in i

code used:

  for i in ( select EMAIL
              into l_user_mail
              from employee A CONNECT BY PRIOR lower(EMAIL) = lower(MANAGER_EMAIL)
                                START WITH lower(GUID) in  (select replace(lower(group_name),'_org_slack')
                                                              from dynamic_group where id = '81')
           ) loop

    l_user_mail:=l_user_mail || i.EMAIL;
  end loop;

how to check the return value of i in sql command prompt.

i want to see the values getting in i

Body:
i want to see the values getting in i

Your FOR LOOP syntax is not correct. INTO clause should not be used in For Loop. See below how you can do that.

 FOR I IN
          (SELECT     EMAIL
                 FROM EMPLOYEE A
           CONNECT BY PRIOR LOWER (EMAIL) = LOWER (MANAGER_EMAIL)
           START WITH LOWER (GUID) IN (
                             SELECT REPLACE (LOWER (GROUP_NAME), '_org_slack')
                               FROM DYNAMIC_GROUP
                              WHERE ID = '81') )
     LOOP
          -- l_user_mail:=:P60_IDP_GROUPS;
          L_USER_MAIL := L_USER_MAIL || I.EMAIL;
          -- To display value of I
          DBMS_OUTPUT.PUT_LINE (I.EMAIL);
     END LOOP;

Demo:

SQL> DECLARE
  2       L_USER_MAIL                   VARCHAR2 (10);
  3  BEGIN
  4       FOR I IN (SELECT     LEVEL
  5                       FROM DUAL
  6                 CONNECT BY LEVEL < 10)
  7       LOOP
  8            -- l_user_mail:=:P60_IDP_GROUPS;
  9            L_USER_MAIL := L_USER_MAIL || I.level;
 10            DBMS_OUTPUT.PUT_LINE (I.level);
 11       END LOOP;
 12  END;
 13  /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.


问:
List Hours worked with multiple shifts and across dates
I have a few questions on how to handle a few employee timekeeping queries in SQL 2012…  I had asked another quesiton last week about determining the time between shifts, which I as able to get a great response to.

We are fed the data from our Point Of Sale Software Provider, so we cannot change the format of the data.

Work days are based on DateOfBusiness which are from 5:00 am until 4:59am the next calendar day, so it crosses midnight.  Locations End Of Day process is offset a little to control balance loads, some are 5:05am instead of 5:00am.  When the End Of Day process runs, it clocks everyone out then clocks them back in when the process completes.
    - Employees clock out for the 30 minute required meal breaks, so there are 2 or more records for one day for these employees. Not sure why, but several employees have more than 3 records in one day (EmployeeShiftNumber).
    - Shifts occasionally cross DateOfBusiness.  In at 11:00PM - Out at 7:00am

I need to report list of initial InTime and Final OutTime and the number of minutes worked. I have will have to compare these against the table which holds the employee schedules.  This reporting is not for Payroll purposes, but for comparisons against scheduled shifts.

I have included some sample data grouped by employee and by day and the values I would expect to see commented to the right.  I also need to see the number of minutes worked in the shift.

```<code>--drop table #Shift

CREATE TABLE #Shift(
    FKEmployeeNumber int,
    DateOfBusiness datetime,
    FKStoreId int,
    EmployeeShiftNumber int,
    FKJobCodeId int,
    InHour int,
    InMinute int,
    OutHour int,
    OutMinute int)

insert into #Shift ( FKEmployeeNumber, DateOfBusiness, FKStoreId, EmployeeShiftNumber, FKJobCodeId, InHour, InMinute,OutHour,OutMinute)
values
(23761, '11/30/2017', 3013, 0, 1, 17, 39, 21, 30),
(23761, '11/30/2017', 3013, 1, 1, 21, 30, 2, 39),   -- 5:39PM  2:39AM

(23770, '11/30/2017', 3013, 0, 200, 7, 19, 16, 25), -- 7:19AM  4:25PM

(23938, '11/30/2017', 3013, 0, 1, 16, 4, 1, 26),    -- 4:04AM  1:26AM

(24006, '11/30/2017', 3013, 0, 1, 7, 30, 18, 36),
(24006, '11/30/2017', 3013, 1, 1, 18, 36, 18, 40),  -- 7:30AM  6:40PM

(24018, '11/30/2017', 3013, 0, 2, 8, 52, 17, 0),    -- 8:52M  4:00PM

(25176, '11/30/2017', 3013, 0, 200, 15, 59, 20, 1), -- 3:59PM  8:01PM

(25176, '11/30/2017', 3013, 1, 200, 20, 30, 0, 05), -- 8:30PM  12:05AM

(25180, '11/30/2017', 3013, 0, 1, 21, 0, 5, 0),     -- 9:00PM  5:00AM

(25187, '11/30/2017', 3013, 0, 1, 10, 0, 16, 6),    -- 10:00AM  4:06PM

(35189, '11/30/2017', 3013, 0, 1, 16, 58, 2, 4),    -- 4:58PM  2:04AM

(25147, '12/04/2017', 3106, 0, 1, 6, 58, 15, 2),
(25147, '12/04/2017', 3106, 1, 1, 15, 3, 15, 3),    -- 6:58AM  3:03PM

(26291, '12/01/2017', 3118, 1, 200, 23, 15, 5, 5),
(26291, '12/02/2017', 3118, 0, 200, 5, 6, 7, 22),   -- 11:15PM  7:22AM

(26291, '12/03/2017', 3118, 0, 200, 7, 30, 15, 38), -- 7:30AM  3:38PM

(26291, '12/04/2017', 3118, 0, 200, 23, 15, 5, 5),
(26291, '12/05/2017', 3118, 0, 200, 5, 6, 7, 12),   -- 11:15PM  7:12AM

(26291, '12/05/2017', 3118, 1, 200, 23, 15, 5, 5),
(26291, '12/06/2017', 3118, 0, 200, 15, 14, 7, 5)   -- 11:15PM  7:05AM
--Select * from #Shift

SELECT fkstoreid, FKEmployeeNumber AS EmpID, DateOfBusiness AS Date,
    RIGHT(CONVERT(varchar(30), DATEADD(MINUTE, InTime_Mins, 0), 100), 7) AS InTime,
    RIGHT(CONVERT(varchar(30), DATEADD(MINUTE, OutTime_Mins, 0), 100), 7) AS OutTime,
    MinsWorked
FROM (
    select sh.FKStoreId, sh.FKEmployeeNumber, sh.DateOfBusiness,
        MIN(sh.InHour*60+InMinute) AS InTime_Mins,
        MAX(sh.OutHour*60+OutMinute) AS OutTime_Mins,
        SUM(((sh.outhour+case when sh.OutHour < sh.InHour then 24 else 0 end)*60 + sh.outminute) -
             (sh.inhour*60 + sh.inminute)) AS MinsWorked
    from #shift sh
    group by sh.FKStoreId,sh.FKEmployeeNumber, sh.DateOfBusiness
) AS derived
order by FKEmployeeNumber, DateOfBusiness
</code>```

答:
I've written a sample of how you could do it.

Briefly summarized I perform these steps:

Mark records that should be grouped with either the next or the previous record, because they are a part of the same shift.

Find the start and end of each shift

Join all records for an employee that fall within each shift

Group the resultset per employee per shift, and calculate the minutes worked by summing up the minutes between checkin and checkout for each record within a shift.

Sample query:

```<code>WITH ShiftParts AS (
    SELECT
        FKEmployeeNumber,
        DATEADD(MINUTE, InMinute, DATEADD(HOUR, InHour, DateOfBusiness)) CheckIn, --Datetime of the checkin
        DATEADD(DAY, CASE WHEN OutHour < InHour THEN 1 ELSE 0 END,
            DATEADD(MINUTE, OutMinute, DATEADD(HOUR, OutHour, DateOfBusiness))) CheckOut --Datetime of the checkout (add one day if we crossed midnight).
    FROM #Shift
),
GroupInfo AS (
    SELECT
        *,
        CASE
            WHEN DATEDIFF(MINUTE, LAG(CheckOut, 1, NULL) OVER (PARTITION BY FKEmployeeNumber ORDER BY CheckOut), CheckIn) <= 120
            THEN 1 ELSE 0 END AS GroupWithPrevious, --Determine whether we want to group this record with the previous
        CASE
            WHEN DATEDIFF(MINUTE, CheckOut, LEAD(CheckIn, 1, NULL) OVER (PARTITION BY FKEmployeeNumber ORDER BY CheckOut)) <= 120
            THEN 1 ELSE 0 END AS GroupWithNext --Determine whether we want to group this record with the next
    FROM ShiftParts
), ShiftStartAndEnd AS (
    SELECT
        *,
        CASE WHEN GroupWithNext = 1 THEN LEAD(CheckOut, 1, NULL) OVER (PARTITION BY FKEmployeeNumber ORDER BY CheckOut) ELSE CheckOut END AS FinalCheckOut
    FROM GroupInfo
    WHERE GroupWithPrevious = 0 OR GroupWithNext = 0 --Only pick beginning and end of a shift
)
SELECT
    sse.FKEmployeeNumber,
    sse.CheckIn,
    sse.FinalCheckOut,
    SUM(DATEDIFF(MINUTE,sp.CheckIn,sp.CheckOut)) AS MinutesWorked
FROM ShiftStartAndEnd sse
    LEFT OUTER JOIN ShiftParts sp ON sp.FKEmployeeNumber = sse.FKEmployeeNumber AND sp.CheckIn >= sse.CheckIn AND sp.CheckOut <= sse.FinalCheckOut
WHERE sse.GroupWithPrevious = 0
GROUP BY sse.FKEmployeeNumber, sse.CheckIn, sse.FinalCheckOut
</code>```

Note: I think the last two records in your sample data should not be grouped

```<code>(26291, '12/05/2017', 3118, 1, 200, 23, 15, 5, 5),
(26291, '12/06/2017', 3118, 0, 200, 15, 14, 7, 5)   -- 11:15PM  7:05AM
</code>```

should be:

```<code>(26291, '12/05/2017', 3118, 1, 200, 23, 15, 5, 5),  -- 11:19PM  5:05AM
(26291, '12/06/2017', 3118, 0, 200, 15, 14, 7, 5)   -- 3:14PM  7:05AM
</code>```

Body:
I have a few questions on how to handle a few employee timekeeping queries in SQL 2012…  I had asked another quesiton last week about determining the time between shifts, which I as able to get a great response to.

We are fed the data from our Point Of Sale Software Provider, so we cannot change the format of the data.

Work days are based on DateOfBusiness which are from 5:00 am until 4:59am the next calendar day, so it crosses midnight.  Locations End Of Day process is offset a little to control balance loads, some are 5:05am instead of 5:00am.  When the End Of Day process runs, it clocks everyone out then clocks them back in when the process completes.
    - Employees clock out for the 30 minute required meal breaks, so there are 2 or more records for one day for these employees. Not sure why, but several employees have more than 3 records in one day (EmployeeShiftNumber).
    - Shifts occasionally cross DateOfBusiness.  In at 11:00PM - Out at 7:00am

I need to report list of initial InTime and Final OutTime and the number of minutes worked. I have will have to compare these against the table which holds the employee schedules.  This reporting is not for Payroll purposes, but for comparisons against scheduled shifts.

I have included some sample data grouped by employee and by day and the values I would expect to see commented to the right.  I also need to see the number of minutes worked in the shift.

--drop table #Shift

CREATE TABLE #Shift(
    FKEmployeeNumber int,
    DateOfBusiness datetime,
    FKStoreId int,
    EmployeeShiftNumber int,
    FKJobCodeId int,
    InHour int,
    InMinute int,
    OutHour int,
    OutMinute int)

insert into #Shift ( FKEmployeeNumber, DateOfBusiness, FKStoreId, EmployeeShiftNumber, FKJobCodeId, InHour, InMinute,OutHour,OutMinute)
values
(23761, '11/30/2017', 3013, 0, 1, 17, 39, 21, 30),
(23761, '11/30/2017', 3013, 1, 1, 21, 30, 2, 39),   -- 5:39PM  2:39AM

(23770, '11/30/2017', 3013, 0, 200, 7, 19, 16, 25), -- 7:19AM  4:25PM

(23938, '11/30/2017', 3013, 0, 1, 16, 4, 1, 26),    -- 4:04AM  1:26AM

(24006, '11/30/2017', 3013, 0, 1, 7, 30, 18, 36),
(24006, '11/30/2017', 3013, 1, 1, 18, 36, 18, 40),  -- 7:30AM  6:40PM

(24018, '11/30/2017', 3013, 0, 2, 8, 52, 17, 0),    -- 8:52M  4:00PM

(25176, '11/30/2017', 3013, 0, 200, 15, 59, 20, 1), -- 3:59PM  8:01PM

(25176, '11/30/2017', 3013, 1, 200, 20, 30, 0, 05), -- 8:30PM  12:05AM

(25180, '11/30/2017', 3013, 0, 1, 21, 0, 5, 0),     -- 9:00PM  5:00AM

(25187, '11/30/2017', 3013, 0, 1, 10, 0, 16, 6),    -- 10:00AM  4:06PM

(35189, '11/30/2017', 3013, 0, 1, 16, 58, 2, 4),    -- 4:58PM  2:04AM

(25147, '12/04/2017', 3106, 0, 1, 6, 58, 15, 2),
(25147, '12/04/2017', 3106, 1, 1, 15, 3, 15, 3),    -- 6:58AM  3:03PM

(26291, '12/01/2017', 3118, 1, 200, 23, 15, 5, 5),
(26291, '12/02/2017', 3118, 0, 200, 5, 6, 7, 22),   -- 11:15PM  7:22AM

(26291, '12/03/2017', 3118, 0, 200, 7, 30, 15, 38), -- 7:30AM  3:38PM

(26291, '12/04/2017', 3118, 0, 200, 23, 15, 5, 5),
(26291, '12/05/2017', 3118, 0, 200, 5, 6, 7, 12),   -- 11:15PM  7:12AM

(26291, '12/05/2017', 3118, 1, 200, 23, 15, 5, 5),
(26291, '12/06/2017', 3118, 0, 200, 15, 14, 7, 5)   -- 11:15PM  7:05AM
--Select * from #Shift

SELECT fkstoreid, FKEmployeeNumber AS EmpID, DateOfBusiness AS Date,
    RIGHT(CONVERT(varchar(30), DATEADD(MINUTE, InTime_Mins, 0), 100), 7) AS InTime,
    RIGHT(CONVERT(varchar(30), DATEADD(MINUTE, OutTime_Mins, 0), 100), 7) AS OutTime,
    MinsWorked
FROM (
    select sh.FKStoreId, sh.FKEmployeeNumber, sh.DateOfBusiness,
        MIN(sh.InHour*60+InMinute) AS InTime_Mins,
        MAX(sh.OutHour*60+OutMinute) AS OutTime_Mins,
        SUM(((sh.outhour+case when sh.OutHour < sh.InHour then 24 else 0 end)*60 + sh.outminute) -
             (sh.inhour*60 + sh.inminute)) AS MinsWorked
    from #shift sh
    group by sh.FKStoreId,sh.FKEmployeeNumber, sh.DateOfBusiness
) AS derived
order by FKEmployeeNumber, DateOfBusiness

Body:
I've written a sample of how you could do it.

Briefly summarized I perform these steps:

Mark records that should be grouped with either the next or the previous record, because they are a part of the same shift.

Find the start and end of each shift

Join all records for an employee that fall within each shift

Group the resultset per employee per shift, and calculate the minutes worked by summing up the minutes between checkin and checkout for each record within a shift.

Sample query:

WITH ShiftParts AS (
    SELECT
        FKEmployeeNumber,
        DATEADD(MINUTE, InMinute, DATEADD(HOUR, InHour, DateOfBusiness)) CheckIn, --Datetime of the checkin
        DATEADD(DAY, CASE WHEN OutHour < InHour THEN 1 ELSE 0 END,
            DATEADD(MINUTE, OutMinute, DATEADD(HOUR, OutHour, DateOfBusiness))) CheckOut --Datetime of the checkout (add one day if we crossed midnight).
    FROM #Shift
),
GroupInfo AS (
    SELECT
        *,
        CASE
            WHEN DATEDIFF(MINUTE, LAG(CheckOut, 1, NULL) OVER (PARTITION BY FKEmployeeNumber ORDER BY CheckOut), CheckIn) <= 120
            THEN 1 ELSE 0 END AS GroupWithPrevious, --Determine whether we want to group this record with the previous
        CASE
            WHEN DATEDIFF(MINUTE, CheckOut, LEAD(CheckIn, 1, NULL) OVER (PARTITION BY FKEmployeeNumber ORDER BY CheckOut)) <= 120
            THEN 1 ELSE 0 END AS GroupWithNext --Determine whether we want to group this record with the next
    FROM ShiftParts
), ShiftStartAndEnd AS (
    SELECT
        *,
        CASE WHEN GroupWithNext = 1 THEN LEAD(CheckOut, 1, NULL) OVER (PARTITION BY FKEmployeeNumber ORDER BY CheckOut) ELSE CheckOut END AS FinalCheckOut
    FROM GroupInfo
    WHERE GroupWithPrevious = 0 OR GroupWithNext = 0 --Only pick beginning and end of a shift
)
SELECT
    sse.FKEmployeeNumber,
    sse.CheckIn,
    sse.FinalCheckOut,
    SUM(DATEDIFF(MINUTE,sp.CheckIn,sp.CheckOut)) AS MinutesWorked
FROM ShiftStartAndEnd sse
    LEFT OUTER JOIN ShiftParts sp ON sp.FKEmployeeNumber = sse.FKEmployeeNumber AND sp.CheckIn >= sse.CheckIn AND sp.CheckOut <= sse.FinalCheckOut
WHERE sse.GroupWithPrevious = 0
GROUP BY sse.FKEmployeeNumber, sse.CheckIn, sse.FinalCheckOut

Note: I think the last two records in your sample data should not be grouped

(26291, '12/05/2017', 3118, 1, 200, 23, 15, 5, 5),
(26291, '12/06/2017', 3118, 0, 200, 15, 14, 7, 5)   -- 11:15PM  7:05AM

should be:

(26291, '12/05/2017', 3118, 1, 200, 23, 15, 5, 5),  -- 11:19PM  5:05AM
(26291, '12/06/2017', 3118, 0, 200, 15, 14, 7, 5)   -- 3:14PM  7:05AM


问:
Setting the value of an unsigned char * in c++
I've got a function that takes an unsigned char * as a parameter, but the data I'm being sent is throwing a type mismatch error.

```<code>int main()
  {
  Queue * queue = newQueue ();
  addByteToQueue (queue, 1);
  addByteToQueue (queue, 2);
  addByteToQueue (queue, 3);
  return 0;
  }

void addByteToQueue (Queue * queue, unsigned char * byte)
  {
  // stuff
  }
</code>```

Visual studio is counting the 1/2/3 in the function calls as integers, which makes sense to me.  As a test, I also tried doing this:

```<code>unsigned char * a = 1;
</code>```

Similar error.  Now, I can't change the function prototype.  Assuming I'm being sent bad data in the call, how would one go about assigning the value of an unsigned char pointer?  Alternatively, is there some other crucial thing I'm missing that would make this work the way it is?

答:
You are setting the pointer to an unsigned char to 1, 2, 3.

That is, you are telling the program that an unsigned char value can be found in memory at the address "1" (or "2" or...).

What you need to do is pass on the pointer to an actually existing unsigned char in memory.

Since it is unclear what you actually want to be doing with all this or why you need an unsigned char*, here is a very simple example:

```<code>unsigned char* test = new unsigned char(); // Create an unsigned char in the heap, note that you need to delete it later or it will be memory leak
*test = 60;  // Assign a value to it
addByteToQueue(queue, test);
</code>```

Body:
I've got a function that takes an unsigned char * as a parameter, but the data I'm being sent is throwing a type mismatch error.

int main()
  {
  Queue * queue = newQueue ();
  addByteToQueue (queue, 1);
  addByteToQueue (queue, 2);
  addByteToQueue (queue, 3);
  return 0;
  }

void addByteToQueue (Queue * queue, unsigned char * byte)
  {
  // stuff
  }

Visual studio is counting the 1/2/3 in the function calls as integers, which makes sense to me.  As a test, I also tried doing this:

unsigned char * a = 1;

Similar error.  Now, I can't change the function prototype.  Assuming I'm being sent bad data in the call, how would one go about assigning the value of an unsigned char pointer?  Alternatively, is there some other crucial thing I'm missing that would make this work the way it is?

Body:
You are setting the pointer to an unsigned char to 1, 2, 3.

That is, you are telling the program that an unsigned char value can be found in memory at the address "1" (or "2" or...).

What you need to do is pass on the pointer to an actually existing unsigned char in memory.

Since it is unclear what you actually want to be doing with all this or why you need an unsigned char*, here is a very simple example:

unsigned char* test = new unsigned char(); // Create an unsigned char in the heap, note that you need to delete it later or it will be memory leak
*test = 60;  // Assign a value to it
addByteToQueue(queue, test);


问:
Sequelize PostgreSQL: Change Column type string to array of String
I'm using the Sequelize ORM with PostgreSQL.

I need to Change the type of a column from String to Array[String].

I used this migration Script

up: (queryInterface, Sequelize) => {
      return queryInterface.changeColumn('email','to', {
        type:Sequelize.ARRAY(Sequelize.TEXT),
                allowNull: false
      });
  }

ERROR: column "to" cannot be cast automatically to type text[]

I tried the answer from this link but It does not work for me

Please let me know If I'm doing something wrong.

答:
It was issue with pg@7.0.2

Downgrading to pg@6.4.1 fixes the issue.


问:
Call Twiml Object in Codeigniter - Twilio service
I am integrating twilio service in codeigniter. But currently, I don't know how to call Twiml object. In raw PHP, I can just code like this:

```<code>use Twilio\Twiml;
$response = new Twiml();
</code>```

But in codeigniter, I can only call the library twilio service (which i put in libraries folder) and cannot use Twiml object in controller.

```<code>$this->load->library( 'twilio_services' );
</code>```

This is where I download twilio service:
https://github.com/t1gr0u/codeigniter-twilio/tree/master/libraries

I try to search everywhere but can't find it. Anyone can help me.

答:
An alternate approach

Download Twilio PHP SDK and put it into the folder third_party

Copy this file and put into library folder as Btwilio.php

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH.'third_party/twilio/Twilio/autoload.php' ;
use Twilio\Rest\Client;
use Twilio\TwiML      ;  // TwiML used

class Btwilio {

    private $btwilio ;

    public function __construct()
    {
        $AccountSid = "AC008e63cc03eec3be4b1cfe7ab80478a0";
        $AuthToken = "82496aa3278d9cbebfc0f24ae1c1ba7f";

        $this->btwilio = new Client($AccountSid, $AuthToken);

        $this->btwiml  = new Twiml();

    }

    public function sendsms()
    {

        $people = array(
        "+919048XXXXXX" => "Rajeev"
        );

        // Step 5: Loop over all our friends. $number is a phone number above, and
        // $name is the name next to it
        foreach ($people as $number => $name) {

            $sms = $this->btwilio->account->messages->create(

                // the number we are sending to - Any phone number
                $number,

                array(
                    // Step 6: Change the 'From' number below to be a valid Twilio number
                    // that you've purchased
                    'from' => "+18559063122",

                    // the sms body
                    'body' => "Hey $name, Monkey Party at 6PM. Bring Bananas!"
                )
            );

            // Display a confirmation message on the screen
            echo "Sent message to $name";
        }

    }

    public function sendtwiml()
    {

        // $this->btwiml  = new Twiml();  use $this->btwiml to use Twiml services

        // Step 5: Loop over all our friends. $number is a phone number above, and
        // $name is the name next to it
        //$response = new Twiml();
        $this->btwiml->sms('The king stay the king.', ['from' => '+14105551234',
            'to' => '+919048309695']);

        print_r($this->btwiml) ;

    }

}

/* End of file Btwilio.php */
/* Location: ./application/libraries/Btwilio.php */
</code>```

Call this library on your controller like

```<code>$this->load->library('btwilio');

$this->btwilio->sendsms() ; // method created on Btwilio library

$this->btwilio->sendtwiml() ; // method of TwiML example
</code>```

Create custom Methods in this library which can use from official Twilio

Link is Here

You have to use $this->btwilio because we have instantiated to this one

Body:
I am integrating twilio service in codeigniter. But currently, I don't know how to call Twiml object. In raw PHP, I can just code like this:

use Twilio\Twiml;
$response = new Twiml();

But in codeigniter, I can only call the library twilio service (which i put in libraries folder) and cannot use Twiml object in controller.

$this->load->library( 'twilio_services' );

This is where I download twilio service:
https://github.com/t1gr0u/codeigniter-twilio/tree/master/libraries

I try to search everywhere but can't find it. Anyone can help me.

Body:
An alternate approach

Download Twilio PHP SDK and put it into the folder third_party

Copy this file and put into library folder as Btwilio.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH.'third_party/twilio/Twilio/autoload.php' ;
use Twilio\Rest\Client;
use Twilio\TwiML      ;  // TwiML used

class Btwilio {

    private $btwilio ;

    public function __construct()
    {
        $AccountSid = "AC008e63cc03eec3be4b1cfe7ab80478a0";
        $AuthToken = "82496aa3278d9cbebfc0f24ae1c1ba7f";

        $this->btwilio = new Client($AccountSid, $AuthToken);

        $this->btwiml  = new Twiml();

    }

    public function sendsms()
    {

        $people = array(
        "+919048XXXXXX" => "Rajeev"
        );

        // Step 5: Loop over all our friends. $number is a phone number above, and
        // $name is the name next to it
        foreach ($people as $number => $name) {

            $sms = $this->btwilio->account->messages->create(

                // the number we are sending to - Any phone number
                $number,

                array(
                    // Step 6: Change the 'From' number below to be a valid Twilio number
                    // that you've purchased
                    'from' => "+18559063122",

                    // the sms body
                    'body' => "Hey $name, Monkey Party at 6PM. Bring Bananas!"
                )
            );

            // Display a confirmation message on the screen
            echo "Sent message to $name";
        }

    }

    public function sendtwiml()
    {

        // $this->btwiml  = new Twiml();  use $this->btwiml to use Twiml services

        // Step 5: Loop over all our friends. $number is a phone number above, and
        // $name is the name next to it
        //$response = new Twiml();
        $this->btwiml->sms('The king stay the king.', ['from' => '+14105551234',
            'to' => '+919048309695']);

        print_r($this->btwiml) ;

    }

}

/* End of file Btwilio.php */
/* Location: ./application/libraries/Btwilio.php */

Call this library on your controller like

$this->load->library('btwilio');

$this->btwilio->sendsms() ; // method created on Btwilio library

$this->btwilio->sendtwiml() ; // method of TwiML example

Create custom Methods in this library which can use from official Twilio

Link is Here

You have to use $this->btwilio because we have instantiated to this one


问:
How to get the name of decorator for function at run time?
In the following code the methods(print_a and print_b) of class Test, has been decorated by the two different decorators.

How can I determine that the given method(let say print_a), is decorated with some specific decorator (decorator1) at the runtime?

The easy solution is to change the name of the wrapper function, i.e. changing the wrapper to wrapper1 and wrapper2 in the decorator method, but the problem with that is I don't have control over that part of the code.

Does python have any reflection API like Java, and could that help me here ?

```<code>def my_decorator1(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:1')
        func(*args, **kwargs)
    return wrapper

def my_decorator2(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:2')
        func(*args, **kwargs)
    return wrapper

class Test():

    def __init__(self, a=None, b=None):
        self.a = a
        self.b = b

    @my_decorator1
    def print_a(self):
        print('Value of a is {}'.format(self.a))

    @my_decorator2
    def print_b(self):
        print('Value of b is {}'.format(self.b))

if __name__ == '__main__':

    d = Test.__dict__

    f1 = d.get('print_a')
    f2 = d.get('print_b')
</code>```

答:
Python decorators are more about transforming functions than about acting as simple metadata labels, as one often does with Java annotations. So to do this, I'd have the decorator set a property on the function it is wrapping (or perhaps wrap it in a callable of a particular type):

```<code>def my_decorator1(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:1')
        func(*args, **kwargs)
    wrapper.decorator_name = 'my_decorator1'
    return wrapper
</code>```

Then:

```<code>print(Test.print_a.decorator_name)
</code>```

Alternatively, in Python 3.3+ you can use PEP 3155's __qualname__ to identify the decorator.

Body:
In the following code the methods(print_a and print_b) of class Test, has been decorated by the two different decorators.

How can I determine that the given method(let say print_a), is decorated with some specific decorator (decorator1) at the runtime?

The easy solution is to change the name of the wrapper function, i.e. changing the wrapper to wrapper1 and wrapper2 in the decorator method, but the problem with that is I don't have control over that part of the code.

Does python have any reflection API like Java, and could that help me here ?

def my_decorator1(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:1')
        func(*args, **kwargs)
    return wrapper

def my_decorator2(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:2')
        func(*args, **kwargs)
    return wrapper

class Test():

    def __init__(self, a=None, b=None):
        self.a = a
        self.b = b

    @my_decorator1
    def print_a(self):
        print('Value of a is {}'.format(self.a))

    @my_decorator2
    def print_b(self):
        print('Value of b is {}'.format(self.b))

if __name__ == '__main__':

    d = Test.__dict__

    f1 = d.get('print_a')
    f2 = d.get('print_b')

Body:
Python decorators are more about transforming functions than about acting as simple metadata labels, as one often does with Java annotations. So to do this, I'd have the decorator set a property on the function it is wrapping (or perhaps wrap it in a callable of a particular type):

def my_decorator1(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:1')
        func(*args, **kwargs)
    wrapper.decorator_name = 'my_decorator1'
    return wrapper

Then:

print(Test.print_a.decorator_name)

Alternatively, in Python 3.3+ you can use PEP 3155's __qualname__ to identify the decorator.


问:
How to see model class in H2 database
I cannot see my tables that I created as model class in h2 database console.

Actually I can access the h2 database (by writing localhost:/h2-console). But I can't see my tables.

Altough I added @Entity annotation, I can not see the table in h2-database.

Product model class:

```<code>package com.example;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;

/**
 * Created by jt on 11/6/15.
 */
@Entity
public class Product implements DomainObject{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String description;
    private BigDecimal price;
    private String imageUrl;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}
</code>```

答: I solved the problem. I corrected my jdbc url for u2 database. Now, I can see my tables(model class) that I created via java.</p>

Title: How to see model class in H2 database

Body:
I cannot see my tables that I created as model class in h2 database console.

Actually I can access the h2 database (by writing localhost:/h2-console). But I can't see my tables.

Altough I added @Entity annotation, I can not see the table in h2-database.

Product model class:

package com.example;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;

/**
 * Created by jt on 11/6/15.
 */
@Entity
public class Product implements DomainObject{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String description;
    private BigDecimal price;
    private String imageUrl;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}


问:
combining two dictionaries after removing some componetnts
I have two dictionaries as follows.

```<code>  A=  {'photos': {'page': 1,
  'pages': 2,
  'perpage': 250,
  'photo': [{'accuracy': '16',
    'context': 0,
    'datetaken': '2013-05-03 13:47:02',
    'datetakengranularity': '0',
    'datetakenunknown': '0',
    'farm': 5,
    'geo_is_contact': 0,
    'geo_is_family': 0,
    'geo_is_friend': 0,
    'geo_is_public': 1,
    'id': '26970758199',
    'isfamily': 0,
    'isfriend': 0,
    'ispublic': 1,
    'latitude': '5.944650',
    'longitude': '80.459766',
    'owner': '61943224@N04',
    'place_id': 'kLamY9hTU7IVDlGv',
    'secret': '1383a29a3b',
    'server': '4563',
    'title': 'Mirissa - Ask your Local Tour Dog',
    'woeid': '2182931'},
   {'accuracy': '14',
    'context': 0,
    'datetaken': '2017-09-28 18:13:17',
    'datetakengranularity': 0,
    'datetakenunknown': '1',
    'farm': 5,
    'geo_is_contact': 0,
    'geo_is_family': 0,
    'geo_is_friend': 0,
    'geo_is_public': 1,
    'id': '37343882352',
    'isfamily': 0,
    'isfriend': 0,
    'ispublic': 1,
    'latitude': '5.930026',
    'longitude': '80.405502',
    'owner': '7415626@N04',
    'place_id': 'J1bv5NZTU70_mRm8',
    'secret': 'c7135b74d2',
    'server': '4335',
    'title': 'Blue whale tail',
    'woeid': '2179328'}],
  'total': '2'},
 'stat': 'ok'}
</code>```

and the second dictonary  as follows:

```<code>    B={'photos': {'page': 2,
      'pages': 2,
      'perpage': 250,
      'photo': [{'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 12:02:57',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8516011398',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': 'e6c6b8548c',
        'server': '8112',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'},
       {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 11:13:47',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8514896103',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '17df7f97e7',
        'server': '8375',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'}],
  'total': '2'},
 'stat': 'ok'}
</code>```

I want to merge this dictonaries together after removing the

```<code>{'photos': {'page': '',
      'pages': '',
      'perpage': '',
</code>```

and removing the last section of each of A and B dictionaries,

```<code>  'total': ''},
 'stat': ''}
</code>```

sections in both A and B. So my final output should be like this,

```<code>C='photo': [{'accuracy': '16',
        'context': 0,
        'datetaken': '2013-05-03 13:47:02',
        'datetakengranularity': '0',
        'datetakenunknown': '0',
        'farm': 5,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '26970758199',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.944650',
        'longitude': '80.459766',
        'owner': '61943224@N04',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '1383a29a3b',
        'server': '4563',
        'title': 'Mirissa - Ask your Local Tour Dog',
        'woeid': '2182931'},
       {'accuracy': '14',
        'context': 0,
        'datetaken': '2017-09-28 18:13:17',
        'datetakengranularity': 0,
        'datetakenunknown': '1',
        'farm': 5,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '37343882352',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.930026',
        'longitude': '80.405502',
        'owner': '7415626@N04',
        'place_id': 'J1bv5NZTU70_mRm8',
        'secret': 'c7135b74d2',
        'server': '4335',
        'title': 'Blue whale tail',
        'woeid': '2179328'},
       {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 12:02:57',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8516011398',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': 'e6c6b8548c',
        'server': '8112',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'},
        {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 11:13:47',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8514896103',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '17df7f97e7',
        'server': '8375',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'}]
</code>```

I have tried several dictionaries merging methods, and none of those yield results, I'm bit new to python. I would be grateful if someone can help.

答:
Try this:-

```<code>C = A['photos']['photo']
C.extend(B['photos']['photo'])
D = {'photo': C}
print(D)
</code>```

Basically You need item photo from both the dictionaries. Since this Item's value is a list, we can create a new list called C with one list and extend the other list.

Reference:- Python List extend()

Body:
I have two dictionaries as follows.

  A=  {'photos': {'page': 1,
  'pages': 2,
  'perpage': 250,
  'photo': [{'accuracy': '16',
    'context': 0,
    'datetaken': '2013-05-03 13:47:02',
    'datetakengranularity': '0',
    'datetakenunknown': '0',
    'farm': 5,
    'geo_is_contact': 0,
    'geo_is_family': 0,
    'geo_is_friend': 0,
    'geo_is_public': 1,
    'id': '26970758199',
    'isfamily': 0,
    'isfriend': 0,
    'ispublic': 1,
    'latitude': '5.944650',
    'longitude': '80.459766',
    'owner': '61943224@N04',
    'place_id': 'kLamY9hTU7IVDlGv',
    'secret': '1383a29a3b',
    'server': '4563',
    'title': 'Mirissa - Ask your Local Tour Dog',
    'woeid': '2182931'},
   {'accuracy': '14',
    'context': 0,
    'datetaken': '2017-09-28 18:13:17',
    'datetakengranularity': 0,
    'datetakenunknown': '1',
    'farm': 5,
    'geo_is_contact': 0,
    'geo_is_family': 0,
    'geo_is_friend': 0,
    'geo_is_public': 1,
    'id': '37343882352',
    'isfamily': 0,
    'isfriend': 0,
    'ispublic': 1,
    'latitude': '5.930026',
    'longitude': '80.405502',
    'owner': '7415626@N04',
    'place_id': 'J1bv5NZTU70_mRm8',
    'secret': 'c7135b74d2',
    'server': '4335',
    'title': 'Blue whale tail',
    'woeid': '2179328'}],
  'total': '2'},
 'stat': 'ok'}

and the second dictonary  as follows:

    B={'photos': {'page': 2,
      'pages': 2,
      'perpage': 250,
      'photo': [{'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 12:02:57',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8516011398',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': 'e6c6b8548c',
        'server': '8112',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'},
       {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 11:13:47',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8514896103',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '17df7f97e7',
        'server': '8375',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'}],
  'total': '2'},
 'stat': 'ok'}

I want to merge this dictonaries together after removing the

{'photos': {'page': '',
      'pages': '',
      'perpage': '',

and removing the last section of each of A and B dictionaries,

  'total': ''},
 'stat': ''}

sections in both A and B. So my final output should be like this,

C='photo': [{'accuracy': '16',
        'context': 0,
        'datetaken': '2013-05-03 13:47:02',
        'datetakengranularity': '0',
        'datetakenunknown': '0',
        'farm': 5,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '26970758199',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.944650',
        'longitude': '80.459766',
        'owner': '61943224@N04',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '1383a29a3b',
        'server': '4563',
        'title': 'Mirissa - Ask your Local Tour Dog',
        'woeid': '2182931'},
       {'accuracy': '14',
        'context': 0,
        'datetaken': '2017-09-28 18:13:17',
        'datetakengranularity': 0,
        'datetakenunknown': '1',
        'farm': 5,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '37343882352',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.930026',
        'longitude': '80.405502',
        'owner': '7415626@N04',
        'place_id': 'J1bv5NZTU70_mRm8',
        'secret': 'c7135b74d2',
        'server': '4335',
        'title': 'Blue whale tail',
        'woeid': '2179328'},
       {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 12:02:57',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8516011398',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': 'e6c6b8548c',
        'server': '8112',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'},
        {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 11:13:47',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8514896103',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '17df7f97e7',
        'server': '8375',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'}]

I have tried several dictionaries merging methods, and none of those yield results, I'm bit new to python. I would be grateful if someone can help.

Body:
Try this:-

C = A['photos']['photo']
C.extend(B['photos']['photo'])
D = {'photo': C}
print(D)

Basically You need item photo from both the dictionaries. Since this Item's value is a list, we can create a new list called C with one list and extend the other list.

Reference:- Python List extend()