问:
Smtp.office365.com for OpenEdx
I am facing a configuration problem with Office 365, the user did not receive email.

I've put my configuration in the file {lms|cms}.{env|auth}.json.

But the user still doesn't receive the email.

{lms|cms}.env.json :

```<code>"EMAIL_HOST": "smtp.office365.com",
"EMAIL_PORT": 587,
"EMAIL_USE_TLS": true,
</code>```

答:
In order to get this working you need to modify a few settings in four different files, then restart Apache:

Navigate to the edx/conf/ folder, the full path of which will depend on how you've installed it

Edit lms.env.json

Modify the following settings:

DEFAULT_FROM_EMAIL: "Open-edX@Yourcompany.com" - This is the email address you want emails to show as having been sent by. NOTE: This may not be the same as the mailbox's login credentials

EMAIL_HOST: "smtp.office365.com"

EMAIL_PORT: 587

EMAIL_USE_TLS: true

Edit cms.env.json

Modify the following settings:

DEFAULT_FROM_EMAIL: "Open-edX@Yourcompany.com" - This is the email address you want emails to show as having been sent by. NOTE: This may not be the same as the mailbox's login credentials

EMAIL_HOST: "smtp.office365.com"

EMAIL_PORT: 587

EMAIL_USE_TLS: true

Edit lms.auth.json

Modify the following settings:

EMAIL_HOST: "smtp.office365.com"

EMAIL_PORT: 587

EMAIL_USE_TLS: true

EMAIL_HOST_USER: "login@yourcompany.onmicrosoft.com" - This is the login you use to access webmail for the mailbox, and may be different or the same as the previously-used DEFAULT_FROM_EMAIL setting

EMAIL_HOST_PASSWORD: The password you use to access webmail for the mailbox

Edit cms.auth.json

Modify the following settings:

EMAIL_HOST_USER: "login@yourcompany.onmicrosoft.com" - This is the login you use to access webmail for the mailbox, and may be different or the same as the previously-used DEFAULT_FROM_EMAIL setting

EMAIL_HOST_PASSWORD: The password you use to access webmail for the mailbox

Restart Apache (or the server, if you're unsure how to)

Title: Smtp.office365.com for OpenEdx

Body:
I am facing a configuration problem with Office 365, the user did not receive email.

I've put my configuration in the file {lms|cms}.{env|auth}.json.

But the user still doesn't receive the email.

{lms|cms}.env.json :

"EMAIL_HOST": "smtp.office365.com",
"EMAIL_PORT": 587,
"EMAIL_USE_TLS": true,


来源: stackexchange

问:
Bash addition by the first column, if data in second column is the same
I have a list with delimiters |

```<code>40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2
</code>```

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

```<code>40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11
</code>```

How you can see, we have counted the numbers from first column.

答:
awk to the rescue!

```<code>$ awk 'BEGIN {FS=OFS="|"}
             {a[$2 FS $3]+=$1}
       END   {for(k in a) print a[k],k}' file | sort -n

40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11
</code>```

if user* is not part of the key and you want to capture the first value

```<code>$ awk 'BEGIN {FS=OFS="|"}
             {c[$2]+=$1;
              if(!($2 in u)) u[$2]=$3}     # capture first user
       END   {for(k in c) print c[k],k,u[k]}' file | sort -n
</code>```

which ends up almost the same with @markp's answer.

ContentLicense: CC BY-SA 3.0

Body:
I have a list with delimiters |

40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11

How you can see, we have counted the numbers from first column.

Body:
awk to the rescue!

$ awk 'BEGIN {FS=OFS="|"}
             {a[$2 FS $3]+=$1}
       END   {for(k in a) print a[k],k}' file | sort -n

40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11

if user* is not part of the key and you want to capture the first value

$ awk 'BEGIN {FS=OFS="|"}
             {c[$2]+=$1;
              if(!($2 in u)) u[$2]=$3}     # capture first user
       END   {for(k in c) print c[k],k,u[k]}' file | sort -n

which ends up almost the same with @markp's answer.


问:
YouTrackSharp: can't get it to work
Trying to open an issue from a C# app.

Few issues:

1) UPDATE: I realize it only supports .NET Standard 1.3 = Framework 4.6; So no issue here.

2) I install version 2.0.31 (and less) - When I try to set up a connection, it says "Method not allowed":

```<code>var connection = new Connection("xxxx.myjetbrains.com", 80, false, "youtrack");
connection.Authenticate("xxxxx", "xxxxxx");
var issueManagement = new IssueManagement(connection);
dynamic issue = new Issue();
issue.Assignee = "xxxxx";
issue.ProjectShortName = "CV";
issue.Type = "Bug";
issue.Summary = "Test";
issue.Description = "Testing 1 2 3 ...";
issueManagement.CreateIssue(issue);
</code>```

connection.Authenticate throws the error.

3) If I don't specify other parameters in Connection  and leave only the basic url, I get the following error (again in connection.Authenticate):

For security reasons DTD is prohibited in this XML document. To enable
  DTD processing set the DtdProcessing property on XmlReaderSettings to
  Parse and pass the settings into XmlReader.Create method.

Can't seem to find much info on this online. Anyone has any idea what to do?

答:
the 1.3 refers to .NETStandard - NOT .Net Framework.  These are not the same thing.

You need .Net Framework 4.6 or up for .Net Standard 1.3 compatibility.

See here:
https://learn.microsoft.com/en-us/dotnet/standard/net-standard

I'd go directly to jetbrains for the other parts...

Title: YouTrackSharp: can't get it to work

Body:
Trying to open an issue from a C# app.

Few issues:

1) UPDATE: I realize it only supports .NET Standard 1.3 = Framework 4.6; So no issue here.

2) I install version 2.0.31 (and less) - When I try to set up a connection, it says "Method not allowed":

var connection = new Connection("xxxx.myjetbrains.com", 80, false, "youtrack");
connection.Authenticate("xxxxx", "xxxxxx");
var issueManagement = new IssueManagement(connection);
dynamic issue = new Issue();
issue.Assignee = "xxxxx";
issue.ProjectShortName = "CV";
issue.Type = "Bug";
issue.Summary = "Test";
issue.Description = "Testing 1 2 3 ...";
issueManagement.CreateIssue(issue);

connection.Authenticate throws the error.

3) If I don't specify other parameters in Connection  and leave only the basic url, I get the following error (again in connection.Authenticate):

For security reasons DTD is prohibited in this XML document. To enable
  DTD processing set the DtdProcessing property on XmlReaderSettings to
  Parse and pass the settings into XmlReader.Create method.

Can't seem to find much info on this online. Anyone has any idea what to do?


问:
Encrypted Database Connection Strings
I'm using the Oracle.ManagedDataAccess.Client to connect to a oracle database (v.12) in my C# Windows Application.

As example:

```<code>using Oracle.ManagedDataAccess.Client;

string connStr = "user id=username;password=secret;data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=hostname)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=servicename)))";
new OracleConnection(connStr);
</code>```

as you can see the  is in plain text.
Can you suggest how this should be done, preventing passwords in code?

Im using .Net Framework 4.5.1 (Windows Application)

Thank you in advance

答:
The best way to prevent storing database credentials in the code of client app is to get data from the database via some API after authenticating the user in the application (using OpenId Connect or other protocol).

In this case, the API is responsible for communication with the database - not the client, so there is no need to store credentials on the client.

It is a bit different approach than you asked for, but I think it is the best solution.

Title: Encrypted Database Connection Strings

Body:
I'm using the Oracle.ManagedDataAccess.Client to connect to a oracle database (v.12) in my C# Windows Application.

As example:

using Oracle.ManagedDataAccess.Client;

string connStr = "user id=username;password=secret;data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=hostname)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=servicename)))";
new OracleConnection(connStr);

as you can see the  is in plain text.
Can you suggest how this should be done, preventing passwords in code?

Im using .Net Framework 4.5.1 (Windows Application)

Thank you in advance

ContentLicense: CC BY-SA 4.0


问:
How to backup Google Storage buckets?
I need to backup our Google Storage buckets. Versioning is not enough.
I was thinking about:

backup to s3 - is there an automated bucket sync from GS->S3 or out-of-the-box solution for scheduled transfers between buckets?

backup to another GS bucket - in the same gc project, a coldline bucket "replica" with read-only privs to most users and some automated process to replicate/sync the data?

any other ideas?

thanks:)

答:
You could use gsutil rsync to do this:

```<code>gsutil -m rsync -rd gs://your-bucket s3://your-bucket
</code>```

(similarly for syncing between GCS buckets).

You would need to set up a cron job or something similar to cause this to run periodically.

Title: How to backup Google Storage buckets?

Body:
You could use gsutil rsync to do this:

gsutil -m rsync -rd gs://your-bucket s3://your-bucket

(similarly for syncing between GCS buckets).

You would need to set up a cron job or something similar to cause this to run periodically.


问:
Oracle where exists clause not working on SQL Plus
I have a query with a "WHERE EXISTS()" clause.
When I execute it on SQL Developer it returns rows, but when I execute it in SQL Plus it doesn't.

Any one has a clue why this is happening?
Thanks in advance.
Regards,
Joao

答:
If the query returns rows into one database session (say, created by SQL Developer) and doesn't return any rows in the other (say, created by SQL Plus) it means these sessions are different.

The difference may be:

database connected

connected user

current schema

NLS settings

FGAC policy

and so on...

As Juan mentioned, uncommitted data may affect this too.

If you look at some rows in SQL Developer, I'd say check if you can access these rows into SQL Plus (use something like select * from table where id = <id visible in SQL Developer>). If this returns some rows - see why it's filtered by your query in SQL Plus. If this doesn't return rows either see if you are connecting to a different data source or have no access to the data.


问:
Hide/show div based on search input
I have worked out some javascript to use my search bar in order to filter/hide things that don't match the search input. I've got it working about 95% I would say but I have one problem to fix.

So my page displays furniture groups and their containing pieces of furniture. The group name/number and description exists as a heading div and below that there is a table created with the actual pieces of furniture. My current javascript works as long as I'm typing 'sofa' or 'chair' which would be in the table row. However, If I type the name of a furniture group, it just shows the name/number/description and images, but hides the table. The group names/descriptions are in this block:

```<code>@foreach ($orderFormData->pgroups as $pgroup)
<div class="group-container">
        <h3 style="font-size: 26px; padding: 10px 0;">{{ $pgroup->group_name
}} - {{ $pgroup->group_code }}</h3>
        <p class="uk-text-muted" style="font-size: 20px;" >{!!
html_entity_decode($pgroup->group_desc) !!}</p>
</code>```

So, I need to try and slightly refactor this to add the functionality so that if my input matches the group name or description, it still shows the whole table for that div.

An idea I had was to add something like this

```<code><script type="text/javascript">
if($('.group-container').children('tr:visible').length == 0) {
$('.group-container').hide();
} else {
$('.group-container').show();
}
</script>
</code>```

Under my first line of html below, right under the foreach loop. But I don't know if that would be the right idea or how to use that exactly the way it should.

HTML:

```<code>@foreach ($orderFormData->pgroups as $pgroup)
<div class="group-container">
        <h3 style="font-size: 26px; padding: 10px 0;">{{ $pgroup->group_name }} - {{ $pgroup->group_code }}</h3>
        <p class="uk-text-muted" style="font-size: 20px;" >{!! html_entity_decode($pgroup->group_desc) !!}</p> <!--Group Description-->

        <div class="uk-grid">
            <div class="uk-width-2-10">
                <ul style="margin: 0; padding: 0; list-style-type: none; float: left; width: 100%;">
                    @foreach ($pgroup->image_names as $image_name)
                    <li><a href="/imagelib/Bigthumbs/{{ substr($image_name, 0, strpos($image_name, ',')) }}" target=_blank><img src="/imagelib/Bigthumbs/{{ substr($image_name, 0, strpos($image_name, ',')) }}" style="width: 100%; height: auto;" /></a><span class="uk-text-center" style="padding: 0 0 5px;">{{ substr($image_name, strpos( $image_name, ',') + 1)  }}</span></li>
                    @endforeach
                </ul>
            </div>

            <div class="uk-width-8-10">
                <table id="userTbl" class="uk-table" style="width: 100%; min-width: 768px;">
                    <thead>
                    <tr>
                        <th style="width: 10%; font-size: 20px;">Frame</th>
                        <th style="width: 20%; font-size: 20px;">Description</th>
                        <th style="width: 15%; font-size: 20px;">Cover/Color</th>
                        <th style="width: 15%; font-size: 20px;">Cover/Color</th>
                        <th style="width: 20%; font-size: 20px;">Quantity</th>
                        <th style="width: 15%; font-size: 20px; text-align: center;"><b>Price</b></th>
                    </tr>
                    </thead>

                    <tbody>

                    @foreach ($pgroup->pskus as $psku)
                    <?php $tempdata['sku-' . $i] = $psku ?>
                    <tr class="@if (isset($psku->quantity) && $psku->quantity > 0) {{ highlight }} @endif">
                        <td style="font-weight: 500; line-height: 30px; font-size: 14px;">{{ $psku->frame_fmt }}</td>
                        <td style="font-weight: 500; line-height: 30px; font-size: 14px;">{!! html_entity_decode($psku->frame_desc) !!}</td>
                        <td style="font-weight: 500; line-height: 30px; font-size: 14px;">{{ $psku->cover1_code }}/{{ $psku->color1_code }} {{ $psku->color1_desc }}</td>
                        <td style="font-weight: 500; line-height: 30px; font-size: 14px;">{{ $psku->cover2_code }}/{{ $psku->color2_code }} {{ $psku->color2_desc }}</td>
                        <td style="font-weight: 700; line-height: 30px; font-size: 14px;">
                            <span style="text-align: center; display: block; width: 100%;">${{ $psku->price }}</span>
                        </td>
                    </tr>
                    <?php $i++; ?>
                    @endforeach
                    </tbody>
                </table>
            </div>

        </div>
</div>
@endforeach
</code>```

JS:

```<code><script>
$(document).ready(function(){
$("#srch-term").keyup(function(){

    // Retrieve the input field text and reset the count to zero
    var filter = $(this).val(), count = 0;

    // Loop through the main container as well as the table body and row that contains the match
    $(".group-container, tbody tr").each(function(){

        // If the list item does not contain the text phrase fade it out
        if ($(this).text().search(new RegExp(filter, "i")) < 0) {
            $(this).fadeOut();

        // Show the list item if the phrase matches and increase the count by 1
        } else {
            $(this).show();
            count++;
        }
    });
  });
});
</script>
</code>```

答:
You could search the groups first and if the name/description matches, show the whole group and all it's rows. Otherwise do the usual procedure.</p>

```<code><script>
$(document).ready(function(){
$("#srch-term").keyup(function(){

    // Retrieve the input field text and reset the count to zero
    var filter = $(this).val(), count = 0;
    var search_regex = new RegExp(filter, "i")

    // Loop through the main container as well as the table body and row that contains the match
    $(".group-container").each(function(){
        //check if filter matches the group name or description
        var group_name = $(this).children('h3').text()
        var group_description = $(this).children('.uk-text-muted').text()

        if(group_name.search(search_regex)>=0 || group_description.search(search_regex)>=0){ // filter matches
            $(this).show() // show group
            $(this).find("tbody tr").show() // and all children
            return // skip tr filtering
        }

        var no_matches = true

        $(this).find("tbody tr").each(function(){

            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(search_regex) < 0) {
                $(this).fadeOut();

            // Show the list item if the phrase matches and increase the count by 1
            } else {
                $(this).show();
                count++;
                no_matches = false
            }
        });

        if(no_matches){ // if no tr matched the search either, hide whole group
            $(this).fadeOut();
        }

    });
  });
});
</script>
</code>```

Title: Hide/show div based on search input

Body:
I have worked out some javascript to use my search bar in order to filter/hide things that don't match the search input. I've got it working about 95% I would say but I have one problem to fix.

So my page displays furniture groups and their containing pieces of furniture. The group name/number and description exists as a heading div and below that there is a table created with the actual pieces of furniture. My current javascript works as long as I'm typing 'sofa' or 'chair' which would be in the table row. However, If I type the name of a furniture group, it just shows the name/number/description and images, but hides the table. The group names/descriptions are in this block:

@foreach ($orderFormData->pgroups as $pgroup)

{{ $pgroup->group_name
}} - {{ $pgroup->group_code }}

{!!
html_entity_decode($pgroup->group_desc) !!}

So, I need to try and slightly refactor this to add the functionality so that if my input matches the group name or description, it still shows the whole table for that div.

An idea I had was to add something like this

Under my first line of html below, right under the foreach loop. But I don't know if that would be the right idea or how to use that exactly the way it should.

HTML:

@foreach ($orderFormData->pgroups as $pgroup)

{{ $pgroup->group_name }} - {{ $pgroup->group_code }}

{!! html_entity_decode($pgroup->group_desc) !!}

                    @foreach ($pgroup->image_names as $image_name)

{{ substr($image_name, strpos( $image_name, ',') + 1)  }}

                    @endforeach

                        Frame
                        Description
                        Cover/Color
                        Cover/Color
                        Quantity
                        Price

                    @foreach ($pgroup->pskus as $psku)
                    <?php $tempdata['sku-' . $i] = $psku ?>

quantity) && $psku->quantity > 0) {{ highlight }} @endif">
                        {{ $psku->frame_fmt }}
                        {!! html_entity_decode($psku->frame_desc) !!}
                        {{ $psku->cover1_code }}/{{ $psku->color1_code }} {{ $psku->color1_desc }}
                        {{ $psku->cover2_code }}/{{ $psku->color2_code }} {{ $psku->color2_desc }}

                            ${{ $psku->price }}

                    <?php $i++; ?>
                    @endforeach

@endforeach

JS:

Body:
You could search the groups first and if the name/description matches, show the whole group and all it's rows. Otherwise do the usual procedure.

<script>
$(document).ready(function(){
$("#srch-term").keyup(function(){

    // Retrieve the input field text and reset the count to zero
    var filter = $(this).val(), count = 0;
    var search_regex = new RegExp(filter, "i")

    // Loop through the main container as well as the table body and row that contains the match
    $(".group-container").each(function(){
        //check if filter matches the group name or description
        var group_name = $(this).children('h3').text()
        var group_description = $(this).children('.uk-text-muted').text()

        if(group_name.search(search_regex)>=0 || group_description.search(search_regex)>=0){ // filter matches
            $(this).show() // show group
            $(this).find("tbody tr").show() // and all children
            return // skip tr filtering
        }

        var no_matches = true

        $(this).find("tbody tr").each(function(){

            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(search_regex) < 0) {
                $(this).fadeOut();

            // Show the list item if the phrase matches and increase the count by 1
            } else {
                $(this).show();
                count++;
                no_matches = false
            }
        });

        if(no_matches){ // if no tr matched the search either, hide whole group
            $(this).fadeOut();
        }

    });
  });
});
</script>


问:
How to run the same query on all tables in Access Database?
All tables have the same structure the same column names.

Here is a code:

UPDATE Table1
INNER JOIN TableX ON Table1.Column1= TableX.Column1
SET Table1.Column2 = TableX.Column2

But I would like to run this code on all tables: Table2, Table3, Table4....Table30

答:
use the following query to get a list of tables and its schema containing particular column(ColumnX)

```<code>SELECT
  sys.columns.name AS ColumnName,
  sys.tables.name AS TableName,
  schema_name (sys.tables.schema_Id) as schemaName
FROM
  sys.columns
JOIN sys.tables ON
  sys.columns.object_id = sys.tables.object_id
WHERE
  sys.columns.name = 'ColumnName'
  --and schema_name (sys.tables.schema_Id) = 'schemaName'
</code>```

output:(if columnX is ID)

```<code>ColumnName  TableName   schemaName
ID          MusicApp    dbo
id          employ      dbo
</code>```

to get values of ID, you can store above queries output in #temptable and use loop to fetch dynamically

```<code>declare @tablename varchar(max)= ''
 declare @count int = 1
 declare @tablecount int= (select count(*) from #temptable)
 while(@count <= @tablecount)
 begin
 set @tablename = (select tablename from #temptable where seqid = @count)
exec ( 'select id from '+@tablename+' ')
set @count = @count + 1
end
</code>```

hope this helps you :)

Body:
use the following query to get a list of tables and its schema containing particular column(ColumnX)

SELECT
  sys.columns.name AS ColumnName,
  sys.tables.name AS TableName,
  schema_name (sys.tables.schema_Id) as schemaName
FROM
  sys.columns
JOIN sys.tables ON
  sys.columns.object_id = sys.tables.object_id
WHERE
  sys.columns.name = 'ColumnName'
  --and schema_name (sys.tables.schema_Id) = 'schemaName'

output:(if columnX is ID)

ColumnName  TableName   schemaName
ID          MusicApp    dbo
id          employ      dbo

to get values of ID, you can store above queries output in #temptable and use loop to fetch dynamically

declare @tablename varchar(max)= ''
 declare @count int = 1
 declare @tablecount int= (select count(*) from #temptable)
 while(@count <= @tablecount)
 begin
 set @tablename = (select tablename from #temptable where seqid = @count)
exec ( 'select id from '+@tablename+' ')
set @count = @count + 1
end

hope this helps you :)


问:
Match all occurrences from the same dictionary in one line in UIMA RUTA
I have type Dog, which has features size, color and other

Size wordlist: big, medium, small

Other wordlist: old, fat, happy, lazy

Color wordlist does not affect anything in this case, so I won't list it.

And my code (just for the main file):

```<code>PACKAGE dog;

SCRIPT dog.Color;
SCRIPT dog.Size;
SCRIPT dog.Other;

TYPESYSTEM dogTypeSystemDescriptor;

ENGINE utils.PlainTextAnnotator;
TYPESYSTEM utils.PlainTextTypeSystem;

Document{-> CALL(Color)};
Document{-> CALL(Size)};
Document{-> CALL(Other)};

Document{-> EXEC(PlainTextAnnotator, {Line})};

Line{-> CREATE(Dog, "color" = Color, "size" = Size, "other" = Other)};

DECLARE Max, Milo;

Dog{Dog.color.ct == "black",
    Dog.size.ct == "big" -> Max};

Dog{Dog.color.ct == "white",
    Dog.other.ct == "fat" -> Milo};
</code>```

As you can see on the picture, annotation "Milo" is never created (because it relies on the value "fat" of the feature "other" which is in the same dictionary with the "happy", but in the input word "happy" goes before "fat"). If we put "fat" before "happy" in the input - everything works as expected.

So, the question is how can I have annotations created for the each single feature from the same dictionary found in the same input?

答:
Rafael has it right, but I would recommend an FSArray instead of the list. Here's an example tested with Ruta 2.6.1. Mind the "s" in feature "others" and its type FSArray.

```<code>ENGINE utils.PlainTextAnnotator;
TYPESYSTEM utils.PlainTextTypeSystem;

// mock dictionary lookup and scripts
DECLARE Color, Size, Other;
"black|white" -> Color;
"big|small" -> Size;
"lazy|happy|fat" -> Other;

DECLARE Dog (Color color, Size size, FSArray others);

Document{-> EXEC(PlainTextAnnotator, {Line})};

Line{-> CREATE(Dog, "color" = Color, "size" = Size, "others" = Other)};

DECLARE Max, Milo;

Dog{Dog.color.ct == "black",
    Dog.size.ct == "big" -> Max};

Dog{Dog.color.ct == "white",
    Dog.others.ct == "fat" -> Milo};
</code>```

DISCLAIMER: I am a developer of UIMA Ruta

Body:
I have type Dog, which has features size, color and other

Size wordlist: big, medium, small

Other wordlist: old, fat, happy, lazy

Color wordlist does not affect anything in this case, so I won't list it.

And my code (just for the main file):

PACKAGE dog;

SCRIPT dog.Color;
SCRIPT dog.Size;
SCRIPT dog.Other;

TYPESYSTEM dogTypeSystemDescriptor;

ENGINE utils.PlainTextAnnotator;
TYPESYSTEM utils.PlainTextTypeSystem;

Document{-> CALL(Color)};
Document{-> CALL(Size)};
Document{-> CALL(Other)};

Document{-> EXEC(PlainTextAnnotator, {Line})};

Line{-> CREATE(Dog, "color" = Color, "size" = Size, "other" = Other)};

DECLARE Max, Milo;

Dog{Dog.color.ct == "black",
    Dog.size.ct == "big" -> Max};

Dog{Dog.color.ct == "white",
    Dog.other.ct == "fat" -> Milo};

As you can see on the picture, annotation "Milo" is never created (because it relies on the value "fat" of the feature "other" which is in the same dictionary with the "happy", but in the input word "happy" goes before "fat"). If we put "fat" before "happy" in the input - everything works as expected.

So, the question is how can I have annotations created for the each single feature from the same dictionary found in the same input?

Body:
Rafael has it right, but I would recommend an FSArray instead of the list. Here's an example tested with Ruta 2.6.1. Mind the "s" in feature "others" and its type FSArray.

ENGINE utils.PlainTextAnnotator;
TYPESYSTEM utils.PlainTextTypeSystem;

// mock dictionary lookup and scripts
DECLARE Color, Size, Other;
"black|white" -> Color;
"big|small" -> Size;
"lazy|happy|fat" -> Other;

DECLARE Dog (Color color, Size size, FSArray others);

Document{-> EXEC(PlainTextAnnotator, {Line})};

Line{-> CREATE(Dog, "color" = Color, "size" = Size, "others" = Other)};

DECLARE Max, Milo;

Dog{Dog.color.ct == "black",
    Dog.size.ct == "big" -> Max};

Dog{Dog.color.ct == "white",
    Dog.others.ct == "fat" -> Milo};

DISCLAIMER: I am a developer of UIMA Ruta


问:
Automatically generate numerical id when using ElasticSearch with Spring Data
I am currently converting a project I did from Spring Data with Hibernate to Spring Data with ElasticSearch.

Before, I was able to auto generate the id of my entity using the annotation @GeneratedValue(strategy = GenerationType.IDENTITY).  This way, when the entity is saved, an id number is generated for it.

However, I can't seem to find an annotation that ElasticSearch uses to achieve the same result.

The entity using Hibernate annotation:

```<code>@Entity
@Table(name = "person")
public class Person {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private int age;

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
</code>```

Is there an ElasticSearch equivalent to the @GeneratedValue annotation?  If not, what is the optimal way to populate the id field when using ElasticSearch?

答: The documentation on https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-mapping-entity does seem to indicate that @GeneratedValue should work correctly. Are you using the proper integration libraries?

Body:
I am currently converting a project I did from Spring Data with Hibernate to Spring Data with ElasticSearch.

Before, I was able to auto generate the id of my entity using the annotation @GeneratedValue(strategy = GenerationType.IDENTITY).  This way, when the entity is saved, an id number is generated for it.

However, I can't seem to find an annotation that ElasticSearch uses to achieve the same result.

The entity using Hibernate annotation:

@Entity
@Table(name = "person")
public class Person {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private int age;

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    }

Is there an ElasticSearch equivalent to the @GeneratedValue annotation?  If not, what is the optimal way to populate the id field when using ElasticSearch?


问:
JQuery iterate through string occurrences
I've an HTML like this

blalblala bla  blalba  bla and so on...

Now I would to get the left position of all items of kind myID.
I've tried with this code

```<code>var x = "";
$('.myID').each(function(index) {
    x += " " + $(this).position().left+",";
});
return x;
</code>```

But it's wrong because it does not return anything.
What's wrong?
Thanks

答:
```<code>var x = new Array;
$('.myID').each(function(index) { x[index] = $(this).position().left; });
console.log(x);
</code>```

try that and see what is present in the array x.

ContentLicense: CC BY-SA 2.5

Body:
I've an HTML like this

blalblala bla  blalba  bla and so on...

Now I would to get the left position of all items of kind myID.
I've tried with this code

var x = "";
$('.myID').each(function(index) {
    x += " " + $(this).position().left+",";
});
return x;

But it's wrong because it does not return anything.
What's wrong?
Thanks

Body:
var x = new Array;
$('.myID').each(function(index) { x[index] = $(this).position().left; });
console.log(x);

try that and see what is present in the array x.


问:
Using the generic type 'PX.Data.And2' requires 2 type arguments
I'm defining a PXSelect for ARTran in a processing window:

//public PXSelect

//Equal>,

//And2,

//IsNull,

//Or

//Equal>>>>>>

//DetailsView;

But I keep getting this error...and need help.

\App_RuntimeCode\UpdateNotificationContacts.cs(18): error CS0305: Using the generic type 'PX.Data.And2' requires 2 type arguments
\App_RuntimeCode\UpdateNotificationContacts.cs(18): error CS0305: Using the generic type 'PX.Data.And2' requires 2 type arguments

答:
The compilation error is raised because the And2 class has only one generic type argument (Where) in your query:

```<code>And2<Operator<...>>
</code>```

Where2/And2/Or2 requires two generic type argument in their prototype:

```<code>And2<Operator<...>, NextOperator<...>>
</code>```

Your query Where clause can be split into two groups, first one is a single condition and the other one is 2 condition joined with an Or clause.

For this I prefer using Where2 over And2 like this:

```<code>Where2<Where<condition1>, And<condition2, Or<condition3>>>
</code>```

For your query:

```<code>PXSelect<ARTran,
Where<Where2<Where<ARTran.customerID, Equal<Current<UpdateNotificationContactsFilter.customerID>>>,
             And<Current<UpdateNotificationContactsFilter.contactID>, IsNull,
                 Or<ARTranExt.usrContactID, Equal<Current<UpdateNotificationContactsFilter.contactID>>>>>>>
</code>```

Body:
The compilation error is raised because the And2 class has only one generic type argument (Where) in your query:

And2<Operator<...>>

Where2/And2/Or2 requires two generic type argument in their prototype:

And2<Operator<...>, NextOperator<...>>

Your query Where clause can be split into two groups, first one is a single condition and the other one is 2 condition joined with an Or clause.

For this I prefer using Where2 over And2 like this:

Where2<Where<condition1>, And<condition2, Or<condition3>>>

For your query:

PXSelect<ARTran,
Where<Where2<Where<ARTran.customerID, Equal<Current<UpdateNotificationContactsFilter.customerID>>>,
             And<Current<UpdateNotificationContactsFilter.contactID>, IsNull,
                 Or<ARTranExt.usrContactID, Equal<Current<UpdateNotificationContactsFilter.contactID>>>>>>>


问:
Gulp - optipng throws error
Running gulp to build my project.

Throws error:

```<code>[14:35:01] Starting 'images'...

events.js:183
      throw er; // Unhandled 'error' event
      ^
Error: spawn X\node_modules\optipng-bin\vendor\optipng.exe ENOENT
    at _errnoException (util.js:1024:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:190:19)
    at onErrorNT (internal/child_process.js:372:16)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
</code>```

Currently installed OptiPNG version 0.7.6

Not sure what to check or do next?

答: Resolution was to delete node_modules folder and run npm install again.

Title: Gulp - optipng throws error

Body:
Running gulp to build my project.

Throws error:

[14:35:01] Starting 'images'...

events.js:183
      throw er; // Unhandled 'error' event
      ^
Error: spawn X\node_modules\optipng-bin\vendor\optipng.exe ENOENT
    at _errnoException (util.js:1024:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:190:19)
    at onErrorNT (internal/child_process.js:372:16)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Currently installed OptiPNG version 0.7.6

Not sure what to check or do next?


问:
Finding the count of  Jquery
I have the following HTML structure and I wanted to find out the length of immediate s. here is the code that I am using:-

```<code><table class="PrintTable">
    <tr>
      **<td>**
        <table>
            <thead>
                <tr><th>Type Of Transaction</th></tr>
            </thead>
            <tbody>
                <tr>
                    <td>Name</td>
                </tr>
                <tr>
                    <td>Age</td>
                </tr>
            </tbody>
        </table>
      </td>
      **<td>**
        <table>
            <thead>
                <tr><th>2006</th></tr>
            </thead>
            <tbody>
                <tr>
                    <td>Andi</td>
                </tr>
                <tr>
                    <td>25</td>
                </tr>
            </tbody>
        </table>
      </td>

    </tr>
</table>
</code>```

The function that I am using to find out the length of td is

```<code>function getBody(element)
{
    var divider=2;
    var originalTable=element.clone();
    var tds = $(originalTable).children('tr').children('td').length;
    alert(tds);

}
</code>```

The result I am seeing is 0. No clue at all. I am expecting 2. Any help will be appreciated.

答:
I think you want to use the following.

```<code>$("td").length
</code>```

UPDATE

You will want to use the tr tag as the start selector and then count each td selector using first to take just the first one.

```<code>$("tr", $("td:first")).length
</code>```

Title: Finding the count of <td> Jquery

Body:
I have the following HTML structure and I wanted to find out the length of immediate s. here is the code that I am using:-

      ****

Type Of Transaction

                    Name

                    Age

      ****

2006

                    Andi

                    25

The function that I am using to find out the length of td is

function getBody(element)
{
    var divider=2;
    var originalTable=element.clone();
    var tds = $(originalTable).children('tr').children('td').length;
    alert(tds);

}

The result I am seeing is 0. No clue at all. I am expecting 2. Any help will be appreciated.

Body:
I think you want to use the following.

$("td").length

UPDATE

You will want to use the tr tag as the start selector and then count each td selector using first to take just the first one.

$("tr", $("td:first")).length


问:
Cannot open resource file in VS 2015: Can't open include file afxres.h
I converted my VS 2012 projects to VS 2015 by using the automatic conversion tool. When I try to load a resource file (.rc) it fails with this error:

```<code>fatal error RC1015: cannot open include file afxres.h
</code>```

Any idea?

答:
This answer on Thomson Reuters website worked for me. Adding for other users:

You probably need to modify the Visual Studio 2015 setup and add the MFC .

Please close VS2015 and go to Control Panel -> Programs and Features -> Microsoft Visual Studio  -> Change -> Modify -> Add Microsoft Foundation Classes

See the figure below:

Body:
I converted my VS 2012 projects to VS 2015 by using the automatic conversion tool. When I try to load a resource file (.rc) it fails with this error:

fatal error RC1015: cannot open include file afxres.h

Any idea?


问:
Distorterd SCNMorpher weights animation imported from Blender
I'm trying to animate face morphing with Scene Kit and assets exported from Blender using SCNMorpher/Key Shapes.

In the imported DAE file I fix 2 Key Shapes with ColladaMorphAdjuster and I can traverse them at

```<code> node?.morpher?.targets
</code>```

logs as

```<code>Optional([<SCNGeometry: 0x1c4137ca0>, <SCNGeometry: 0x1c4137d40>])
</code>```

But the mesh gets distorted when animated like on SCNMorpher docs site :

```<code>let animation = CABasicAnimation(keyPath: "morpher.weights[0]")
animation.fromValue = 0.0;
animation.toValue = 1.0;
animation.autoreverses = true;
animation.repeatCount = HUGE;
animation.duration = 5;
node?.addAnimation(animation, forKey: nil)
</code>```

I've tried setting unifiesNormals but with no result.

I cannot find the reason why those key shapes produce wrong output in Scene Kit view.

答: Distortion was caused by applying modifiers on export from Blender (Apply Modifiers) - subsurf in my case.</p>

Body:
I'm trying to animate face morphing with Scene Kit and assets exported from Blender using SCNMorpher/Key Shapes.

In the imported DAE file I fix 2 Key Shapes with ColladaMorphAdjuster and I can traverse them at

 node?.morpher?.targets

logs as

Optional([<SCNGeometry: 0x1c4137ca0>, <SCNGeometry: 0x1c4137d40>])

But the mesh gets distorted when animated like on SCNMorpher docs site :

let animation = CABasicAnimation(keyPath: "morpher.weights[0]")
animation.fromValue = 0.0;
animation.toValue = 1.0;
animation.autoreverses = true;
animation.repeatCount = HUGE;
animation.duration = 5;
node?.addAnimation(animation, forKey: nil)

I've tried setting unifiesNormals but with no result.

I cannot find the reason why those key shapes produce wrong output in Scene Kit view.


问:
libcurl-x64.dll was not found
I'm reciving a very odd error. I'm compiling a code which parses JSON data from a url using libcurl. After trial and error I've gotten it compiled without error. However, when trying to run the code I get a system error, saying  libcurl-x64.dll was not found.
Picture of error here
I'm not exactly sure what is finding what, here. My windows system cannot find  libcurl-x64.dll or is it my gcc compiler? Nevertheless, a quick system search shows the location of it. I didn't use it for anything. What exactly do I need to do with  libcurl-x64.dll so that my system can find it? It only pertains to this one parsing program I'm doing, every other cpp/exe file and project works fine. System specs: Windows 10, Dev C++ IDE, mingw g++ compiler.
Here is the location of my supposedly missing file:
FilePath1
FilePath2

答:
It has nothing to do with your compiler. On any OS that supports dynamic
libaries (DLLs on Windows, shared libraries on Linux, etc.), if a program has
been linked to some dynamic library at linktime then, at runtime, the OS
program loader must be able to find that dynamic library in
one of the places where it looks for dynamic libraries by default, or in one
of the places that you specify at runtime in some OS-dependent manner.

This is the nature of dynamic libraries.

In the case of Windows, it means that to run a program you have linked with
libcurl-x64.dll the program loader will try to locate libcurl-x64.dll
using the Search Path Used by Windows to Locate a DLL,
in order to load it into your program's process. If it fails to find libcurl-x64.dll in any of those places
then the program will fail to start, with the error you observed.

Title: libcurl-x64.dll was not found


问:
Use exported class as type in a .d.ts
I have ./class1.ts and ./class2.ts which both look like this:

```<code>export class Class1{ ... }
</code>```

and

```<code>export class Class2{ ... }
</code>```

In ./run.ts I have a function that takes a class input

```<code>function doSomething(klass: ClassType){
    let foo = new klass()
}
</code>```

In ./typings.d.ts I have:

```<code>type ClassType = Class1 | Class2
</code>```

I get an error in typings.d.ts saying that Class1 and Class2 cannot be found.

Adding

```<code>/// <reference path="./class1.ts" />
</code>```

Causes no errors but does not solve the problem.

Adding

```<code>import {Class1} from './class1.ts'
</code>```

Fixes the problem in ./typings.d.ts but it then causes all my typing to be unusable in the project.

How do I use exported classes as types in my project?

答:
Change typings.d.ts to typings.ts with content:

```<code>import { Class1 } from './class1'
import { Class2 } from './class2'

export type ClassType = Class1 | Class2
</code>```

and run.ts to

```<code>import { ClassType } from './typings'

function doSomething(klass: ClassType) {
    let foo = new klass()
}
</code>```

import/export and /// <reference path="..." /> are two different loading concept you shouldn't mix those.

Title: Use exported class as type in a .d.ts

Body:
I have ./class1.ts and ./class2.ts which both look like this:

export class Class1{ ... }

and

export class Class2{ ... }

In ./run.ts I have a function that takes a class input

function doSomething(klass: ClassType){
    let foo = new klass()
}

In ./typings.d.ts I have:

type ClassType = Class1 | Class2

I get an error in typings.d.ts saying that Class1 and Class2 cannot be found.

Adding

/// <reference path="./class1.ts" />

Causes no errors but does not solve the problem.

Adding

import {Class1} from './class1.ts'

Fixes the problem in ./typings.d.ts but it then causes all my typing to be unusable in the project.

How do I use exported classes as types in my project?

Body:
Change typings.d.ts to typings.ts with content:

import { Class1 } from './class1'
import { Class2 } from './class2'

export type ClassType = Class1 | Class2

and run.ts to

import { ClassType } from './typings'

function doSomething(klass: ClassType) {
    let foo = new klass()
}

import/export and /// <reference path="..." /> are two different loading concept you shouldn't mix those.


问:
Pass validation to the controller rails
How can I check if the validation is true and use it in a condition in the controller?

Model

```<code>validate :no_reservation_overlap

scope :overlapping, ->(period_start, period_end) do
  where "((date_start <= ?) and (date_end >= ?))", period_end, period_start
end

private

def no_reservation_overlap
  if (Reservation.overlapping(date_start, date_end).any?)
     errors.add(:date_end, 'it overlaps another reservation')
  end
end
</code>```

Link for more information: Date range overlap per user rails

I want to be able to check if validation is true and pass it to the controller

Controller

```<code>   if validation == true
      #do something
   end
</code>```

I tried using on: create to prevent it from executing a create action.

答:
if @user.valid?
  do something
end

Title: Pass validation to the controller rails

Body:
How can I check if the validation is true and use it in a condition in the controller?

Model

validate :no_reservation_overlap

scope :overlapping, ->(period_start, period_end) do
  where "((date_start <= ?) and (date_end >= ?))", period_end, period_start
end

private

def no_reservation_overlap
  if (Reservation.overlapping(date_start, date_end).any?)
     errors.add(:date_end, 'it overlaps another reservation')
  end
end

Link for more information: Date range overlap per user rails

I want to be able to check if validation is true and pass it to the controller

Controller

   if validation == true
      #do something
   end

I tried using on: create to prevent it from executing a create action.

Body:
if @user.valid?
  do something
end


问:
How to show Woo Category (clothing) and WP Category (php) at a time in wordpress php
I want to show only two categories one from wp categories (category name - php) and one from woo categories (category name - clothing) and hide remaining woo and wp categories except php and clothing. How can i do this?</p>

```<code>function custom_pre_get_posts_query( $q ) {
  $tax_query = (array) $q->get( 'tax_query' );

  $tax_query[] = array(
       'taxonomy' => 'product_cat',
       'field' => 'slug',
       'terms' => array( 'clothing' ), // clothing is woo category name
       'operator' => 'IN'
  );

  $tax_query[] = array(
       'taxonomy' => 'category',
       'field' => 'slug',
       'terms' => array( 'php' ), // php is wp category name
       'operator' => 'IN'
  );

  $q->set( 'tax_query', $tax_query );
}

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
</code>```

答:
```<code>$args = array(
'tax_query' => array(
    'relation' => 'AND',
    array(
        'taxonomy' => 'product_cat',
        'field' => 'slug',
        'terms' => array('clothing'),
        'operator' => 'IN'
    ),
    array(
        'taxonomy' => 'category',
        'field' => 'slug',
        'terms' => array('php'),
        'operator' => 'IN'
    )
  )
);
$query = new WP_Query( $args );
</code>```

Body:
I want to show only two categories one from wp categories (category name - php) and one from woo categories (category name - clothing) and hide remaining woo and wp categories except php and clothing. How can i do this?

function custom_pre_get_posts_query( $q ) {
  $tax_query = (array) $q->get( 'tax_query' );

  $tax_query[] = array(
       'taxonomy' => 'product_cat',
       'field' => 'slug',
       'terms' => array( 'clothing' ), // clothing is woo category name
       'operator' => 'IN'
  );

  $tax_query[] = array(
       'taxonomy' => 'category',
       'field' => 'slug',
       'terms' => array( 'php' ), // php is wp category name
       'operator' => 'IN'
  );

  $q->set( 'tax_query', $tax_query );
}

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );


问:
Is there any way I can run CMD as administrator without admin privileges
I have windows 10 , need to open CMD as admin o that i can change admin password
.My lone admin account somehow changed to standard . Need to fix this issue .
When i boot in safe mode administrator account shows up asking for password , I believe i can change admin password by running cmd as admin and boot up again in safe mode and access the administrator account there .
THANKS IN ADVANCE</p>

答:
So this means you've locked yourself out of your admin account ?

If that's the case. There is a little trick you can use. Boot into a linux live system (partedmagic or anything else) then mount your Windows Partition. Navigate to system32 folder and search for cmd. Rename it to cmd2. then search for utilman.exe and rename it to cmd.exe rename cmd2 to utilman.exe and restart. Once done click the "Help Icon" on your lock screen. It will give you a cmd window with full admin permissions. Change Admin password and revert your changes

Hope this helps :)


问:
How can users get bazel-run.sh?
bazel run typically occupies the Bazel server, blocking other commands.

https://github.com/bazelbuild/bazel/blob/c484f19a2cf7427887d6e4c71c8534806e1ba83e/scripts/bazel-run.sh is a fantastic replacement

Question: what's a good way for end-users to get hold of that shell script and add to their path? Can we make that part of the bazel install?

I tried ls -R $(bazel info install_base) | grep bazel-run but no luck there.

答:
Bazel run is a good replacement for end-user to run a Bazel command if you need to run interactively or multiple command (#2337). There has been no need for us to consider it as an installation script.

Please file an issue on Github to discuss the possibility of installing it along with Bazel.

Title: How can users get bazel-run.sh?


问:
In matlab, how to get all edges of a polygon whose indices are labelled by integers using sets
To put the problem in context: I have a 3D polygon, whose vertices are all labelled by integers 1,...,N, and I have a n*3 matrix faces each of whose rows indicates one of its triangular faces. E.g.

```<code>faces =

     1     3     5
     2     4     6
     1     3     6
     2     4     5
     1     4     5
     2     3     6
     1     4     6
     2     3     5
</code>```

So the first row [1 3 5] denotes the face formed by vertices 1 3 5 and so on. Now I want to get all the edges of these faces.

So I want to use the concept of a set (non-ordered, unique elements). For each row of faces there are three edges, corresponding to three sets, say, {1, 3}, {1, 5}, {3, 5} (here I'm borrowing notations from Python). And I want to create a set of all these sets for all rows. How to do it in Matlab?

In Python it seems I simply can't do a set of sets, since sets are unhashable. In Matlab, it seems everything is a matrix, so I may have to still use a 1x2 matrix to represent each edge, which is fine, but what I want is I don't get duplicated edges. For example, [1 2] and [2 1] are one same edge so I have to make sure one and only one of them is retained in the final dataset.

答:
Here's one way:

create all edges for each triangle (by brute-force)

sort all edges, so that they all "point" in the same direction

select unique ones

Something like this:

```<code>faces = [1     3     5
         2     4     6
         1     3     6
         2     4     5
         1     4     5
         2     3     6
         1     4     6
         2     3     5];

% Create all edges
A = [faces(:, [1 2]); faces(:, [2 3]); faces(:, [1 3])];

% First sort(), then unique()
A = unique(sort(A,2), 'rows')
</code>```

Body:
To put the problem in context: I have a 3D polygon, whose vertices are all labelled by integers 1,...,N, and I have a n*3 matrix faces each of whose rows indicates one of its triangular faces. E.g.

faces =

     1     3     5
     2     4     6
     1     3     6
     2     4     5
     1     4     5
     2     3     6
     1     4     6
     2     3     5

So the first row [1 3 5] denotes the face formed by vertices 1 3 5 and so on. Now I want to get all the edges of these faces.

So I want to use the concept of a set (non-ordered, unique elements). For each row of faces there are three edges, corresponding to three sets, say, {1, 3}, {1, 5}, {3, 5} (here I'm borrowing notations from Python). And I want to create a set of all these sets for all rows. How to do it in Matlab?

In Python it seems I simply can't do a set of sets, since sets are unhashable. In Matlab, it seems everything is a matrix, so I may have to still use a 1x2 matrix to represent each edge, which is fine, but what I want is I don't get duplicated edges. For example, [1 2] and [2 1] are one same edge so I have to make sure one and only one of them is retained in the final dataset.

Body:
Here's one way:

create all edges for each triangle (by brute-force)

sort all edges, so that they all "point" in the same direction

select unique ones

Something like this:

faces = [1     3     5
         2     4     6
         1     3     6
         2     4     5
         1     4     5
         2     3     6
         1     4     6
         2     3     5];

% Create all edges
A = [faces(:, [1 2]); faces(:, [2 3]); faces(:, [1 3])];

% First sort(), then unique()
A = unique(sort(A,2), 'rows')


问:
Qt QWizard validateCurrentPage isn't called on last page
I have a QWizard, and I override validateCurrentPage() in order to perform actions before passing to the next page.
This function is working well on all pages, except for the last page - where Finish is pressed.
the accept() function is called, but not validateCurrentPage().

Judging by Qt docs:

This virtual function is called by QWizard when the user clicks Next or Finish to perform some last-minute validation

this function was supposed to be called just like in any other page.

Why isn't it working?

答: The problem was that I overridden QDialog::accept() and unless I call QDialog::accept(), validateCurrentPage() wouldn't be called.</p>


问:
.setAdapter doesn't work
The ListView is empty. The Logcat haven't an error. The application can read the data from the website. I checked it with the "Log.i("String", readLine.toString());" command.

```<code>String gamehost = "https://example.com";

private SharedPreferences speicher;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_worldhighscore);
    speicher = getApplicationContext().getSharedPreferences("Data", 0);
    editor = speicher.edit();

    String userid = speicher.getString("userid", null);

    ArrayList<String> strArray;
    strArray = new ArrayList<String>();
    ArrayAdapter<String> stradapt;
    String quellcodee = null;
    URL urle = null;

    ListView listView = (ListView) findViewById(R.id.listviewuser);
    try {
        urle = new URL(gamehost + "/highscoreread.php");
        String readLine = null;
        BufferedReader buffReader = new BufferedReader (new InputStreamReader(urle.openStream ()));
        while ((readLine = buffReader.readLine ()) != null) {
            strArray.add(readLine);
            Log.e("Data", readLine.toString());
        }
    }
    catch (MalformedURLException me) {
        me.printStackTrace();
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }

    stradapt = new ArrayAdapter<String>(Worldhighscore.this, android.R.layout.simple_list_item_1, strArray);
    listView.setAdapter(stradapt);
    Log.e("Datas", strArray.toString());
}
</code>```

Logcat:
  I/Data: 1305957942849692 - 18
  I/Data: 1587261998061410 - 10
  I/Data: 88030 - 4
  I/Datas: [1305957942849692 - 18, 1587261998061410 - 10, 88030 - 4]

The R.layout.activity_worldhighscore:

```<code><ListView
    android:id="@+id/listviewuser"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="56dp"
    android:headerDividersEnabled="false"
    android:scrollbars="horizontal"
    android:visibility="visible"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1" />
</code>```

Edit: The code is changed.

答:
Try Use This

```<code>public class Adapter extends ArrayAdapter {
    List arr;
    int resource;
    Context context;
    public Adapter(Context context, int resource, List arr) {
        super(context, resource, arr);
        this.arr=arr;
        this.resource=resource;
        this.context=context;
    }
    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        View rowView;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.layout_adapter, parent, false);
        TextView param1=(TextView)rowView.findViewById(R.id.param1);
        TextView param2=(TextView)rowView.findViewById(R.id.param2);
        final ArrayList<Class.MyOBJECT> data=(ArrayList<Class.MyOBJECT>)arr;
        param1.setText(data.get(position).param1);
        param2.setText(data.get(position).param2);

        return rowView;
    }
}
</code>```

...

```<code>Adapter adapter=new Adapter(this,R.layout..,arr);
ListView.setAdapter(adapter);
</code>```

and also next approach if you want to use default adapter

put this

```<code>stradapt = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, strArray);
</code>```

instead of

```<code>stradapt = new ArrayAdapter<String>(Worldhighscore.this, android.R.layout.simple_list_item_1, strArray);
</code>```

Title: .setAdapter doesn't work

Body:
The ListView is empty. The Logcat haven't an error. The application can read the data from the website. I checked it with the "Log.i("String", readLine.toString());" command.

String gamehost = "https://example.com";

private SharedPreferences speicher;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_worldhighscore);
    speicher = getApplicationContext().getSharedPreferences("Data", 0);
    editor = speicher.edit();

    String userid = speicher.getString("userid", null);

    ArrayList<String> strArray;
    strArray = new ArrayList<String>();
    ArrayAdapter<String> stradapt;
    String quellcodee = null;
    URL urle = null;

    ListView listView = (ListView) findViewById(R.id.listviewuser);
    try {
        urle = new URL(gamehost + "/highscoreread.php");
        String readLine = null;
        BufferedReader buffReader = new BufferedReader (new InputStreamReader(urle.openStream ()));
        while ((readLine = buffReader.readLine ()) != null) {
            strArray.add(readLine);
            Log.e("Data", readLine.toString());
        }
    }
    catch (MalformedURLException me) {
        me.printStackTrace();
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }

    stradapt = new ArrayAdapter<String>(Worldhighscore.this, android.R.layout.simple_list_item_1, strArray);
    listView.setAdapter(stradapt);
    Log.e("Datas", strArray.toString());
}

Logcat:
  I/Data: 1305957942849692 - 18
  I/Data: 1587261998061410 - 10
  I/Data: 88030 - 4
  I/Datas: [1305957942849692 - 18, 1587261998061410 - 10, 88030 - 4]

The R.layout.activity_worldhighscore:

<ListView
    android:id="@+id/listviewuser"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="56dp"
    android:headerDividersEnabled="false"
    android:scrollbars="horizontal"
    android:visibility="visible"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1" />

Edit: The code is changed.

Body:
Try Use This

public class Adapter extends ArrayAdapter {
    List arr;
    int resource;
    Context context;
    public Adapter(Context context, int resource, List arr) {
        super(context, resource, arr);
        this.arr=arr;
        this.resource=resource;
        this.context=context;
    }
    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        View rowView;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.layout_adapter, parent, false);
        TextView param1=(TextView)rowView.findViewById(R.id.param1);
        TextView param2=(TextView)rowView.findViewById(R.id.param2);
        final ArrayList<Class.MyOBJECT> data=(ArrayList<Class.MyOBJECT>)arr;
        param1.setText(data.get(position).param1);
        param2.setText(data.get(position).param2);

        return rowView;
    }
}

...

Adapter adapter=new Adapter(this,R.layout..,arr);
ListView.setAdapter(adapter);

and also next approach if you want to use default adapter

put this

stradapt = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, strArray);

instead of

stradapt = new ArrayAdapter<String>(Worldhighscore.this, android.R.layout.simple_list_item_1, strArray);


问:
openGL moving camera
I m trying to move my camera. I am using gluLookAt function. I have some variables for this.

```<code>float x,y,z ==> is camera location
float lx,ly,lz ==> is point that camera looks.
</code>```

I try to move on x axis

```<code>x= x+0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);
</code>```

it is work.

When i try to move on z axis as same as above

```<code>z = z +0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);
</code>```

nothing  change. Also when i invoke this function several times, first half of object dissapear (corners of object) and after next calling gluLookAt object dissapear completely.

I want the object looks bigger when camera move forward and smaller when camera move backward. But any changes is occured when i move camera on z axis.

What is the problem? Why object dissapear? How can i achieve that object get bigger when moving camera forward.

I know i can solve it by glTranslate or increasing size of object. But i want to use  gluLookAt.

Thanks you for answers.

答: Sounds like you haven't set up your projection matrix correctly. Use gluPerspective (gl http://www.opengl.org/sdk/docs/man/xhtml/gluPerspective.xml) and make sure the zNear and zFar parameters will accommodate your object.</p>

Title: openGL moving camera

Body:
I m trying to move my camera. I am using gluLookAt function. I have some variables for this.

float x,y,z ==> is camera location
float lx,ly,lz ==> is point that camera looks.

I try to move on x axis

x= x+0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);

it is work.

When i try to move on z axis as same as above

z = z +0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);

nothing  change. Also when i invoke this function several times, first half of object dissapear (corners of object) and after next calling gluLookAt object dissapear completely.

I want the object looks bigger when camera move forward and smaller when camera move backward. But any changes is occured when i move camera on z axis.

What is the problem? Why object dissapear? How can i achieve that object get bigger when moving camera forward.

I know i can solve it by glTranslate or increasing size of object. But i want to use  gluLookAt.

Thanks you for answers.


问:
How I can change render to return json in view Django
I have function in view

```<code>from django.shortcuts import render
from .models import myModel

def articleTheme(request):
    if request.method == 'POST':
        article_id = request.POST['id']
        article = myModel.objects.get(id=article_id)
        theme = article.theme
        return render(request, 'theme.html', {'newTheme': theme })
</code>```

now it works normal. But I have excess html. I want return json object.
What I can import and return?

答:
You can return the data with HttpResponse and in JSON format like this:

```<code>data = {'newTheme': theme}
data = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(data)
</code>```

Body:
I have function in view

from django.shortcuts import render
from .models import myModel

def articleTheme(request):
    if request.method == 'POST':
        article_id = request.POST['id']
        article = myModel.objects.get(id=article_id)
        theme = article.theme
        return render(request, 'theme.html', {'newTheme': theme })

now it works normal. But I have excess html. I want return json object.
What I can import and return?

Body:
You can return the data with HttpResponse and in JSON format like this:

data = {'newTheme': theme}
data = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(data)


答:
Just call valid? on an ActiveRecord object.  For example:

```<code>@reservation = Reservation.new(reservation_params)

if @reservation.valid?
  # Do something if any validation fails
  if @reservation.errors[:date_end].include? 'it overlaps another reservation'
    # Do something if the overlapping validation fails
  end
end
</code>```

You can read more about validations in the Ruby on Rails Guide

If you want to check for a specific validation error, you can look at this Stack Overflow question.

Title: Pass validation to the controller rails

Body:
Just call valid? on an ActiveRecord object.  For example:

@reservation = Reservation.new(reservation_params)

if @reservation.valid?
  # Do something if any validation fails
  if @reservation.errors[:date_end].include? 'it overlaps another reservation'
    # Do something if the overlapping validation fails
  end
end

You can read more about validations in the Ruby on Rails Guide

If you want to check for a specific validation error, you can look at this Stack Overflow question.


问:
Can I compare current month to previous month, day to day?
How can I compare current month to previous month, day to day?

I'm due to create a report that compares the current month to the previous month but the code I've written only has volumes and values in one column. Ideally I'd have last months data  in one column and this months data in another column.

Thanks in advance

答:
Whenever you want to compare rows of the same table, you have to join the table to itself and give it to distinct aliases (here A and B):

```<code>SELECT A.Value - B.Value As Difference, ...
FROM
    myTable A
    INNER JOIN myTable B
        ON A.theDate = DATEADD(month, 1, B.theDate);
</code>```

Here the A table represents the current month where as B represents the previous month. I assume that the dates do not contain times and that you have pure dates (i.e. time = 00:00:00). However, if you have times, you can truncate them with CAST(theDate As Date).

You might have to add other conditions to the join ON-clause, like AND A.CustomerID = B.CustomerID to get the right pairing of rows. Also add a where clause, if you want to restrict the date range.

Body:
Whenever you want to compare rows of the same table, you have to join the table to itself and give it to distinct aliases (here A and B):

SELECT A.Value - B.Value As Difference, ...
FROM
    myTable A
    INNER JOIN myTable B
        ON A.theDate = DATEADD(month, 1, B.theDate);

Here the A table represents the current month where as B represents the previous month. I assume that the dates do not contain times and that you have pure dates (i.e. time = 00:00:00). However, if you have times, you can truncate them with CAST(theDate As Date).

You might have to add other conditions to the join ON-clause, like AND A.CustomerID = B.CustomerID to get the right pairing of rows. Also add a where clause, if you want to restrict the date range.


问:
Error loading Python dll/ LoadLibrary: The specified module could not be found
I am new at programming. I wrote a small program in python and converted it to .exe file with pyinstaller. Now when i try to open the .exe file a black screen appears and closes immediately. I was able to get a screenshot:

I saw a solution like adding input() at the end of the code but it didn't work either. My code:

```<code>import random

print("Hello, what is your name?")
name = str(input())
print("Well, " + name + ", I think of a number between 1 and 1000. Can you guess this number in 10 chances?")
number = random.randint(1, 1001)

for guessTaken in range(1, 11):
  print("Take a guess")
  guess = int(input())
  if guess > number:
    print("The number you think is too high")
  elif guess < number:
    print("The number you think is too low")
  else:
    break

if guess == number:
  print("OK, " + name + ", you guessed the number in " + str(guessTaken) + " guesses")
else:
  print("Unfortunatelly, you couldn't find the number. The number is " + str(number))
</code>```

答:
The problem seen in the screenshot is that the Python Library cannot be found. So some configuration in your pyinstaller is wrong. Are you sure that python36.dll is in that folder? Check where your python36.dll is located (normally in the same folder where your python installation is located and your python.exe can be found). Maybe you need to add this path to your Windows Path Configuration?

Please check the following two answers to see if your pyinstaller is configured correctly:

PyInstaller not working on simple HelloWorld Program

Error loading python27.dll error for pyinstaller

The situation should be similar for you with Python 3.6

Body:
I am new at programming. I wrote a small program in python and converted it to .exe file with pyinstaller. Now when i try to open the .exe file a black screen appears and closes immediately. I was able to get a screenshot:

I saw a solution like adding input() at the end of the code but it didn't work either. My code:

import random

print("Hello, what is your name?")
name = str(input())
print("Well, " + name + ", I think of a number between 1 and 1000. Can you guess this number in 10 chances?")
number = random.randint(1, 1001)

for guessTaken in range(1, 11):
  print("Take a guess")
  guess = int(input())
  if guess > number:
    print("The number you think is too high")
  elif guess < number:
    print("The number you think is too low")
  else:
    break

if guess == number:
  print("OK, " + name + ", you guessed the number in " + str(guessTaken) + " guesses")
else:
  print("Unfortunatelly, you couldn't find the number. The number is " + str(number))


问:
message queue thinking
We have implemented a message queue by using C# Queue. We know we only have ONE consumer to take available message out from the queue for processing with a while loop. We also know there is only ONE producer to put message onto the queue.

We have a lock on above message queue to make sure the consumer and producer cannot access the queue simultaneously.

My question is is that lock necessary? If the Queue increase its Count property AFTER an item is actually added and if the consumer check the Count before retrieve, the consumer should get a complete message item even we don't have that lock. Right? So we will not face a partial message item issue. Then we can get rid of that lock?

That lock will slow down the system and occasionally we can see the retrieve thread is blocked for a while because we have a very heavy producer.

EDIT:

Unfortunately we are using .Net 3.5.

答:
No, this won't work consistently... why?

Let's disassemble the two methods we are going to be calling concurrently from two threads (one read & one writer):

```<code>public T Dequeue()
{
    if (this._size == 0)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyQueue);
    }
    T local = this._array[this._head];
    this._array[this._head] = default(T);
    this._head = (this._head + 1) % this._array.Length;
    this._size--;
    this._version++;
    return local;
}

public void Enqueue(T item)
{
    if (this._size == this._array.Length)
    {
        int capacity = (int) ((this._array.Length * 200L) / 100L);
        if (capacity < (this._array.Length + 4))
        {
            capacity = this._array.Length + 4;
        }
        this.SetCapacity(capacity);
    }
    this._array[this._tail] = item;
    this._tail = (this._tail + 1) % this._array.Length;
    this._size++;
    this._version++;
}
</code>```

Given the above code three of the variables are safe if (and only if) there is adequate capacity in the queue.  the fields for _array, _head, and _tail are either unmodified or modified in only one of the two methods above.

The reason you cannot remove the lock() is that both methods modify _size and _version.  Though arguably the collision on _version could be ignored, the collision on _size would cause some undesired and unpredictable behavior.

Title: message queue thinking

Body:
No, this won't work consistently... why?

Let's disassemble the two methods we are going to be calling concurrently from two threads (one read & one writer):

public T Dequeue()
{
    if (this._size == 0)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyQueue);
    }
    T local = this._array[this._head];
    this._array[this._head] = default(T);
    this._head = (this._head + 1) % this._array.Length;
    this._size--;
    this._version++;
    return local;
}

public void Enqueue(T item)
{
    if (this._size == this._array.Length)
    {
        int capacity = (int) ((this._array.Length * 200L) / 100L);
        if (capacity < (this._array.Length + 4))
        {
            capacity = this._array.Length + 4;
        }
        this.SetCapacity(capacity);
    }
    this._array[this._tail] = item;
    this._tail = (this._tail + 1) % this._array.Length;
    this._size++;
    this._version++;
}

Given the above code three of the variables are safe if (and only if) there is adequate capacity in the queue.  the fields for _array, _head, and _tail are either unmodified or modified in only one of the two methods above.

The reason you cannot remove the lock() is that both methods modify _size and _version.  Though arguably the collision on _version could be ignored, the collision on _size would cause some undesired and unpredictable behavior.


问:
Trying to retain selected checkbox/radio buttons value if previously selected
```<code>@Request.Form["Gender"] == "Male" ? "selected" : ""
</code>```

Keeps saying I'm missing name attribute.

答:
You need to save the value of radiobutton to your database. Then create conditional. If radiobutton just 2 options, use if conditional to keep selected radiobutton. And if more than 2 options you can use switch conditional.

This is sample of radiobutton:

```<code><input type="radio" name="gender" id="male" value="Male" /> Male</div>
<input type="radio" name="gender" id="female" value="Female" /> Female</div>
<input type="radio" name="gender" id="other" value="Other" /> Other</div>
</code>```

The script to keep selected radiobutton:

```<code><script>
    var gender = "@Model.Gender";
    switch (theme) {
        case "Male":
            document.getElementById("male").checked = true;;
            break;
    case "Female":
            document.getElementById("female").checked = true;;
            break;
    case "Other":
            document.getElementById("other").checked = true;;
            break;
    }
</script>
</code>```

"Model.Gender" is the way used to call the value stored in the database.

Body:
@Request.Form["Gender"] == "Male" ? "selected" : ""

Keeps saying I'm missing name attribute.

Body:
You need to save the value of radiobutton to your database. Then create conditional. If radiobutton just 2 options, use if conditional to keep selected radiobutton. And if more than 2 options you can use switch conditional.

This is sample of radiobutton:

<input type="radio" name="gender" id="male" value="Male" /> Male</div>
<input type="radio" name="gender" id="female" value="Female" /> Female</div>
<input type="radio" name="gender" id="other" value="Other" /> Other</div>

The script to keep selected radiobutton:

<script>
    var gender = "@Model.Gender";
    switch (theme) {
        case "Male":
            document.getElementById("male").checked = true;;
            break;
    case "Female":
            document.getElementById("female").checked = true;;
            break;
    case "Other":
            document.getElementById("other").checked = true;;
            break;
    }
</script>

"Model.Gender" is the way used to call the value stored in the database.


问:
Can't make a network call from background notification after app force-quit and phone restart
I am using background notifications in my app. And I use it to make a small call to our server after each notification. Tested on iPhone 5/6 and iOS 11

In those cases I am able to call the server to mark my notification as received :

the app is in foreground

the app is in background

I just reboot my device

But sometimes users kill the app and then I can not call my server, that is a normal behaviour of background notification.

BUT, from the documentation :

However, the system does not automatically launch your app if the user
  has force-quit it. In that situation, the user must relaunch your app
  or restart the device before the system attempts to launch your app
  automatically again.

Source : https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application

So if I am correct, if I force quit the app and then restart my device I should be able to make a network call again after phone restart.

This is my issue, it does not work. After a force quit of my app and a phone restart the notification is displayed on the screen of the phone but the network call is not done.

Do you have the same issue ? Do you know a solution ?

答: Your application has to be in the multitasking stack to make a call to server when notification is received. That is, application has to opened atleast once after the reboot to meet your expectation.</p>


问:
Stripe Custom Checkout with dynamically amount
I need to implement a stripe solution for a registration system. In this registration, users pay a single time payment and have the choice to make a donation.
My problem is how to show dynamically the total amount (Registration + donation)with checkout.js ?

The payment works perfectly on Stripe Dashboard. Donation + Registration fee are added together. My problem is to dynamically put the amount on the checkout window. On this window, just appear "Pay", I want if it's possible to have Pay $amount.

For information, I'm using Wordpress.

Thank you.

Here is my page.php :

```<code><form action="myURL/charge.php" method="POST" id="payment-form">

<!-- //Header -->
<!--<div class="form-header"><p>Powered by Stripe</p></div>-->
<span  id="card-errors" class="payment-errors" style="color: red; font-size: 22px; "></span>

<!-- // First and Last Name -->
<div class="form-row left"><label for="firstname" class="next-line">First Name</label><input type="text" name="fname" value="<?php ( isset( $_POST['fname'] ) ? $first_name : null ) ?>"></div>
<div class="form-row right"><label for="lastname" class="next-line">Last Name</label><input type="text" name="lname" value="<?php ( isset( $_POST['lname'] ) ? $last_name : null ) ?>"></div>

<!-- //Email -->
<div><label for="email">Email <strong>*</strong></label><input type="text" name="email" value="<?php ( isset( $_POST['email'] ) ? $email : null ) ?>"></div>
<!-- //Phone-->
<div><label for="phone">Phone</label><input type="tel" name="phone" value="<?php ( isset( $_POST['phone'] ) ? $phone : null ) ?>"></div>
<select name="registration_fee" id="registration_fee" required>
    <option selected="selected" disabled>Choose registration </option>
    <option value="1200">18 - 29 year</option>
    <option value="1600">30 - 39 year</option>
</select>
    <div class="form-row left"><label for="donation" class="next-line">Donation</label><input type="text" name="donation" value="<?php ( isset( $_POST['donation'] ) ? $donation : null ) ?>"></div>

<div id="card-element">
  <!-- a Stripe Element will be inserted here. -->
</div>

<!--Submit-->
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="XXXXXXXxXXXXXXXX"
data-amount="$registration_fee + $donation"
data-name="XXXX XXXXX"
data-description="Widget"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto"
data-currency="eur">
</code>```

And charge.php :

```<code><?php
$email = $_POST['email'];
$phone = $_POST['phone'];
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
try {
    require_once('Stripe/init.php');

    // Use Stripe's library to make requests...
    \Stripe\Stripe::setApiKey("sk_test_XXXXXXXXXXXXXXX");

    $token  = $_POST['stripeToken'];

    isset ($_POST['registration_fee']) ? $registration_fee = $_POST['registration_fee'] : '';
    isset ($_POST['donation']) ? $donation = $_POST['donation'] : '';

    $response = \Stripe\Charge::create(array(
        //'customer' => $customer->id,
        'amount' => $registration_fee + $donation ,
        'currency' => "eur",
        'source' => $token,
        // "source" => "tok_mastercard", // obtained with Stripe.js
        //"metadata" => array("order_id" => "6735")

    ));

    //print_r($response);

    /*===========================
        send email
    ============================*/

    $strTo = 'XXXXXXX@XXXXXXX.com';
    $strName = $first_name . ' ' . $last_name;

    $strEmail = $email;
    $strPhone = $phone;
    // Uniqid Session //
    $strSid = md5(uniqid(time()));
    $strHeader = "";
    $strHeader .= "From: ".$strName."<".$strEmail.">\nReply-To: ".$strEmail."";
    $strSubject = 'Form Submission from ' . $strName;
    $strHeader .= "\nMIME-Version: 1.0\n";
    $strHeader .= "Content-Type: multipart/mixed; boundary=\"".$strSid."\"\n\n";
    $strHeader .= "This is a multi-part message in MIME format.\n";
    $strHeader .= "--".$strSid."\n";
    $strHeader .= "Content-type: text/html; charset=utf-8\n";
    $strHeader .= "Content-Transfer-Encoding: 7bit\n\n";
    $strHeader .= "Name: \n";
    $strHeader .= $strName."\n\n";
    $strHeader .= "Email: \n";
    $strHeader .= $strEmail."\n\n";
    $strHeader .= "Phone: \n";
    $strHeader .= $strPhone."\n\n";

    $flgSend = mail("$strTo", "$strSubject", $strHeader);  // @ = No Show Error //

    if($flgSend) {

        $clientHeader = "";
        $clientHeader .= "From: " . "NAME_HERE" . "<" . "REPLYTO@EXAMPLE.COM" . ">\n";
        $clientHeader .= "Reply-To: " . "XXXXX@XXXXX.com" . "\n";

        $clientSubject = 'Thank you, ' . $strName . ' for your purchase of XXXXXXXXXXXXXXX.';

        $clientHeader .= "\nMIME-Version: 1.0\n";
        $clientHeader .= "Content-Type: multipart/mixed; boundary=\"".$strSid."\"\n\n";
        $clientHeader .= "This is a multi-part message in MIME format.\n";
        $clientHeader .= "--".$strSid."\n";
        $clientHeader .= "Content-type: text/html; charset=utf-8\n";
        $clientHeader .= "Content-Transfer-Encoding: 7bit\n\n";

        $clientHeader .= "Congrats, " . $strName . " paid $XX.00 to XXXX for XXXXXXXXXXXXXXXXXXXX!" . "\n\n";
        $clientHeader .= "Name: \n";
        $clientHeader .= $strName."\n\n";
        $clientHeader .= "Email: \n";
        $clientHeader .= $strEmail."\n\n";
        $clientHeader .= "Phone: \n";
        $clientHeader .= $strPhone."\n\n";

        $emailtoClient = mail($strEmail, "$clientSubject", $clientHeader);

        header("Location: https://XXXXXXXX.com/thank-you");
        die();
    } else {
        echo "Cannot send mail.";
    }

} catch(\Stripe\Error\Card $e) {
    // Since it's a decline, \Stripe\Error\Card will be caught
    $body = $e->getJsonBody();
    $err  = $body['error'];
    print('Status is:' . $e->getHttpStatus() . "\n");
    print('Type is:' . $err['type'] . "\n");
    print('Code is:' . $err['code'] . "\n");
    // param is '' in this case
    print('Param is:' . $err['param'] . "\n");
    print('Message is:' . $err['message'] . "\n");
} catch (\Stripe\Error\RateLimit $e) {
    // Too many requests made to the API too quickly
     echo "Too many requests sent to Stripe's API too quickly";
} catch (\Stripe\Error\InvalidRequest $e) {
    // Invalid parameters were supplied to Stripe's API
    print_r($response);
    //echo ("test");
    echo " Invalid parameters were supplied to Stripe's API";
} catch (\Stripe\Error\Authentication $e) {
    // Authentication with Stripe's API failed
    // (maybe you changed API keys recently)
    echo " Authentication with Stripe's API failed";
} catch (\Stripe\Error\ApiConnection $e) {
    // Network communication with Stripe failed
    echo " Network communication with Stripe failed";
} catch (\Stripe\Error\Base $e) {
    // Display a very generic error to the user, and maybe send
    // yourself an email
    echo "You have encountered an error!";
} catch (Exception $e) {
    // Something else happened, completely unrelated to Stripe
     echo "Error: Something else happened, completely unrelated to Stripe";
}

?>
</code>```

答:
Here is my solution. Use jQuery/Javascript. I advise adding the id="donation" to the donation input field, and also a placeholder="10.00" as an example of donation input. </p>

```<code>jQuery(document).ready(function($) {
    var first_price = 0;
    var second_price = 0;
    var total_price = 0;

  $('#registration_fee').on( "change", function() {
    first_price = $('#registration_fee').val();
    first_price = parseInt( first_price );
    //console.log( first_price );
  });

  $('#donation').on( "change", function() {
    second_price = $('#donation').val();
    second_price = parseInt( second_price );
    //console.log( second_price );
  });

  $('#payment-form').on( "change", function() {
    total_price = first_price + second_price;
    //console.log( "total: " + total_price );
    $('.stripe-button-el span').html( "Pay with Card $" + total_price );
  });

});
</code>```

Body:
I need to implement a stripe solution for a registration system. In this registration, users pay a single time payment and have the choice to make a donation.
My problem is how to show dynamically the total amount (Registration + donation)with checkout.js ?

The payment works perfectly on Stripe Dashboard. Donation + Registration fee are added together. My problem is to dynamically put the amount on the checkout window. On this window, just appear "Pay", I want if it's possible to have Pay $amount.

For information, I'm using Wordpress.

Thank you.

Here is my page.php :

<form action="myURL/charge.php" method="POST" id="payment-form">

First Name<input type="text" name="fname" value="<?php ( isset( $_POST['fname'] ) ? $first_name : null ) ?>">

Last Name<input type="text" name="lname" value="<?php ( isset( $_POST['lname'] ) ? $last_name : null ) ?>">

Email *<input type="text" name="email" value="<?php ( isset( $_POST['email'] ) ? $email : null ) ?>">

Phone<input type="tel" name="phone" value="<?php ( isset( $_POST['phone'] ) ? $phone : null ) ?>">

<select name="registration_fee" id="registration_fee" required>
    <option selected="selected" disabled>Choose registration </option>
    <option value="1200">18 - 29 year</option>
    <option value="1600">30 - 39 year</option>
</select>

Donation<input type="text" name="donation" value="<?php ( isset( $_POST['donation'] ) ? $donation : null ) ?>">

Body:
Here is my solution. Use jQuery/Javascript. I advise adding the id="donation" to the donation input field, and also a placeholder="10.00" as an example of donation input.

jQuery(document).ready(function($) {
    var first_price = 0;
    var second_price = 0;
    var total_price = 0;

  $('#registration_fee').on( "change", function() {
    first_price = $('#registration_fee').val();
    first_price = parseInt( first_price );
    //console.log( first_price );
  });

  $('#donation').on( "change", function() {
    second_price = $('#donation').val();
    second_price = parseInt( second_price );
    //console.log( second_price );
  });

  $('#payment-form').on( "change", function() {
    total_price = first_price + second_price;
    //console.log( "total: " + total_price );
    $('.stripe-button-el span').html( "Pay with Card $" + total_price );
  });

});


问:
Redirect HTTP to HTTPS or deny usage of HTTP?
Configuring on Apache HTTPD server, many articles on the web advise to enforce HTTPS protocol by redirecting (permanently) all HTTP request to HTTPS.

Below is what I understand is happening when a user tries to reach a server supporting both HTTP and HTTPS :

Client's user agent (web browser for example, but not only) sends a request to http://my.domain.com.

Server receives request on port 80, and sends a permanent redirection (code 301) to https://my.domain.com.

Client's user agent receives the response. Given the status code, it sends the same request to https://my.domain.com.

Server receives request on port 443 and sends back the wanted content.

So, if the request contains sensitive data, between steps 1 and 2, a man-in-the-middle could recover it, non-ciphered, in the request.

If the client uses a web browser, this browser keeps in cache the 301 redirection, and the next time the client send a request using HTTP, it will automatically send it using HTTPS instead.

But, what if the client clears the cache often ? Or use another user agent than a web browser, which does not store the permanent redirection ? Don't we lose the benefit of HTTPS here ?

A concrete example : a REST API, and the requests contain sensitive data. This API can be called from any HTTP client (online, embed in a software or website, standalone).

In this case, could it be better to just disable HTTP support on server level in order to enforce the use of HTTPS ?

Edit 2017-11-14:

sys0dm1n told me about HSTS below. But the security provided by this mechanism depends entirely on the user agent's compliance to the specification.

Edit 2017-11-15:

I edit my post after the first answers I receive, to precise my concern.

答:
To make sure always your website is using https for security, one way is to enable HSTS

Automatically turn any insecure links referencing the web application into secure links.

To enable it, you need to add a header in your vHost configuration:

```<code>Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains;"
</code>```

Make sure the Header module is enabled.

You can follow the instruction here and add your domain for inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list.

This is a list of sites that are hardcoded into Chrome as being HTTPS only.

Body:
To make sure always your website is using https for security, one way is to enable HSTS

Automatically turn any insecure links referencing the web application into secure links.

To enable it, you need to add a header in your vHost configuration:

Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains;"

Make sure the Header module is enabled.

You can follow the instruction here and add your domain for inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list.

This is a list of sites that are hardcoded into Chrome as being HTTPS only.


问:
formData.delete() not a known property
Am using a FormData object to upload a file , i want the functionality of deleting file from FormData, but i get an error delete property does not exist on FormData object

```<code>formData.delete(fileName)
</code>```

Code

```<code>upload(){
    let formData = new FormData();
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let files: FileList = inputEl.files;
    formData.append('uploadFile', files, files.name);
}

delete(fileName){
    formData.delete(fileName);
}
</code>```

答:
Variables cannot be shared between methods, so you'll need to use a property, or call the method and get a result.

The example below stores the formData in a private property and references it within each method with this.formData.

```<code>private formData: FormData;

upload() {
    this.formData = new FormData();
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let files: FileList = inputEl.files;
    this.formData.append('uploadFile', files, files.name);
}

delete(fileName){
    this.formData.delete(fileName);
}
</code>```

Title: formData.delete() not a known property

Body:
Am using a FormData object to upload a file , i want the functionality of deleting file from FormData, but i get an error delete property does not exist on FormData object

formData.delete(fileName)

Code

upload(){
    let formData = new FormData();
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let files: FileList = inputEl.files;
    formData.append('uploadFile', files, files.name);
}

delete(fileName){
    formData.delete(fileName);
}

Body:
Variables cannot be shared between methods, so you'll need to use a property, or call the method and get a result.

The example below stores the formData in a private property and references it within each method with this.formData.

private formData: FormData;

upload() {
    this.formData = new FormData();
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let files: FileList = inputEl.files;
    this.formData.append('uploadFile', files, files.name);
}

delete(fileName){
    this.formData.delete(fileName);
}