问:
Capture and write string inside of dataframe using foreach row
Trying to capture and write a string value after substituting contents obtained from specific fields from each row of a dataframe using scala. But since it is deployed on cluster not able to capture any records. Can anyone provide a solution? </p>

<p>Assuming TEST_DB.finalresult has 2 fields input1 and input2: </p>

```<code>val finalresult=spark.sql("select * from TEST_DB.finalresult")

finalResult.foreach { row =>
    val param1=row.getAs("input1").asInstanceOf[String]
    val param2=row.getAs("input2").asInstanceOf[String]

    val string = """new values of param1 and param2 are -> """ + param1 + """,""" + param2
    // how to append modified string to csv file continously for each microbatch in hdfs ??
}
</code>```

答:
In your code you create the wanted string variable but it is not being saved anywhere, hence you can't see the result.

You can potentially in each foreach execution open up the wanted csv file and append the new string, but I'd like to propose a different solution.

If you can, try to always use built-in functionality of Spark, since it is (usually) more optimised and better in handling null inputs. You can achieve the same by:

```<code>import org.apache.spark.sql.functions.{lit, concat, col}

val modifiedFinalResult = finalResult.select(
 concat(
  lit("new values of param1 and param2 are -> "),
  col("input1"),
  lit(","),
  col("input2")
 ).alias("string")
)
</code>```

In variable modifiedFinalResult you will have a spark dataframe with single column named string, which represents the exact same output as your variable string in your code. Afterwards you can save the dataframe directly as a single csv file (using the repartition functionality):

```<code>modifiedFinalResult.repartition(1).write.format("csv").save("path/to/your/csv/output")
</code>```

PS: Also a suggestion for the future, try to avoid naming variables after data types.

UPDATE: Fixed the empty rows issue by using "concat_ws" instead of concat and coalesce to each fields. It seems some of the values which were null were transforming the entire concatenated string to null after the transformation. Nevertheless this solution works for now!

Body:
Trying to capture and write a string value after substituting contents obtained from specific fields from each row of a dataframe using scala. But since it is deployed on cluster not able to capture any records. Can anyone provide a solution?

Assuming TEST_DB.finalresult has 2 fields input1 and input2:

val finalresult=spark.sql("select * from TEST_DB.finalresult")

finalResult.foreach { row =>
    val param1=row.getAs("input1").asInstanceOf[String]
    val param2=row.getAs("input2").asInstanceOf[String]

    val string = """new values of param1 and param2 are -> """ + param1 + """,""" + param2
    // how to append modified string to csv file continously for each microbatch in hdfs ??
}

Body:
In your code you create the wanted string variable but it is not being saved anywhere, hence you can't see the result.

You can potentially in each foreach execution open up the wanted csv file and append the new string, but I'd like to propose a different solution.

If you can, try to always use built-in functionality of Spark, since it is (usually) more optimised and better in handling null inputs. You can achieve the same by:

import org.apache.spark.sql.functions.{lit, concat, col}

val modifiedFinalResult = finalResult.select(
 concat(
  lit("new values of param1 and param2 are -> "),
  col("input1"),
  lit(","),
  col("input2")
 ).alias("string")
)

In variable modifiedFinalResult you will have a spark dataframe with single column named string, which represents the exact same output as your variable string in your code. Afterwards you can save the dataframe directly as a single csv file (using the repartition functionality):

modifiedFinalResult.repartition(1).write.format("csv").save("path/to/your/csv/output")

PS: Also a suggestion for the future, try to avoid naming variables after data types.

UPDATE: Fixed the empty rows issue by using "concat_ws" instead of concat and coalesce to each fields. It seems some of the values which were null were transforming the entire concatenated string to null after the transformation. Nevertheless this solution works for now!


来源: stackexchange

问:
What are differences between UDP and WCF in SOAP?
I am now working on a client-server communication project. I implemented the server using UDP client method by simply passing text strings between client and server. But I would like to change it to WCF method. I did some research online about WCF but still cannot figure out what are the difference between WCF and UDP. Need some explanation about it.</p>

答:
You are attempting to compare two different concepts. Per the Microsoft web site,

Windows Communication Foundation (WCF) is a framework for building
  service-oriented applications.
  https://learn.microsoft.com/en-us/dotnet/framework/wcf/whats-wcf

WCF supports a variety of formats - not just SOAP. WCF also supports a variety of transports - one of which is UDP.

The answer to your question is WCF is a client-server communication framework that supports, among many other things, SOAP using UDP.

ContentLicense: CC BY-SA 4.0


问:
my emulator does not show the same positioning of views as I design and see while making the app
I am using constraint layout and positioning 4 buttons in the middle of the screen in android studio but when I run the emulator. The buttons are shown at the bottom.
I am facing similar kind of problem while using relative layout. Nothing shows on the emulator the way I intend it to. I followed the

I went through the Android developer site to see how they place views in constraint layout. I did the same as instructed. I also went through some posts on Stack Overflow but I was unable to resolve this issue.

Kindly help me. Below is the image describing my problem
enter image description here

答: It appears that you have a 'hard'constraint that the top button has to be so many dp from the top of the screen, but the bottom constraint is 'flexible'.  Which means that in order to get the top space to match the hard constraint, on some devices, this might push it further down on the screen.  You could just try deleting the top and bottom constraints, or make them both hard constraints, or both flexible constraints.  I'm not that familiar with constraint editing, so, can't give you specific instructions.</p>


问:
How to set background image only for a part of the textView
I have a multiline textview and i want to set a background image only at the last three characters of the textview -> from tv.length() - 3 to tv.lenght()</p>

答:
This can help you a lot:

```<code>    String input = "stackoverflow.com";
    String firstCharactersResult = "";
    String lastThreeCharactersResult = "";

    if (input.length() > 3) {
        firstCharactersResult = input.substring(0, input.length() - 3);
        lastThreeCharactersResult = input.substring(input.length() - 3);

        textView.setText(HtmlCompat.fromHtml(firstCharactersResult + "<font color=\"red\">" + lastThreeCharactersResult + "</font>", 0));
    }
</code>```

If you want to change the background, This is simple use 2 TextViews!
Set the firstCharactersResult to first TextView and set the lastThreeCharactersResult to second TextView.

Body:
This can help you a lot:

    String input = "stackoverflow.com";
    String firstCharactersResult = "";
    String lastThreeCharactersResult = "";

    if (input.length() > 3) {
        firstCharactersResult = input.substring(0, input.length() - 3);
        lastThreeCharactersResult = input.substring(input.length() - 3);

        textView.setText(HtmlCompat.fromHtml(firstCharactersResult + "<font color=\"red\">" + lastThreeCharactersResult + "</font>", 0));
    }

If you want to change the background, This is simple use 2 TextViews!
Set the firstCharactersResult to first TextView and set the lastThreeCharactersResult to second TextView.


问:
Multiple ID selectors aren't working
So i have two Divs like this:

```<code><div id="first_content">
    <ul>
      <li>This</li>
      <li>text</li>
      <li>should</li>
      <li>be</li>
      <li>displayed</li>
      <li>in</li>
      <li>one</li>
      <li>line</li>
    </ul>
</div>

<div id="second_content">
    <ul>
      <li>This</li>
      <li>text</li>
      <li>should</li>
      <li>be</li>
      <li>displayed</li>
      <li>in</li>
      <li>one</li>
      <li>line</li>
    </ul>
</div>
</code>```

And CSS:

```<code>#first_content, #second_content ul {
    list-style: none;
}

#first_content, #second_content ul li {
    display: inline;
}
</code>```

It doesn't work (at least on firefox 34). Style applies only to one ID.

When i remove one of these ID selectors, another one works fine.

I guess it should work? what's wrong?

答:
Multiple id concatenation has never worked in Firefox. For example, I am using 67.0 (64-bit) and the following CSS works as intended:

```<code>#noDisplay {
   display: none;
}

#togForm {
   display: none;
}
</code>```

...but if I concatenate that, as shown below, it does not work (one id working, the other not working), and this has always been the case.

```<code>#noDisplay,#togForm {
   display: none;
}
</code>```

I know that sometimes the reason is because of conflicting entries, but display: none on its own? - Argue with that if you can!

ContentLicense: CC BY-SA 3.0

Title: Multiple ID selectors aren't working

Body:
So i have two Divs like this:

This

text

should

be

displayed

in

one

line

This

text

should

be

displayed

in

one

line

And CSS:

#first_content, #second_content ul {
    list-style: none;
}

#first_content, #second_content ul li {
    display: inline;
}

It doesn't work (at least on firefox 34). Style applies only to one ID.

When i remove one of these ID selectors, another one works fine.

I guess it should work? what's wrong?

Body:
Multiple id concatenation has never worked in Firefox. For example, I am using 67.0 (64-bit) and the following CSS works as intended:

#noDisplay {
   display: none;
}

#togForm {
   display: none;
}

...but if I concatenate that, as shown below, it does not work (one id working, the other not working), and this has always been the case.

#noDisplay,#togForm {
   display: none;
}

I know that sometimes the reason is because of conflicting entries, but display: none on its own? - Argue with that if you can!


问:
How can I stop Tabula from automatically dropping empty columns?
I am trying to scrape data from a PDF so that I can reformat it and then insert it to a table in Oracle. I am trying to use Tabula to read the PDF and convert it to a list of tables, but Tabula seems to be dropping columns from tables if those columns only hold null values.
Normally this wouldn't be an issue (the data is 'None' to begin with, so I don't care about preserving it), but dropping the 'null' values on certain columns but not on others makes it impossible for my code to identify which columns are which.
Eg, it might go from:

```<code>0   1   2   3

x   x  n/a  x

x   x  n/a  x

x   x  n/a  x
</code>```

to

```<code>0   1   2

x   x   x

x   x   x

x   x   x
</code>```

There is no way to know during runtime which column is being dropped, so I can't just re-insert it to the necessary place.

The columns do not have any unique identifiers in the data.
I can't just add a null column at the end because it is absolutely necessary that I keep the same ordering in the columns.

I have investigated the Tabula API, and while I found a number of handy guides for how to DROP null columns, I found nothing for ensuring that they stay present.

```<code>dflist = tabula.read_pdf(path, pages = '14-27', multiple_tables = True)
# dflist is a list of dataframes
# dflist[0] == a single dataframe
</code>```

(Apologies for poor formatting; unfamiliar with stack overflow spacing)

Expected results:

```<code>0   1   2   3

X   NaN X   X

X   NaN X   X

X   NaN X   NaN
</code>```

Actual results:

```<code>0   1   2

X   X   X

X   X   X

X   X   NaN
</code>```

答:
UPDATE: The best solution I could find was fiddling with the 'lattice' settings which determined how tables are read in Tabula (you can find documentation on their site).
Unfortunately, these settings also offset some of the rows on my PDF, so I couldn't use it. I had to give up the idea of making it entirely automated, and now use a staging table where a human checks which columns will be dropped.</p>

Body:
I am trying to scrape data from a PDF so that I can reformat it and then insert it to a table in Oracle. I am trying to use Tabula to read the PDF and convert it to a list of tables, but Tabula seems to be dropping columns from tables if those columns only hold null values.
Normally this wouldn't be an issue (the data is 'None' to begin with, so I don't care about preserving it), but dropping the 'null' values on certain columns but not on others makes it impossible for my code to identify which columns are which.
Eg, it might go from:

0   1   2   3

x   x  n/a  x

x   x  n/a  x

x   x  n/a  x

to

0   1   2

x   x   x

x   x   x

x   x   x

There is no way to know during runtime which column is being dropped, so I can't just re-insert it to the necessary place.

The columns do not have any unique identifiers in the data.
I can't just add a null column at the end because it is absolutely necessary that I keep the same ordering in the columns.

I have investigated the Tabula API, and while I found a number of handy guides for how to DROP null columns, I found nothing for ensuring that they stay present.

dflist = tabula.read_pdf(path, pages = '14-27', multiple_tables = True)
# dflist is a list of dataframes
# dflist[0] == a single dataframe

(Apologies for poor formatting; unfamiliar with stack overflow spacing)

Expected results:

0   1   2   3

X   NaN X   X

X   NaN X   X

X   NaN X   NaN

Actual results:

0   1   2

X   X   X

X   X   X

X   X   NaN


问:
How would you analyse a file too big for memory?
Recently I was asked this question in a live coding interview round by the recruiter. I was not sure how to do this with code.

I thought of splitting the file into multiple files and then read those chunks through multiple threads.

But I was not able to implement the same.

Any help with the implementation or some other approach will be appreciated !

答:
I would answer "It depends".  In an interview scenario, they're likely giving you a vague question intentionally to see where you go with it.  As others point out, finding out about the file, and what information you want to get out of it are key, and potential solutions could vary widely depending on these factors.

For example, if the file is in fact CSV, and you want to do potentially complex analysis on the data (sorts, counts, aggregations, etc), then pushing it into a relational database table, say H2, might not be a bad idea.  If the file contains more free-form text, you might want to index it with Lucene, or push it into an ElasticSearch index, and poke at it with Kibana.

None of these solutions are analyzing the file "with code" though, and would be completely ineffective if the file was, say, a 100GB movie clip.  Since they're asking how you would analyze the file "with code", I expect they're trying to see if you know how to do byte-oriented I/O (e.g. Java InputStream) vs character-oriented (e.g. Reader) and/or how to read through a potentially large  file using a buffer (i.e. without loading the whole file into memory).

Here's a simple code example...

```<code>import java.io.*;

public class StreamFile {
    /** Stream through a file using a buffer. */
    final static int BUFSIZE = 1024; // Use a 1K buffer.

    public static void main(String[] args) throws Exception {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(args[0])));
        long totalBytes = 0;
        byte[] buf = new byte[BUFSIZE];
        while (bis.available() > 0) {
            totalBytes += bis.read(buf, 0, BUFSIZE); // Do something here with the data in buf.
            System.out.println(totalBytes); // Show progress.
        }
        System.out.println("Read " + totalBytes + " bytes");
        bis.close();
    }
}
</code>```

Body:
I would answer "It depends".  In an interview scenario, they're likely giving you a vague question intentionally to see where you go with it.  As others point out, finding out about the file, and what information you want to get out of it are key, and potential solutions could vary widely depending on these factors.

For example, if the file is in fact CSV, and you want to do potentially complex analysis on the data (sorts, counts, aggregations, etc), then pushing it into a relational database table, say H2, might not be a bad idea.  If the file contains more free-form text, you might want to index it with Lucene, or push it into an ElasticSearch index, and poke at it with Kibana.

None of these solutions are analyzing the file "with code" though, and would be completely ineffective if the file was, say, a 100GB movie clip.  Since they're asking how you would analyze the file "with code", I expect they're trying to see if you know how to do byte-oriented I/O (e.g. Java InputStream) vs character-oriented (e.g. Reader) and/or how to read through a potentially large  file using a buffer (i.e. without loading the whole file into memory).

Here's a simple code example...

import java.io.*;

public class StreamFile {
    /** Stream through a file using a buffer. */
    final static int BUFSIZE = 1024; // Use a 1K buffer.

    public static void main(String[] args) throws Exception {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(args[0])));
        long totalBytes = 0;
        byte[] buf = new byte[BUFSIZE];
        while (bis.available() > 0) {
            totalBytes += bis.read(buf, 0, BUFSIZE); // Do something here with the data in buf.
            System.out.println(totalBytes); // Show progress.
        }
        System.out.println("Read " + totalBytes + " bytes");
        bis.close();
    }
}


问:
Display dynamic number of fields
I'm new to progress and I'm trying to learn dynamic queries. As a Task I gave to myself I want to read a csv file and create a table based on the contents of said file. So far everything works but I can't really seem to find a way to display the contents properly.

I have a temp-table created based on a csv input with the first line being the columns or fields of the table and everything after being the records.

```<code>Field1,Field2,Field3,Field4,Fieldn...
Value1.1,Value2.1,Value3.1,Value4.1,Valuen.1...
Value1.2,Value2.2,Value3.2,Value4.2,Valuen.1...
Value1.3,Value2.3,Value3.3,Value4.3,Valuen.1...
Value1.4,Value2.4,Value3.4,Value4.4,Valuen.1...
etc...
</code>```

How can I display a dynamic number of fields and their names properly?

The following things are unknown:

Number of fields

Name of fields

Values of records

The following works and shows the data in the desired format (but it's hard coded):

```<code>DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.
</code>```

I'm trying to loop over the buffer fields but I can't find a way to do it without redefining the DISPLAY command every iteration. Also I don't know how to display the labels of the fields in as a header row.

I'm looking for something like this :

```<code>/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE LABEL cTitlerow[i].
    END.
END.
</code>```

This would be the full code:

```<code>/*
Variables
*/
DEF VAR i AS INTEGER INITIAL 0 NO-UNDO. //Counter
DEF VAR iEntry AS INTEGER INITIAL 0 NO-UNDO. //Counter2
DEF VAR cTitleRow AS CHARACTER NO-UNDO. //Fields csv
DEF VAR cDataRow AS CHARACTER NO-UNDO. //Entries csv
DEF VAR cFieldName AS CHARACTER NO-UNDO. //Field
DEF VAR iNumFields AS INTEGER NO-UNDO. //Amount of Fields
DEF VAR iNumLines AS INTEGER NO-UNDO. //Amount of records
DEF VAR cTitleArray AS CHARACTER EXTENT NO-UNDO. //Fields Array
/*
Handles
*/
DEF VAR ttMyTable AS HANDLE NO-UNDO. //Temp table
DEF VAR bMyTable AS HANDLE NO-UNDO. //Buffer
DEF VAR qMyTable AS HANDLE NO-UNDO. //Query

INPUT FROM 'C:\Path\To\CSV\mycsv.csv'.

/*
Get first row for fields and field names
*/
IMPORT UNFORMATTED cTitleRow.
iNumFields = NUM-ENTRIES(cTitleRow) + 1. //Additional field for PK
EXTENT(cTitleArray) = iNumFields.

/*
Dynamic table creation
*/
CREATE TEMP-TABLE ttMyTable.
ttMyTable:ADD-NEW-FIELD('PK', 'integer').
cTitleArray[1] = 'PK'.
DO i = 2 to iNumFields:
    iEntry = i - 1.
    cFieldName = ENTRY(iEntry,cTitleRow).
    ttMyTable:ADD-NEW-FIELD(cFieldName, 'character').
    cTitleArray[i] = cFieldName.
END.

/*
Adding and defining indexes
*/
ttMyTable:ADD-NEW-INDEX('idx', TRUE, TRUE).
ttMyTable:ADD-INDEX-FIELD('idx', 'PK', 'asc').
ttMyTable:TEMP-TABLE-PREPARE('myTable').

/*
Creating buffer
*/
bMyTable = ttMyTable:DEFAULT-BUFFER-HANDLE.

/*
Populating data
*/
REPEAT:
    IMPORT UNFORMATTED cDataRow.
    bMyTable:BUFFER-CREATE.
    bMyTable::pk = iNumLines.
    DO i = 2 to iNumFields:
        iEntry = i - 1.
        bMyTable:BUFFER-FIELD(i):BUFFER-VALUE = ENTRY(iEntry,cDataRow).
        bMyTable:BUFFER-FIELD(i):COLUMN-LABEL = cTitleArray[i].
        bMyTable:BUFFER-FIELD(i):LABEL = cTitleArray[i].
    END.

    iNumLines = iNumLines + 1.
END.

/*
Creating query
*/
CREATE QUERY qMyTable.
qMyTable:SET-BUFFERS(bMyTable).
qMyTable:QUERY-PREPARE('for each myTable').
qMyTable:QUERY-OPEN().

/*
/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE.
    END.
END.
*/

DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.

qMyTable:QUERY-CLOSE().

DELETE OBJECT qMyTable.
</code>```

答:
This should get you started on creating a frame and a "text" widgets dynamically:

```<code>define variable f as handle no-undo.
define variable t as handle no-undo.

define variable r as integer no-undo initial 1.
define variable c as integer no-undo initial 1.

create frame f.
assign
  f:row           = 4
  f:column        = 1
  f:width-chars   = 132
  f:box           = no
  f:top-only      = false
  f:overlay       = true
  f:name          = "something"
no-error.

create text t.
assign
  t:frame        = f
  t:name         = "text1"
  t:format       = substitute( "x(&1)", max( 1, 20, length( t:name )))
  t:row          = r
  t:col          = c
  t:screen-value = "value1"
  f:height-chars = max( r, f:height-chars )
.

f:visible = yes.
</code>```

In your case you would probably want to create the frame just once at the top and then create 2 text widgets for each field - one for the label and one for the data values.

Title: Display dynamic number of fields

Body:
I'm new to progress and I'm trying to learn dynamic queries. As a Task I gave to myself I want to read a csv file and create a table based on the contents of said file. So far everything works but I can't really seem to find a way to display the contents properly.

I have a temp-table created based on a csv input with the first line being the columns or fields of the table and everything after being the records.

Field1,Field2,Field3,Field4,Fieldn...
Value1.1,Value2.1,Value3.1,Value4.1,Valuen.1...
Value1.2,Value2.2,Value3.2,Value4.2,Valuen.1...
Value1.3,Value2.3,Value3.3,Value4.3,Valuen.1...
Value1.4,Value2.4,Value3.4,Value4.4,Valuen.1...
etc...

How can I display a dynamic number of fields and their names properly?

The following things are unknown:

Number of fields

Name of fields

Values of records

The following works and shows the data in the desired format (but it's hard coded):

DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.

I'm trying to loop over the buffer fields but I can't find a way to do it without redefining the DISPLAY command every iteration. Also I don't know how to display the labels of the fields in as a header row.

I'm looking for something like this :

/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE LABEL cTitlerow[i].
    END.
END.

This would be the full code:

/*
Variables
*/
DEF VAR i AS INTEGER INITIAL 0 NO-UNDO. //Counter
DEF VAR iEntry AS INTEGER INITIAL 0 NO-UNDO. //Counter2
DEF VAR cTitleRow AS CHARACTER NO-UNDO. //Fields csv
DEF VAR cDataRow AS CHARACTER NO-UNDO. //Entries csv
DEF VAR cFieldName AS CHARACTER NO-UNDO. //Field
DEF VAR iNumFields AS INTEGER NO-UNDO. //Amount of Fields
DEF VAR iNumLines AS INTEGER NO-UNDO. //Amount of records
DEF VAR cTitleArray AS CHARACTER EXTENT NO-UNDO. //Fields Array
/*
Handles
*/
DEF VAR ttMyTable AS HANDLE NO-UNDO. //Temp table
DEF VAR bMyTable AS HANDLE NO-UNDO. //Buffer
DEF VAR qMyTable AS HANDLE NO-UNDO. //Query

INPUT FROM 'C:\Path\To\CSV\mycsv.csv'.

/*
Get first row for fields and field names
*/
IMPORT UNFORMATTED cTitleRow.
iNumFields = NUM-ENTRIES(cTitleRow) + 1. //Additional field for PK
EXTENT(cTitleArray) = iNumFields.

/*
Dynamic table creation
*/
CREATE TEMP-TABLE ttMyTable.
ttMyTable:ADD-NEW-FIELD('PK', 'integer').
cTitleArray[1] = 'PK'.
DO i = 2 to iNumFields:
    iEntry = i - 1.
    cFieldName = ENTRY(iEntry,cTitleRow).
    ttMyTable:ADD-NEW-FIELD(cFieldName, 'character').
    cTitleArray[i] = cFieldName.
END.

/*
Adding and defining indexes
*/
ttMyTable:ADD-NEW-INDEX('idx', TRUE, TRUE).
ttMyTable:ADD-INDEX-FIELD('idx', 'PK', 'asc').
ttMyTable:TEMP-TABLE-PREPARE('myTable').

/*
Creating buffer
*/
bMyTable = ttMyTable:DEFAULT-BUFFER-HANDLE.

/*
Populating data
*/
REPEAT:
    IMPORT UNFORMATTED cDataRow.
    bMyTable:BUFFER-CREATE.
    bMyTable::pk = iNumLines.
    DO i = 2 to iNumFields:
        iEntry = i - 1.
        bMyTable:BUFFER-FIELD(i):BUFFER-VALUE = ENTRY(iEntry,cDataRow).
        bMyTable:BUFFER-FIELD(i):COLUMN-LABEL = cTitleArray[i].
        bMyTable:BUFFER-FIELD(i):LABEL = cTitleArray[i].
    END.

    iNumLines = iNumLines + 1.
END.

/*
Creating query
*/
CREATE QUERY qMyTable.
qMyTable:SET-BUFFERS(bMyTable).
qMyTable:QUERY-PREPARE('for each myTable').
qMyTable:QUERY-OPEN().

/*
/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE.
    END.
END.
*/

DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.

qMyTable:QUERY-CLOSE().

DELETE OBJECT qMyTable.

Body:
This should get you started on creating a frame and a "text" widgets dynamically:

define variable f as handle no-undo.
define variable t as handle no-undo.

define variable r as integer no-undo initial 1.
define variable c as integer no-undo initial 1.

create frame f.
assign
  f:row           = 4
  f:column        = 1
  f:width-chars   = 132
  f:box           = no
  f:top-only      = false
  f:overlay       = true
  f:name          = "something"
no-error.

create text t.
assign
  t:frame        = f
  t:name         = "text1"
  t:format       = substitute( "x(&1)", max( 1, 20, length( t:name )))
  t:row          = r
  t:col          = c
  t:screen-value = "value1"
  f:height-chars = max( r, f:height-chars )
.

f:visible = yes.

In your case you would probably want to create the frame just once at the top and then create 2 text widgets for each field - one for the label and one for the data values.


问:
TinyMCE is glitchy/unusable in IE8
I'm using the jQuery version of TinyMCE 3.3.9.3

In firefox, it works fine (10 sec video depicting it in use): http://www.youtube.com/watch?v=TrAE0igfT3I

In IE8 (in IE8 standards mode), I can't type or click any buttons. However, if I use ctrl+v to paste, then I can start typing, but the buttons still don't work (a 45 sec video depicting it in use): http://www.youtube.com/watch?v=iBSRlE8D8F4

The jQuery TinyMCE demo on TinyMCE's site works for me in IE8.

Here's the init code:

```<code>$().ready(function(){

    function tinymce_focus(){
        $('.defaultSkin table.mceLayout').css({'border-color' : '#6478D7'});
        $('.defaultSkin table.mceLayout tr.mceFirst td').css({'border-top-color' : '#6478D7'});
        $('.defaultSkin table.mceLayout tr.mceLast td').css({'border-bottom-color' : '#6478D7'});
    }

    function tinymce_blur(){
        $('.defaultSkin table.mceLayout').css({'border-color' : '#93a6e1'});
        $('.defaultSkin table.mceLayout tr.mceFirst td').css({'border-top-color' : '#93a6e1'});
        $('.defaultSkin table.mceLayout tr.mceLast td').css({'border-bottom-color' : '#93a6e1'});
    }

    $('textarea.tinymce').tinymce({
        script_url : 'JS/tinymce/tiny_mce.js',
        theme : "advanced",
        mode : "exact",
        invalid_elements : "b,i,iframe,font,input,textarea,select,button,form,fieldset,legend,script,noscript,object,embed,table,img,a,h1,h2,h3,h4,h5,h6",

        //theme options
        theme_advanced_buttons1 : "cut,copy,paste,pastetext,pasteword,selectall,|,undo,redo,|,cleanup,removeformat,|",
        theme_advanced_buttons2 : "bold,italic,underline,|,bullist,numlist,|,forecolor,backcolor,|",
        theme_advanced_buttons3 : "",
        theme_advanced_buttons4 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "none",
        theme_advanced_resizing : false,

        //plugins
        plugins : "inlinepopups,paste",
        dialog_type : "modal",
        paste_auto_cleanup_on_paste : true,

        setup: function(ed){
            ed.onInit.add(function(ed){

                //check for addEventListener -- primarily supported by firefox only
                var edDoc = ed.getDoc();
                if ("addEventListener" in edDoc){
                    edDoc.addEventListener("focus", function(){
                        tinymce_focus();
                    }, false);

                    edDoc.addEventListener("blur", function(){
                        tinymce_blur();
                    }, false);
                }

            });
        }

    });

});
</code>```

Any ideas as to why it's not working in IE8?

[edit]: stripping everything out of the init (leaving just script_url and theme) results in the same symptoms

答: Check if you have a # in your URL while the Editor is initialized. Strange but I got a few problems because of it.  Making sure there is no # in URL did solve a couple of problems similar to this. Hope it works out with you.</p>

ContentLicense: CC BY-SA 2.5

Title: TinyMCE is glitchy/unusable in IE8

Body:
I'm using the jQuery version of TinyMCE 3.3.9.3

In firefox, it works fine (10 sec video depicting it in use): http://www.youtube.com/watch?v=TrAE0igfT3I

In IE8 (in IE8 standards mode), I can't type or click any buttons. However, if I use ctrl+v to paste, then I can start typing, but the buttons still don't work (a 45 sec video depicting it in use): http://www.youtube.com/watch?v=iBSRlE8D8F4

The jQuery TinyMCE demo on TinyMCE's site works for me in IE8.

Here's the init code:

$().ready(function(){

    function tinymce_focus(){
        $('.defaultSkin table.mceLayout').css({'border-color' : '#6478D7'});
        $('.defaultSkin table.mceLayout tr.mceFirst td').css({'border-top-color' : '#6478D7'});
        $('.defaultSkin table.mceLayout tr.mceLast td').css({'border-bottom-color' : '#6478D7'});
    }

    function tinymce_blur(){
        $('.defaultSkin table.mceLayout').css({'border-color' : '#93a6e1'});
        $('.defaultSkin table.mceLayout tr.mceFirst td').css({'border-top-color' : '#93a6e1'});
        $('.defaultSkin table.mceLayout tr.mceLast td').css({'border-bottom-color' : '#93a6e1'});
    }

    $('textarea.tinymce').tinymce({
        script_url : 'JS/tinymce/tiny_mce.js',
        theme : "advanced",
        mode : "exact",
        invalid_elements : "b,i,iframe,font,input,textarea,select,button,form,fieldset,legend,script,noscript,object,embed,table,img,a,h1,h2,h3,h4,h5,h6",

        //theme options
        theme_advanced_buttons1 : "cut,copy,paste,pastetext,pasteword,selectall,|,undo,redo,|,cleanup,removeformat,|",
        theme_advanced_buttons2 : "bold,italic,underline,|,bullist,numlist,|,forecolor,backcolor,|",
        theme_advanced_buttons3 : "",
        theme_advanced_buttons4 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "none",
        theme_advanced_resizing : false,

        //plugins
        plugins : "inlinepopups,paste",
        dialog_type : "modal",
        paste_auto_cleanup_on_paste : true,

        setup: function(ed){
            ed.onInit.add(function(ed){

                //check for addEventListener -- primarily supported by firefox only
                var edDoc = ed.getDoc();
                if ("addEventListener" in edDoc){
                    edDoc.addEventListener("focus", function(){
                        tinymce_focus();
                    }, false);

                    edDoc.addEventListener("blur", function(){
                        tinymce_blur();
                    }, false);
                }

            });
        }

    });

});

Any ideas as to why it's not working in IE8?

[edit]: stripping everything out of the init (leaving just script_url and theme) results in the same symptoms


问:
Sequelize String being output as [Object object]
In my Sequelize models I have this model

```<code>module.exports = function(sequelize, Sequelize) {
return sequelize.define('TradingPlan', {
  id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.INTEGER
  },
  name:Sequelize.STRING,
  symbol: Sequelize.STRING(10),
  symbol_pair: Sequelize.STRING(10),
  entry_type: Sequelize.STRING(10),
  conditional_long_entry_point: Sequelize.DECIMAL(18,8),
  conditional_short_entry_point: Sequelize.DECIMAL(18,8),
  entry_price: Sequelize.DECIMAL(18,8),
  entry_order_type: Sequelize.STRING(10),
  pyramid_entry: Sequelize.BOOLEAN,
  exchange: Sequelize.STRING(30),
  notes: Sequelize.STRING,  <----------This is the problem one
</code>```

When I retrieve the notes table data it outputs as

[object Object]

Then when I try to edit one of my posts in this table it will not accept it because it is an Object. Even though it is input as a String. I usually input This is a good note!

The error I receive is this

```<code>name: 'SequelizeValidationError',
errors:
 [ ValidationErrorItem {
   message: 'notes cannot be an array or an object',
   type: 'string violation',
   path: 'notes',
   value: [Object],
   origin: 'CORE',
   instance: [Object],
   validatorKey: 'not_a_string',
at Promise._settlePromiseFromHandler (C:\node\trade-
mentor\node_modules\bluebird\js\release\promise.js:517:31
)
</code>```

I haven't had any luck googling this, has anyone else seen this?

答: I had my datatype wrong in Mysql, I had it as Blob, I also changed my datatype in Sequelize to Text after doing more reading about it.

Body:
In my Sequelize models I have this model

module.exports = function(sequelize, Sequelize) {
return sequelize.define('TradingPlan', {
  id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.INTEGER
  },
  name:Sequelize.STRING,
  symbol: Sequelize.STRING(10),
  symbol_pair: Sequelize.STRING(10),
  entry_type: Sequelize.STRING(10),
  conditional_long_entry_point: Sequelize.DECIMAL(18,8),
  conditional_short_entry_point: Sequelize.DECIMAL(18,8),
  entry_price: Sequelize.DECIMAL(18,8),
  entry_order_type: Sequelize.STRING(10),
  pyramid_entry: Sequelize.BOOLEAN,
  exchange: Sequelize.STRING(30),
  notes: Sequelize.STRING,  <----------This is the problem one

When I retrieve the notes table data it outputs as

[object Object]

Then when I try to edit one of my posts in this table it will not accept it because it is an Object. Even though it is input as a String. I usually input This is a good note!

The error I receive is this

name: 'SequelizeValidationError',
errors:
 [ ValidationErrorItem {
   message: 'notes cannot be an array or an object',
   type: 'string violation',
   path: 'notes',
   value: [Object],
   origin: 'CORE',
   instance: [Object],
   validatorKey: 'not_a_string',
at Promise._settlePromiseFromHandler (C:\node\trade-
mentor\node_modules\bluebird\js\release\promise.js:517:31
)

I haven't had any luck googling this, has anyone else seen this?


问:
Is it possible to edit and save website content to server, making the change viewable by everyone?
I have created a website for a third party, who have no experience in editing HTML. However, the third party wishes to be able to edit the content on the website without having to open the files and edit it this way, they wish to do it somewhat WYSIWYG (For example, hit an "edit" button for the content they wish to edit). Is this possible to achieve? It is not an internal website, it has user tracking (this should obviously only be available to admin users).

Is there a way of making contents of a div editable, then saving the change directly to the server, so the content gets updated publicly?

I am currently researching the topic, and although I have found some indications that the solution may be a PHP script, I have yet to find any definitive solutions or examples of similar functionality.

答:
Yes you will need a backend language or framework to archive this. Where Javascript is used to interact with the page, the actual storage of information requires a database or similar technology.

Unfortunately which backend language or framework to choose really is the million dollar question. It largely depends on exactly what you are trying to accomplish, what your client or user is comfortable with, and how much experience you have programming.

PHP is fast and time tested backend language. Node is the new kid on the block, and it very popular also. Java and dotNet are on the way out. You can dig up a bunch more including Go, Python, Haskel, Etc.

You can use a languge listed above and start scripting away, but this can be time consuming and error prone. Most people use a framework to get started, and program using that framework's tools. The most popular PHP framework is WordPress, but it is designed for blogs and might not fit your use case. I use the framework Craft CMS which is very customizable. But the way you are phrasing the question a framework might be overkill. This is really up to you to decide after doing research into the available options and comparing them to what you wish to accomplish.

For the WYSIWYG, you might want to look into the following tools for the client to edit content:

https://imperavi.com/redactor/

https://ckeditor.com/

Hopefully this provides some direction, happy coding!


问:
Checking if column exists in BIMC table, SAP HANA
I have a HANA SQL query I execute to determine which cubes/views belong to a particular HANA catalog. I want to make sure I'm including HDI-based views in the results set, and to that end I want to use the QUALIFIED_NAME column in the BIMC_ALL_AUTHORIZED_CUBES/BIMC_CUBES etc system tables. However, I want to make sure I'm supporting pre-HDI version of HANA, so it's possible I'll encounter a case where the QUALIFIED_NAME column doesn't exist in one of those tables.

How can I check whether the QUALIFIED_NAME column exists in HANA SQL Script? Preferably without checking the HANA version.

答:
QUALIFIED_NAME was introduced in HANA 1 SPS 11. You can check the version of HANA in use using the following query:

Select VERSION from "SYS"."M_DATABASE"

You can interpret the version number returned using the following examples:

```<code>        01.00.0091 00-1418659308 => HANA 1.0 SPS09
        1.00.091.00.1418659308 => HANA 1.0 SPS09
        1.00.122.09.1493036600 => HANA 1.0 SPS12
</code>```

Body:
QUALIFIED_NAME was introduced in HANA 1 SPS 11. You can check the version of HANA in use using the following query:

Select VERSION from "SYS"."M_DATABASE"

You can interpret the version number returned using the following examples:

        01.00.0091 00-1418659308 => HANA 1.0 SPS09
        1.00.091.00.1418659308 => HANA 1.0 SPS09
        1.00.122.09.1493036600 => HANA 1.0 SPS12


问:
How to pass form values to route
I'm having trouble passing a value from a form to a route.

```<code>{!! Form::open(['method'=>'POST', 'action'=> 'ReportController@index']) !!}

<div class="radio">
     <label><input type="radio" name="report_option" class="report_option" value="call_details">Call Details</label>
</div>
</code>```

Route::post('reports/{report}', 'ReportController@index');

答:
The action value can be an array to which you can pass the parameter so try this instead:

```<code>{!! Form::open(['method'=>'POST', 'action'=> ['ReportController@index', $report]]) !!}
</code>```

Keep in mind that in the view you should have the $report.

Title: How to pass form values to route

Body:
I'm having trouble passing a value from a form to a route.

{!! Form::open(['method'=>'POST', 'action'=> 'ReportController@index']) !!}

     <input type="radio" name="report_option" class="report_option" value="call_details">Call Details

Route::post('reports/{report}', 'ReportController@index');

Body:
The action value can be an array to which you can pass the parameter so try this instead:

{!! Form::open(['method'=>'POST', 'action'=> ['ReportController@index', $report]]) !!}

Keep in mind that in the view you should have the $report.


问:
Problems with win32com
I have the following error in my code, I have tried everything and I can not solve:

1° Not Successful

excel = win32com.client.Dispatch("Excel.Application")
wb = excel.Workbooks.Open(os.path.join(os.getcwd(),diretorio_BKP + filename +
                          '  '+str(nome_arq_parcial)+' -.xlsx'))
ws = wb.Worksheets(1).Select()
ws = wb.Worksheets(1)
print('abrir o arquivo de novo')
```
<h1>2° Not Successful</h1>
<pre class="lang-py prettyprint-override"><code>excel = win32com.client.Dispatch("Excel.Application")
wb = excel.Workbooks.Open(diretorio_BKP + filename +'  '+
                          str(nome_arq_parcial)+' -.xlsx')
ws = wb.Worksheets(1).Select()
ws = wb.Worksheets(1)
print('abrir o arquivo de novo')
</code>```

The two attempts return the following problem to me:

ERRO:    (-2147352567, 'Exception.', (0, 'Microsoft Excel', "Microsoft Excel does not you can access the file '\\\\ IEMEN \\ file location -.xlsx'. There are several reasons possible: \ r \ n \ r \ n • The file name or path does not exist. \ r \ n • The file is being used by another program. \ r \ n • The workbook you are trying to save has the same name as another currently open \ r \ nfolder. ", 'xlmain11.chm', 0, -2146827284), None)
```

As you can see already tried to leave in absolute path, already tried to leave the full path, I already put excel.Application.Quit()
before that stretch as well and nothing.

I need the code to go through this step to start formatting the whole file.

答:
As the error messages details, there are several possible reasons for this error:

"The file name or path does not exist" - This means that the file you are trying to open was never created OR it may be that the path to the file is incorrect.

"The file is being used by another program" - This means that another program is actively using this file. You cannot make changes to an excel file while it is in use.

"The workbook you are trying to save has the same name as another currently open" - This means that the file name of the excel file that you are trying to work with is already taken inside that directory and that the other file is open or in use by another program.

Check to make sure that you are not violating any of the items above.

Title: Problems with win32com

Body:
I have the following error in my code, I have tried everything and I can not solve:

1° Not Successful

excel = win32com.client.Dispatch("Excel.Application")
wb = excel.Workbooks.Open(os.path.join(os.getcwd(),diretorio_BKP + filename +
                          '  '+str(nome_arq_parcial)+' -.xlsx'))
ws = wb.Worksheets(1).Select()
ws = wb.Worksheets(1)
print('abrir o arquivo de novo')

2° Not Successful

excel = win32com.client.Dispatch("Excel.Application")
wb = excel.Workbooks.Open(diretorio_BKP + filename +'  '+
                          str(nome_arq_parcial)+' -.xlsx')
ws = wb.Worksheets(1).Select()
ws = wb.Worksheets(1)
print('abrir o arquivo de novo')

The two attempts return the following problem to me:

ERRO:    (-2147352567, 'Exception.', (0, 'Microsoft Excel', "Microsoft Excel does not you can access the file '\\\\ IEMEN \\ file location -.xlsx'. There are several reasons possible: \ r \ n \ r \ n • The file name or path does not exist. \ r \ n • The file is being used by another program. \ r \ n • The workbook you are trying to save has the same name as another currently open \ r \ nfolder. ", 'xlmain11.chm', 0, -2146827284), None)

As you can see already tried to leave in absolute path, already tried to leave the full path, I already put excel.Application.Quit()
before that stretch as well and nothing.

I need the code to go through this step to start formatting the whole file.


问:
Nodemailer sendingRate works locally, but only sends the specified number of emails on Lambda
My transporter is set-up as such:

```<code> const ses = new aws.SES();
 var transporter = mailer.createTransport({
    SES: ses,
    sendingRate: 25
  });
</code>```

I have a sendEmail function that sets up an email to send an attachment:

```<code>function sendEmail(body, filename, customer_name) {
  var mailOptions = {
    from: "test@test.com",
    subject: "A test subject - " + customer_name,
    html: '<p>' + customer_name + '</p><br />Please see attached file.',
    to: "testing@testing.com",
    attachments: [
      {
          filename: filename + ".txt",
          content: body.toString()
      }
    ]
  };
  return transporter.sendMail(mailOptions);
};
</code>```

Within the Lambda, I add the sendEmail to an array of promises and process as such:

```<code>module.exports.publish = async (event, context, callback) => {
...
var promises = data.map(async (i) => {
  ...
  await sendEmail(data, file_prefix, customer_name);
};
await Promise.all(promises).then(() => {
   addMessageToLog('Emails sent successfully');
});
await sendSNS(logger).then(() => {
   if (isError) { callback(errorObj); }
   callback(null, 'Emails successfully sent.');
});
</code>```

My issue is that when I invoke this locally using the Serverless framework in VS Code, all my emails run perfectly fine at what seems like a 25/sec rate as specified. When I deploy to AWS Lambda, it simply sends 25 emails, then the request ends. Locally, it sends my SNS topic my log messages, but not on the Lambda. It abruptly ends at 25 every time.

Am I using the sendingRate correctly in this case? Why would the AWS Lambda end the request but not my test locally?

答:
I'll put this here for posterity in case anyone else runs into this...

I set the maxConnections to 1 and this fixed my issue on AWS.

Body:
My transporter is set-up as such:

 const ses = new aws.SES();
 var transporter = mailer.createTransport({
    SES: ses,
    sendingRate: 25
  });

I have a sendEmail function that sets up an email to send an attachment:

function sendEmail(body, filename, customer_name) {
  var mailOptions = {
    from: "test@test.com",
    subject: "A test subject - " + customer_name,
    html: '
' + customer_name + '

Please see attached file.',
    to: "testing@testing.com",
    attachments: [
      {
          filename: filename + ".txt",
          content: body.toString()
      }
    ]
  };
  return transporter.sendMail(mailOptions);
};

Within the Lambda, I add the sendEmail to an array of promises and process as such:

module.exports.publish = async (event, context, callback) => {
...
var promises = data.map(async (i) => {
  ...
  await sendEmail(data, file_prefix, customer_name);
};
await Promise.all(promises).then(() => {
   addMessageToLog('Emails sent successfully');
});
await sendSNS(logger).then(() => {
   if (isError) { callback(errorObj); }
   callback(null, 'Emails successfully sent.');
});

My issue is that when I invoke this locally using the Serverless framework in VS Code, all my emails run perfectly fine at what seems like a 25/sec rate as specified. When I deploy to AWS Lambda, it simply sends 25 emails, then the request ends. Locally, it sends my SNS topic my log messages, but not on the Lambda. It abruptly ends at 25 every time.

Am I using the sendingRate correctly in this case? Why would the AWS Lambda end the request but not my test locally?


问:
CAShapeLayer() draws weird line/path
I have a CAShapeLayer() with a gradient on top which is being animated, but somehow it looks like in the image below:

How come it looks like this?

My code:

```<code>override func viewDidLayoutSubviews() {
    displayLine()
}

override func viewDidAppear(_ animated: Bool) {
    animateStroke()
}

func displayLine() {
    let trackLayer = CAShapeLayer()
    let rect = CGRect(x: topView.frame.width * 0.15, y: topView.frame.size.height / 1.5, width: topView.frame.width * 0.7, height: 2)
    let path = UIBezierPath(roundedRect: rect, cornerRadius: 1)

    trackLayer.path = path.cgPath
    trackLayer.strokeColor = UIColor.groupTableViewBackground.cgColor
    trackLayer.lineWidth = 3
    trackLayer.fillColor = UIColor.clear.cgColor

    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.green.cgColor
    shapeLayer.lineWidth = 4
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeEnd = 0

    topView.layer.addSublayer(trackLayer)
    topView.layer.addSublayer(shapeLayer)

    let color = UIColor(red: 11/255, green: 95/255, blue: 244/255, alpha: 1).cgColor
    let sndColor = UIColor(red: 255/255, green: 87/255, blue: 87/255, alpha: 1).cgColor

    gradient.colors = [color, sndColor]
    gradient.locations = [0.0, 1.0]
    gradient.startPoint = CGPoint(x: 0, y: 0)
    gradient.endPoint = CGPoint(x: 1, y: 0)
    gradient.frame = topView.bounds

    gradient.mask = shapeLayer
    topView.layer.addSublayer(gradient)
}

func animateStroke() {
    if !animated {
        animated = true

        let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
        var value: Double?

        let distance = currLeasingCar!.currentKm - currLeasing!.startKm
        value = Double(distance) / Double(finalKm)

        basicAnimation.toValue = value
        basicAnimation.duration = 1.5
        basicAnimation.fillMode = .forwards
        basicAnimation.isRemovedOnCompletion = false
        basicAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

        shapeLayer.add(basicAnimation, forKey: "lineStrokeAnimation")
    }
}
</code>```

答:
The issue is that your path is a rounded rectangle. In the image you shared with us, it’s probably about 2-3% stroked. Change it to stroke 90% of the way, and you’ll see it trying to draw a wide and extremely short rounded rectangle, e.g.:

Instead, just make the path a line, and it will work as intended:

```<code>let path = UIBezierPath()

let bounds = topView.bounds
path.move(to:    CGPoint(x: bounds.minX + bounds.width * 0.15, y: bounds.minY + bounds.height / 1.5))
path.addLine(to: CGPoint(x: bounds.minX + bounds.width * 0.85, y: bounds.minY + bounds.height / 1.5))
</code>```

You might also want to round the caps of your shape layers:

```<code>trackLayer.lineCap = .round  // or whatever you want
shapeLayer.lineCap = .round
</code>```

And, of course, this change lost the 2 point height of your original path, so if you want to make these shape layer’s thicker, just increase their respective lineWidth values.

A couple of unrelated observations:

viewDidLayoutSubviews() and viewDidAppear(_:) should call their super implementations.

viewDidLayoutSubviews() can be called multiple times, so you don’t want to instantiate a new trackLayer every time. Or if you do, make sure to remove the prior one.

When adding subviews/sublayers, it is prudent to use bounds instead of frame. In this case it probably doesn’t matter, but in some cases you can get all sorts of weird problems because frame is in the view’s superview’s coordinate system, whereas bounds is the coordinate system of the view in question.

Personally, if you were to keep this code in the view controller, I’d suggest:

add the shape layers and gradient in viewDidLoad;

update the paths and the bounds of the gradient from viewDidLayoutSubviews;

I’d put these various shape layer and gradient methods in their own private extension.

Even better, all of this animation code doesn’t really belong in the app’s view controller at all, but rather a UIView subclass (or a child view controller).

Thus, perhaps:

```<code>@IBDesignable
public class GradientProgressView: UIView {

    private var shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.green.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineCap = .round
        return shapeLayer
    }()

    private var trackLayer: CAShapeLayer = {
        let trackLayer = CAShapeLayer()
        trackLayer.strokeColor = UIColor.groupTableViewBackground.cgColor
        trackLayer.fillColor = UIColor.clear.cgColor
        trackLayer.lineCap = .round
        return trackLayer
    }()

    private var gradient: CAGradientLayer = {
        let gradient = CAGradientLayer()

        let color = UIColor(red: 11/255, green: 95/255, blue: 244/255, alpha: 1).cgColor
        let sndColor = UIColor(red: 255/255, green: 87/255, blue: 87/255, alpha: 1).cgColor

        gradient.colors = [color, sndColor]
        gradient.locations = [0.0, 1.0]
        gradient.startPoint = CGPoint(x: 0, y: 0)
        gradient.endPoint = CGPoint(x: 1, y: 0)

        return gradient
    }()

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        addSubLayers()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addSubLayers()
    }

    override public func layoutSubviews() {
        super.layoutSubviews()
        updatePaths()
    }

    override public func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setProgress(0.75, animated: false)
    }

    public func setProgress(_ progress: CGFloat, animated: Bool = true) {
        if animated {
            animateStroke(to: progress)
        } else {
            shapeLayer.strokeEnd = progress
        }
    }
}

private extension GradientProgressView {
    func addSubLayers() {
        layer.addSublayer(trackLayer)
        layer.addSublayer(shapeLayer)
        layer.addSublayer(gradient)
    }

    func updatePaths() {
        let lineWidth = bounds.height / 2
        trackLayer.lineWidth = lineWidth * 0.75
        shapeLayer.lineWidth = lineWidth

        let path = UIBezierPath()
        path.move(to:    CGPoint(x: bounds.minX + lineWidth / 2, y: bounds.midY))
        path.addLine(to: CGPoint(x: bounds.maxX - lineWidth / 2, y: bounds.midY))

        trackLayer.path = path.cgPath
        shapeLayer.path = path.cgPath

        gradient.frame = bounds
        gradient.mask = shapeLayer
    }

    func animateStroke(to progress: CGFloat) {
        let key = "lineStrokeAnimation"

        layer.removeAnimation(forKey: key)

        let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")

        basicAnimation.toValue = progress
        basicAnimation.duration = 1.5
        basicAnimation.fillMode = .forwards
        basicAnimation.isRemovedOnCompletion = false
        basicAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

        shapeLayer.add(basicAnimation, forKey: key)
    }
}
</code>```

Then the view controller is merely:

```<code>class ViewController: UIViewController {

    @IBOutlet weak var gradientProgressView: GradientProgressView!

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        updateProgress()
    }

    ...
}

// MARK: - Progress related methods

private extension ViewController {
    func updateProgress() {
        let distance = currLeasingCar!.currentKm - currLeasing!.startKm
        let value = CGFloat(distance) / CGFloat(finalKm)
        gradientProgressView.setProgress(value)
    }
}
</code>```

Title: CAShapeLayer() draws weird line/path

Body:
I have a CAShapeLayer() with a gradient on top which is being animated, but somehow it looks like in the image below:

How come it looks like this?

My code:

override func viewDidLayoutSubviews() {
    displayLine()
}

override func viewDidAppear(_ animated: Bool) {
    animateStroke()
}

func displayLine() {
    let trackLayer = CAShapeLayer()
    let rect = CGRect(x: topView.frame.width * 0.15, y: topView.frame.size.height / 1.5, width: topView.frame.width * 0.7, height: 2)
    let path = UIBezierPath(roundedRect: rect, cornerRadius: 1)

    trackLayer.path = path.cgPath
    trackLayer.strokeColor = UIColor.groupTableViewBackground.cgColor
    trackLayer.lineWidth = 3
    trackLayer.fillColor = UIColor.clear.cgColor

    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.green.cgColor
    shapeLayer.lineWidth = 4
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeEnd = 0

    topView.layer.addSublayer(trackLayer)
    topView.layer.addSublayer(shapeLayer)

    let color = UIColor(red: 11/255, green: 95/255, blue: 244/255, alpha: 1).cgColor
    let sndColor = UIColor(red: 255/255, green: 87/255, blue: 87/255, alpha: 1).cgColor

    gradient.colors = [color, sndColor]
    gradient.locations = [0.0, 1.0]
    gradient.startPoint = CGPoint(x: 0, y: 0)
    gradient.endPoint = CGPoint(x: 1, y: 0)
    gradient.frame = topView.bounds

    gradient.mask = shapeLayer
    topView.layer.addSublayer(gradient)
}

func animateStroke() {
    if !animated {
        animated = true

        let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
        var value: Double?

        let distance = currLeasingCar!.currentKm - currLeasing!.startKm
        value = Double(distance) / Double(finalKm)

        basicAnimation.toValue = value
        basicAnimation.duration = 1.5
        basicAnimation.fillMode = .forwards
        basicAnimation.isRemovedOnCompletion = false
        basicAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

        shapeLayer.add(basicAnimation, forKey: "lineStrokeAnimation")
    }
}

Body:
The issue is that your path is a rounded rectangle. In the image you shared with us, it’s probably about 2-3% stroked. Change it to stroke 90% of the way, and you’ll see it trying to draw a wide and extremely short rounded rectangle, e.g.:

Instead, just make the path a line, and it will work as intended:

let path = UIBezierPath()

let bounds = topView.bounds
path.move(to:    CGPoint(x: bounds.minX + bounds.width * 0.15, y: bounds.minY + bounds.height / 1.5))
path.addLine(to: CGPoint(x: bounds.minX + bounds.width * 0.85, y: bounds.minY + bounds.height / 1.5))

You might also want to round the caps of your shape layers:

trackLayer.lineCap = .round  // or whatever you want
shapeLayer.lineCap = .round

And, of course, this change lost the 2 point height of your original path, so if you want to make these shape layer’s thicker, just increase their respective lineWidth values.

A couple of unrelated observations:

viewDidLayoutSubviews() and viewDidAppear(_:) should call their super implementations.

viewDidLayoutSubviews() can be called multiple times, so you don’t want to instantiate a new trackLayer every time. Or if you do, make sure to remove the prior one.

When adding subviews/sublayers, it is prudent to use bounds instead of frame. In this case it probably doesn’t matter, but in some cases you can get all sorts of weird problems because frame is in the view’s superview’s coordinate system, whereas bounds is the coordinate system of the view in question.

Personally, if you were to keep this code in the view controller, I’d suggest:

add the shape layers and gradient in viewDidLoad;

update the paths and the bounds of the gradient from viewDidLayoutSubviews;

I’d put these various shape layer and gradient methods in their own private extension.

Even better, all of this animation code doesn’t really belong in the app’s view controller at all, but rather a UIView subclass (or a child view controller).

Thus, perhaps:

@IBDesignable
public class GradientProgressView: UIView {

    private var shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.green.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineCap = .round
        return shapeLayer
    }()

    private var trackLayer: CAShapeLayer = {
        let trackLayer = CAShapeLayer()
        trackLayer.strokeColor = UIColor.groupTableViewBackground.cgColor
        trackLayer.fillColor = UIColor.clear.cgColor
        trackLayer.lineCap = .round
        return trackLayer
    }()

    private var gradient: CAGradientLayer = {
        let gradient = CAGradientLayer()

        let color = UIColor(red: 11/255, green: 95/255, blue: 244/255, alpha: 1).cgColor
        let sndColor = UIColor(red: 255/255, green: 87/255, blue: 87/255, alpha: 1).cgColor

        gradient.colors = [color, sndColor]
        gradient.locations = [0.0, 1.0]
        gradient.startPoint = CGPoint(x: 0, y: 0)
        gradient.endPoint = CGPoint(x: 1, y: 0)

        return gradient
    }()

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        addSubLayers()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addSubLayers()
    }

    override public func layoutSubviews() {
        super.layoutSubviews()
        updatePaths()
    }

    override public func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setProgress(0.75, animated: false)
    }

    public func setProgress(_ progress: CGFloat, animated: Bool = true) {
        if animated {
            animateStroke(to: progress)
        } else {
            shapeLayer.strokeEnd = progress
        }
    }
}

private extension GradientProgressView {
    func addSubLayers() {
        layer.addSublayer(trackLayer)
        layer.addSublayer(shapeLayer)
        layer.addSublayer(gradient)
    }

    func updatePaths() {
        let lineWidth = bounds.height / 2
        trackLayer.lineWidth = lineWidth * 0.75
        shapeLayer.lineWidth = lineWidth

        let path = UIBezierPath()
        path.move(to:    CGPoint(x: bounds.minX + lineWidth / 2, y: bounds.midY))
        path.addLine(to: CGPoint(x: bounds.maxX - lineWidth / 2, y: bounds.midY))

        trackLayer.path = path.cgPath
        shapeLayer.path = path.cgPath

        gradient.frame = bounds
        gradient.mask = shapeLayer
    }

    func animateStroke(to progress: CGFloat) {
        let key = "lineStrokeAnimation"

        layer.removeAnimation(forKey: key)

        let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")

        basicAnimation.toValue = progress
        basicAnimation.duration = 1.5
        basicAnimation.fillMode = .forwards
        basicAnimation.isRemovedOnCompletion = false
        basicAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

        shapeLayer.add(basicAnimation, forKey: key)
    }
}

Then the view controller is merely:

class ViewController: UIViewController {

    @IBOutlet weak var gradientProgressView: GradientProgressView!

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        updateProgress()
    }

    ...
}

// MARK: - Progress related methods

private extension ViewController {
    func updateProgress() {
        let distance = currLeasingCar!.currentKm - currLeasing!.startKm
        let value = CGFloat(distance) / CGFloat(finalKm)
        gradientProgressView.setProgress(value)
    }
}


问:
How to access to a cell into a dataframe
Issue trying to get a value from a DataFrame

I'm using pyspark in Databricks, I'm trying to get the amount of rows as a value to do some calculation

What I did:

```<code>f=sqlContext.sql('SELECT COUNT(*) AS COUNTF FROM SOOMLA')
#It´s a dataframe
</code>```

Now I want to get this number into the DataFrame as a value to make calculation, I tried already:

```<code>f['COUNTF'].iloc[0]
</code>```

but I got:

```<code>Out[158]: Column<b'COUNTF[iloc][0]'>
</code>```

How can I get this 439016392 as a value?

答:
I guess you're mixing Pandas df with Spark df when using iloc.

```<code>type(f['COUNTF'])

pyspark.sql.column.Column
</code>```

You can do it, as Ben T suggested by:

```<code>f=sqlContext.sql('SELECT * FROM SOOMLA').count()
print(f)
</code>```

or convert the df to pandas first and then:

```<code>f=sqlContext.sql('SELECT COUNT(*) AS COUNTF FROM SOOMLA').toPandas()['COUNTF'].iloc[0]
print(f)
</code>```

Body:
Issue trying to get a value from a DataFrame

I'm using pyspark in Databricks, I'm trying to get the amount of rows as a value to do some calculation

What I did:

f=sqlContext.sql('SELECT COUNT(*) AS COUNTF FROM SOOMLA')
#It´s a dataframe

Now I want to get this number into the DataFrame as a value to make calculation, I tried already:

f['COUNTF'].iloc[0]

but I got:

Out[158]: Column

How can I get this 439016392 as a value?

Body:
I guess you're mixing Pandas df with Spark df when using iloc.

type(f['COUNTF'])

pyspark.sql.column.Column

You can do it, as Ben T suggested by:

f=sqlContext.sql('SELECT * FROM SOOMLA').count()
print(f)

or convert the df to pandas first and then:

f=sqlContext.sql('SELECT COUNT(*) AS COUNTF FROM SOOMLA').toPandas()['COUNTF'].iloc[0]
print(f)


问:
Batch command to have program open a file
I have a portable java launcher program that I use to run .jar files. Once the program is executed a window titled "Open" is launched where you can navigate to and select the .jar file needed.

I am trying to create a batch file to automate this process for one specific file that I need to open on a regular basis. That file is "Build.jar". It is located at "C:\Users\John\Store\Build.jar".

So far I have the following that calls the java launcher:

```<code>@echo off
cd "C:\Users\John"
start Java Portable Launcher.exe
</code>```

What is the next line to select the .jar file from the prompt that opens?

Thanks in advance.

答:
If this is the Java Portable Launcher from PortableApps.com, then you just need to append the full file path to the end:

```<code>@echo off
cd "C:\Users\John"
start "" "Java Portable Launcher.exe" "C:\Users\John\Store\Build.jar"
</code>```

I added " quotes to avoid issues with spaces. The first "" is to avoid issues with start's "title" option.

Source

Body:
I have a portable java launcher program that I use to run .jar files. Once the program is executed a window titled "Open" is launched where you can navigate to and select the .jar file needed.

I am trying to create a batch file to automate this process for one specific file that I need to open on a regular basis. That file is "Build.jar". It is located at "C:\Users\John\Store\Build.jar".

So far I have the following that calls the java launcher:

@echo off
cd "C:\Users\John"
start Java Portable Launcher.exe

What is the next line to select the .jar file from the prompt that opens?

Thanks in advance.

Body:
If this is the Java Portable Launcher from PortableApps.com, then you just need to append the full file path to the end:

@echo off
cd "C:\Users\John"
start "" "Java Portable Launcher.exe" "C:\Users\John\Store\Build.jar"

I added " quotes to avoid issues with spaces. The first "" is to avoid issues with start's "title" option.

Source


问:
Get a single compare function to order both ASC and DESC using Array.sort()?
I need to order an array of objects by the property price.

Right now I have the following, which works as intended:

```<code>function orderByPriceASC(a,b) {
    return(
      a.price < b.price ? -1
      : a.price > b.price ? 1
        : 0
    );
  }

  function orderByPriceDESC(a,b) {
    return(
      a.price < b.price ? 1
      : a.price > b.price ? -1
        : 0
    );
  }

  function sortByPrice(order) {
    setProductList((prevState) => {
      const aux = Array.from(prevState);
      order === 'asc' ? aux.sort(orderByPriceASC) : aux.sort(orderByPriceDESC);
      return aux;
    });
  }
</code>```

But can is there a way that I can structure this so I can get a single compare function that works for both ASC and DESC order?

Something like:

```<code>function orderByPrice(a,b,order) {
    return(
      a.price < b.price ?
        order === 'asc' ? -1 : 1
      : a.price > b.price ? 1
        order === 'asc' ? 1 : -1
        : 0
    );
  }
</code>```

The problem is that I would have to send that extra parameter down to the Array.sort method which I don't think it's possible. Maybe with some wrapper function.

How can this be implemented?

答:
You can use a multiplier and set it to 1 or -1 based on the order variable. Then multiply it to the existing expression inside compareFunction (Here I'm assuming price is of type number)

let arr = [{ price: 2 },{ price: 1 },{ price: 3 }]

function sort(array, order) {
  const multiplier = order === "asc" ? 1 : -1;
  return array.sort((a, b) => multiplier * (a.price - b.price))
}

console.log(sort(arr, "asc"))
console.log(sort(arr, "desc"))```

Body:
I need to order an array of objects by the property price.

Right now I have the following, which works as intended:

function orderByPriceASC(a,b) {
    return(
      a.price  b.price ? 1
        : 0
    );
  }

  function orderByPriceDESC(a,b) {
    return(
      a.price  b.price ? -1
        : 0
    );
  }

  function sortByPrice(order) {
    setProductList((prevState) => {
      const aux = Array.from(prevState);
      order === 'asc' ? aux.sort(orderByPriceASC) : aux.sort(orderByPriceDESC);
      return aux;
    });
  }

But can is there a way that I can structure this so I can get a single compare function that works for both ASC and DESC order?

Something like:

function orderByPrice(a,b,order) {
    return(
      a.price  b.price ? 1
        order === 'asc' ? 1 : -1
        : 0
    );
  }

The problem is that I would have to send that extra parameter down to the Array.sort method which I don't think it's possible. Maybe with some wrapper function.

How can this be implemented?


问:
Using wordpress in a subdirectory error
I have a non-wordpress site where i installed wordpress in a subdirectory

www.example.com/wordpress/

I have created an htaccess file in the wordpress folder (whre i have all its content)

```<code>    # BEGIN WordPress
   <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /wordpress/
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /wordpress/index.php [L]
    </IfModule>
    # END WordPress
</code>```

And made this change in the index.php (inside wordpress folder)

```<code><?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . './wordpress/wp-blog-header.php' );
</code>```

The admin works ok but when try to visit the site it gives me an error 500.
what am i missing?

Aclaration: I want to use wordpress in this url www.example.com/wordpress/
since i have other content in the root.

答:
Remove /wordpress from the last rule (RewriteBase stays as before).</p>

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

Title: Using wordpress in a subdirectory error

Body:
I have a non-wordpress site where i installed wordpress in a subdirectory

www.example.com/wordpress/

I have created an htaccess file in the wordpress folder (whre i have all its content)

    # BEGIN WordPress
   <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /wordpress/
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /wordpress/index.php [L]
    </IfModule>
    # END WordPress

And made this change in the index.php (inside wordpress folder)

<?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . './wordpress/wp-blog-header.php' );

The admin works ok but when try to visit the site it gives me an error 500.
what am i missing?

Aclaration: I want to use wordpress in this url www.example.com/wordpress/
since i have other content in the root.

Body:
Remove /wordpress from the last rule (RewriteBase stays as before).

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


问:
Using Powershell to replace captured value
I want to replace the value in an XML using PowerShell. I have below string (a part of XML) want to replace 100 with different value

```<code><stringProp 79357name="ThreadGroup.79357num_threads">100</stringProp>
</code>```

I have tried below code which identify the required value but while replacing it replace all the numeric value

```<code>$DN = '<stringProp 79357name="ThreadGroup.79357num_threads">100</stringProp>'
$test =10000
[regex]$rx='^ThreadGroup.79357num_threads">(.+?)</stringProp>$'
$rx.Match($DN)
$DN = $rx.Replace($DN,'$1') -replace '\d+',$test
Write-Host $DN
</code>```

After running above code I am getting below output

```<code><stringProp 10000name="ThreadGroup.10000num_threads">10000</stringProp>
</code>```

and am expecting

```<code><stringProp name="ThreadGroup.10000num_threads">10000</stringProp>
</code>```

答:
Capturing groups are used in regex to extract part of a pattern match when we need to match those in specific contexts. Replacing captured texts is not directly supported, though with some coding it can be worked around.

Instead, use capturing groups to do what they are meant to do: capture what you need to keep and just match what you need to replace.

Use

```<code>$DN -replace '(ThreadGroup\.79357num_threads">).*?(</stringProp>)',"`${1}$test`$2"
</code>```

The ThreadGroup.79357num_threads"> is captured with (ThreadGroup\.79357num_threads">) into Group 1 and </stringProp> is captured with (</stringProp>) into Group 2.

The "`${1}$test`$2" replacement is the contents of Group 1 ($1), then the value of the $test variable and then the value of Group 2. Note the backticks before $ are necessary for Powershell to treat them as literal $ chars, not the string extrapolating "marker".

You need ${1} and not $1 because the $test variable starts with a digit and when there is a digit straight after a backreference (like $1) the ID should be wrapped with curly braces to avoid ambiguity with the Group ID.

Body:
I want to replace the value in an XML using PowerShell. I have below string (a part of XML) want to replace 100 with different value

<stringProp 79357name="ThreadGroup.79357num_threads">100</stringProp>

I have tried below code which identify the required value but while replacing it replace all the numeric value

$DN = '<stringProp 79357name="ThreadGroup.79357num_threads">100</stringProp>'
$test =10000
[regex]$rx='^ThreadGroup.79357num_threads">(.+?)</stringProp>$'
$rx.Match($DN)
$DN = $rx.Replace($DN,'$1') -replace '\d+',$test
Write-Host $DN

After running above code I am getting below output

<stringProp 10000name="ThreadGroup.10000num_threads">10000</stringProp>

and am expecting

<stringProp name="ThreadGroup.10000num_threads">10000</stringProp>

Body:
Capturing groups are used in regex to extract part of a pattern match when we need to match those in specific contexts. Replacing captured texts is not directly supported, though with some coding it can be worked around.

Instead, use capturing groups to do what they are meant to do: capture what you need to keep and just match what you need to replace.

Use

$DN -replace '(ThreadGroup\.79357num_threads">).*?(</stringProp>)',"`${1}$test`$2"

The ThreadGroup.79357num_threads"> is captured with (ThreadGroup\.79357num_threads">) into Group 1 and </stringProp> is captured with (</stringProp>) into Group 2.

The "`${1}$test`$2" replacement is the contents of Group 1 ($1), then the value of the $test variable and then the value of Group 2. Note the backticks before $ are necessary for Powershell to treat them as literal $ chars, not the string extrapolating "marker".

You need ${1} and not $1 because the $test variable starts with a digit and when there is a digit straight after a backreference (like $1) the ID should be wrapped with curly braces to avoid ambiguity with the Group ID.


问:
Ejabberd api endpoint private_set won't save the data
I'm trying to manipulate the private storage on ejabberd server, I send the POST with the json to the endpoint private_set. The answer of the call private_set it's 200 and the body 0, means all ok and then I call the other endpoint private_get to query the private storage, and when I do this last call the storage is not updated. </p>

```<code>{
    "user": "example",
    "host": "localhost",
    "element": "<query xmlns='jabber:iq:private'><storage xmlns='storage:bookmarks'><conference autojoin='false' jid='test@conference.localhost' name='test'><nick>example</nick></storage></query>"
}
</code>```

答:
I don't know with older versions, but at least with ejabberd 19.02, the Query element must not be included in the argument. So, there's a mistake in the documentation of the command example argument. Also, you forgot to close the Conference element.

Try with this:

```<code>{
    "user": "example",
    "host": "localhost",
    "element": "<storage xmlns='storage:bookmarks'><conference autojoin='false' jid='test@conference.localhost' name='test'><nick>example</nick></conference></storage>"
}
</code>```

Body:
I'm trying to manipulate the private storage on ejabberd server, I send the POST with the json to the endpoint private_set. The answer of the call private_set it's 200 and the body 0, means all ok and then I call the other endpoint private_get to query the private storage, and when I do this last call the storage is not updated.

{
    "user": "example",
    "host": "localhost",
    "element": "<query xmlns='jabber:iq:private'><storage xmlns='storage:bookmarks'><conference autojoin='false' jid='test@conference.localhost' name='test'><nick>example</nick></storage></query>"
}

Body:
I don't know with older versions, but at least with ejabberd 19.02, the Query element must not be included in the argument. So, there's a mistake in the documentation of the command example argument. Also, you forgot to close the Conference element.

Try with this:

{
    "user": "example",
    "host": "localhost",
    "element": "<storage xmlns='storage:bookmarks'><conference autojoin='false' jid='test@conference.localhost' name='test'><nick>example</nick></conference></storage>"
}


答:
POST request data are not encoded in url its  within the message body of the HTTP request.

```<code>Route::post('reports', 'ReportController@index');
</code>```

and in your controller

```<code>public function index(Request $request)
{
   return $request->report_option;

}
</code>```

Title: How to pass form values to route

Body:
I'm having trouble passing a value from a form to a route.

{!! Form::open(['method'=>'POST', 'action'=> 'ReportController@index']) !!}

     <input type="radio" name="report_option" class="report_option" value="call_details">Call Details

Route::post('reports/{report}', 'ReportController@index');

Body:
POST request data are not encoded in url its  within the message body of the HTTP request.

Route::post('reports', 'ReportController@index');

and in your controller

public function index(Request $request)
{
   return $request->report_option;

}


问:
Remove fields to sales report Odoo v12
I want my quote reports, orders and invoices in Odoo v12 to be rendered without the price or quantity field for each item.
I'm learning Odoo, and it's my first time doing an inheritance with reports. However I do not know where the file that I inherit and modify is located, and what part of the code.

I appreciate your help.

答:
Ok, so I have a couple ways that you can hide this information.

The first way will leave the column headers in the tree views and in actuality leaves this information in the view but makes it invisible:

```<code><xpath expr="//field[@name='field_name']" position="attributes">
    <attribute name="invisible">1</attribute>
</xpath>
</code>```

The second way is to completely remove the field from the view:

```<code><xpath expr="//field[@name='field_name'] position="replace"/>
</code>```

Title: Remove fields to sales report Odoo v12

Body:
Ok, so I have a couple ways that you can hide this information.

The first way will leave the column headers in the tree views and in actuality leaves this information in the view but makes it invisible:

<xpath expr="//field[@name='field_name']" position="attributes">
    <attribute name="invisible">1</attribute>
</xpath>

The second way is to completely remove the field from the view:

<xpath expr="//field[@name='field_name'] position="replace"/>


问:
PostgreSQL function with table and column names as parameters,and would return min and max of that column (any type) as an array?
I am trying to make a function in PostgreSQL, which would take a name of a table and a name of one column in that table (in varchars); and return an array which would have minimum and maximum values of that column.

In advance I do not (want to) know the type of the column, ie. type of the elements in the return array.

I've tried to create a function with polymorphic anyarray as a return type, but keep hitting syntax errors. Have tried both in SQL and in PLPQSQL.

```<code>CREATE OR REPLACE FUNCTION minmax(tablename character varying, columnname character varying, OUT minmaxa anyarray) AS
$function$
BEGIN
   EXECUTE FORMAT('SELECT array_agg(foo) AS %s FROM (
            (SELECT min(%s) AS foo FROM %s)
            UNION
            (SELECT max(%s) AS foo FROM %s)
    ) AS foobar'
       , columnname
       , columnname, tablename
       , columnname, tablename)
   INTO minmaxa;
END
$function$
LANGUAGE plpgsql;
</code>```

The string from the FORMAT would be:

```<code>SELECT array_agg(foo) AS columnname FROM (
  (SELECT min(columnname) AS foo FROM tablename)
  UNION
  (SELECT max(columnname) AS foo FROM tablename)
 ) AS foobar
</code>```

Then test case:

```<code>create table example (columnA int, columnB varchar);
insert into example (columnA, columnB) values (1, 'ac'), (2, 'ab'), (3, 'aa');

select minmax('example', 'columnA');
select minmax('example', 'columnB');

select array_agg(columnA) from (
   (select min(columnA) AS columnA from example)
   UNION
   (select max(columnA) AS columnA from example)
  ) AS foobar;
</code>```

Should return:

{1,3}

  {'aa','ac'}

  {1,3}

But currently function definition gives:
"SQL Error [42P13]: ERROR: cannot determine result data type
  Detail: A function returning a polymorphic type must have at least one polymorphic argument."

I can make it work, by defining a dummy function parameter 'foo':

```<code>CREATE OR REPLACE FUNCTION minmax(tablename character varying, columnname character varying, foo anyelement, OUT minmaxa anyarray)
</code>```

(Note. A function parameter foo is not used in function body anywhere.)

And now giving a dummy typed value of the correct type of returning array when calling the function:

```<code>select minmax('example', 'columnB', ''::varchar);
select minmax('example', 'columnA', 0::int);
</code>```

Then it works, but what should be changed to I would not need that dummy function parameter?

答:
You can't do this with the standard polymorphic types, but you could do this with jsonb.

```<code>CREATE OR REPLACE FUNCTION minmax(tablename regclass, columnname character varying)
RETURNS JSONB AS
$function$
DECLARE
  minmaxa jsonb;
BEGIN
   EXECUTE FORMAT('SELECT jsonb_agg(foo) AS %I FROM (
            (SELECT min(%I) AS foo FROM %I)
            UNION
            (SELECT max(%I) AS foo FROM %I)
    ) AS foobar'
       , columnname
       , columnname, tablename
       , columnname, tablename)
   INTO minmaxa;
   RETURN minmaxa;
END
$function$
STABLE
LANGUAGE plpgsql;

-- Test with integers
CREATE TABLE test (a int);
insert into test (a) values (1), (2), (3);
select minmax('test'::regclass, 'a');
 minmax
--------
 [1, 2]
(1 row)

-- Test with timestamps
create table test2 (a timestamp);
insert into test2 values ('2012-01-01T00:00:00'), ('2015-01-01T00:00:00');
select minmax('test2'::regclass, 'a');
                     minmax
------------------------------------------------
 ["2012-01-01T00:00:00", "2015-01-01T00:00:00"]
(1 row)
</code>```

I used regclass instead of string for the tablename to help find the correct table according to your search path.

Body:
I am trying to make a function in PostgreSQL, which would take a name of a table and a name of one column in that table (in varchars); and return an array which would have minimum and maximum values of that column.

In advance I do not (want to) know the type of the column, ie. type of the elements in the return array.

I've tried to create a function with polymorphic anyarray as a return type, but keep hitting syntax errors. Have tried both in SQL and in PLPQSQL.

CREATE OR REPLACE FUNCTION minmax(tablename character varying, columnname character varying, OUT minmaxa anyarray) AS
$function$
BEGIN
   EXECUTE FORMAT('SELECT array_agg(foo) AS %s FROM (
            (SELECT min(%s) AS foo FROM %s)
            UNION
            (SELECT max(%s) AS foo FROM %s)
    ) AS foobar'
       , columnname
       , columnname, tablename
       , columnname, tablename)
   INTO minmaxa;
END
$function$
LANGUAGE plpgsql;

The string from the FORMAT would be:

SELECT array_agg(foo) AS columnname FROM (
  (SELECT min(columnname) AS foo FROM tablename)
  UNION
  (SELECT max(columnname) AS foo FROM tablename)
 ) AS foobar

Then test case:

create table example (columnA int, columnB varchar);
insert into example (columnA, columnB) values (1, 'ac'), (2, 'ab'), (3, 'aa');

select minmax('example', 'columnA');
select minmax('example', 'columnB');

select array_agg(columnA) from (
   (select min(columnA) AS columnA from example)
   UNION
   (select max(columnA) AS columnA from example)
  ) AS foobar;

Should return:

{1,3}

  {'aa','ac'}

  {1,3}

But currently function definition gives:
"SQL Error [42P13]: ERROR: cannot determine result data type
  Detail: A function returning a polymorphic type must have at least one polymorphic argument."

I can make it work, by defining a dummy function parameter 'foo':

CREATE OR REPLACE FUNCTION minmax(tablename character varying, columnname character varying, foo anyelement, OUT minmaxa anyarray)

(Note. A function parameter foo is not used in function body anywhere.)

And now giving a dummy typed value of the correct type of returning array when calling the function:

select minmax('example', 'columnB', ''::varchar);
select minmax('example', 'columnA', 0::int);

Then it works, but what should be changed to I would not need that dummy function parameter?

Body:
You can't do this with the standard polymorphic types, but you could do this with jsonb.

CREATE OR REPLACE FUNCTION minmax(tablename regclass, columnname character varying)
RETURNS JSONB AS
$function$
DECLARE
  minmaxa jsonb;
BEGIN
   EXECUTE FORMAT('SELECT jsonb_agg(foo) AS %I FROM (
            (SELECT min(%I) AS foo FROM %I)
            UNION
            (SELECT max(%I) AS foo FROM %I)
    ) AS foobar'
       , columnname
       , columnname, tablename
       , columnname, tablename)
   INTO minmaxa;
   RETURN minmaxa;
END
$function$
STABLE
LANGUAGE plpgsql;

-- Test with integers
CREATE TABLE test (a int);
insert into test (a) values (1), (2), (3);
select minmax('test'::regclass, 'a');
 minmax
--------
 [1, 2]
(1 row)

-- Test with timestamps
create table test2 (a timestamp);
insert into test2 values ('2012-01-01T00:00:00'), ('2015-01-01T00:00:00');
select minmax('test2'::regclass, 'a');
                     minmax
------------------------------------------------
 ["2012-01-01T00:00:00", "2015-01-01T00:00:00"]
(1 row)

I used regclass instead of string for the tablename to help find the correct table according to your search path.


问:
K product array
I am working on an algorithms problem. You have an array numbers, size of array t , number number_of_elements and number multiplication_value. You have to find any set of number_of_elements indexes of the elements of the array , which product will be equal to multiplication_value. It is guaranteed, that such set of indexes exists

That problem looks like 2 sum, but I can't extrapolate it to my case.
I have tried naive algorithm for O(n), but it fails, when you have bad first number in an array. I think there is a way to use recursion in here. I guess it is well-known problem, but I couldn't find the solution

Example in:

```<code>t = 7
number_of_elements = 2
multiplication_value = 27
numbers = [9,1,1,27,3,27,3]
</code>```

Example out:

```<code>1 3
</code>```

My code ideas:

    def return_index_values(numbers,multiplication_value,number_of_elements):
    cur_number = int(multiplication_value)
    list_of_indexes = []
    values = []
    for i in range(len(numbers)):
        if ((cur_number == 1) and (len(values) == number_of_elements)):
            print(values)
            #finishing if everything worked
            break
        else:
            if (cur_number % int(numbers[i]) == 0):
                if(len(values) < number_of_elements):
            #pushing values if possible
                    values.append(int(numbers[i]))
                    list_of_indexes.append(i)
                    cur_number = int(cur_number / int(numbers[i]))
                    print(cur_number)
                else:
                    pass
            if(len(values) == number_of_elements):
                if mult_check(values,int(multiplication_value)):
               #mult_check checks if the array's element multiplication gives a value
                    break
                else:
               #started dealing with bad cases, but it doesn't work properly
                    values.sort()
                    val_popped = values.pop()
                    cur_number = cur_number * val_popped
```

<p>Bad case for my code</p>

``` numbers = [9,3,1,27,3,27,3]
```

答: You can use itertools.combinations() (https://www.geeksforgeeks.org/itertools-combinations-module-python-print-possible-combinations/) to select number_of_elements entries from your list in all possible ways, then check each whether they multiply to the required number.</p>

Title: K product array

Body:
I am working on an algorithms problem. You have an array numbers, size of array t , number number_of_elements and number multiplication_value. You have to find any set of number_of_elements indexes of the elements of the array , which product will be equal to multiplication_value. It is guaranteed, that such set of indexes exists

That problem looks like 2 sum, but I can't extrapolate it to my case.
I have tried naive algorithm for O(n), but it fails, when you have bad first number in an array. I think there is a way to use recursion in here. I guess it is well-known problem, but I couldn't find the solution

Example in:

t = 7
number_of_elements = 2
multiplication_value = 27
numbers = [9,1,1,27,3,27,3]

Example out:

1 3

My code ideas:

    def return_index_values(numbers,multiplication_value,number_of_elements):
    cur_number = int(multiplication_value)
    list_of_indexes = []
    values = []
    for i in range(len(numbers)):
        if ((cur_number == 1) and (len(values) == number_of_elements)):
            print(values)
            #finishing if everything worked
            break
        else:
            if (cur_number % int(numbers[i]) == 0):
                if(len(values) < number_of_elements):
            #pushing values if possible
                    values.append(int(numbers[i]))
                    list_of_indexes.append(i)
                    cur_number = int(cur_number / int(numbers[i]))
                    print(cur_number)
                else:
                    pass
            if(len(values) == number_of_elements):
                if mult_check(values,int(multiplication_value)):
               #mult_check checks if the array's element multiplication gives a value
                    break
                else:
               #started dealing with bad cases, but it doesn't work properly
                    values.sort()
                    val_popped = values.pop()
                    cur_number = cur_number * val_popped

Bad case for my code

 numbers = [9,3,1,27,3,27,3]


问:
SWIFT ACK Message Parsing
I am Generating a SWIFT Messages MT 110 and MT 103 through my java based application. For reconciliation and sharing with end customer, we need to map the Ack Nak message received from SWIFT terminal back to MT 110 and MT 103 transactions. To do this I need to parse each ACK file and find out

20: Sender's Reference
ABC1380Q02418

451:0 (ACK)

451:1 (NAK) then 405 field.

I have tried doing this using Prowide Core (WIFE) Open source SWIFT Java library but I am not able to parse the ACK. Through library I am able to parse  MT 110 and MT 103 messages but not ACK or NAK messages. Need you help in understanding how to parse the SWIFT ACK NAK file through Prowide Core (WIFE) Open source SWIFT Java library.

Sample ACK message pasted below:

23/12/15-11:50:14               BulBoardCTFACK-0192-000001   1

---------------------  Instance Type and Transmission --------------

Notification (Transmission) of Original sent to SWIFT (ACK)

Network Delivery Status   : Network Ack

Priority/Delivery         : Normal

Message Input Reference   : 1150 151223ABCINBBADEL2567311531

--------------------------- Message Header -------------------------

Swift Input                   : FIN 103 Single Customer Credt Transfer

Sender   : ABCDINBBDEL
TTTT BANK LIMITED
(XXXXX BRANCH)
YYYYYYYYY YY

Receiver : ANZBAU3MXXX
AUSTRALIA AND NEW ZEALAND BANKING GROUP LIMITED
MELBOURNE AU

--------------------------- Message Text ---------------------------

20: Sender's Reference
ABC1380Q02418

23B: Bank Operation Code
CRED

32A: Val Dte/Curr/Interbnk Settld Amt
Date           : 23 December 2015
Currency       : AUD (AUSTRALIAN DOLLAR)
Amount         :                  #8000,0#

33B: Currency/Instructed Amount
Currency       : AUD (AUSTRALIAN DOLLAR)
Amount         :                  #8000,0#

50K: Ordering Customer-Name & Address
/M4132378
ABC DEF
GHI 76 AX , MODEL TOWN EXT ,
XXXXXXXX

53A: Sender's Correspondent - FI BIC
/1111111 00001
ABCDEFBBDEL
ABC

57D: Account With Inst -Name & Addr
//AU063144
COMMON WEALTH BANK
AUSTRALIA SWIFT CODE CTBAAU2S

59: Beneficiary Customer-Name & Addr
/555555
ABCDEF
YYYYYYYYY

70: Remittance Information
MAINTENACE

71A: Details of Charges
BEN

71F: Sender's Charges
Currency       : AUD (AUSTRALIAN DOLLAR)
Amount         :                     #0,0#

--------------------------- Message Trailer ------------------------

{CHK:41B1AA23FEDF}

PKI Signature: MAC-Equivalent

---------------------------- Interventions -------------------------

Category      : Network Report

Creation Time : 23/12/15 11:50:03

Application   : SWIFT Interface

Operator      : SYSTEM

Text

{1:F21ABCDEFBBADEL2567311531}{4:{177:1512231150}{451:0}}

答:
ACK/NAK notifications are identified with service id 21.

You can use ServiceMessage21 class from Prowide Core to parse Acks and Nacks

https://www.javadoc.io/doc/com.prowidesoftware/pw-swift-core/SRU2018-7.10.4

Title: SWIFT ACK Message Parsing