问:
Output the index of map()
I want to output the index of each element using map().

const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
}
.it {
    border: 2px solid;
    background-color: burlywood;
    color: white;
    width: 60px;
    height: 50px;
}</code>```

```

How to output indexes of each element inside div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');?

答:
try to understand...
this ?

const arr = [ 'a','b','c'];

const div = document.querySelector('#container')

div.innerHTML = arr.map((val,i)=>`<div>${val} - ${i}</div>`).join('');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container div {
  display: inline-block;
  border: 2px solid grey;
  background-color: burlywood;
  color: white;
  width: 4em;
  height: 2.5em;
  text-align: center;
  line-height: 2.6em;
  margin: 1em;
}</code>```

```

Title: Output the index of map()

Body:
I want to output the index of each element using map().

const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');

* {
    margin: 0;
    padding: 0;
}
.it {
    border: 2px solid;
    background-color: burlywood;
    color: white;
    width: 60px;
    height: 50px;
}

How to output indexes of each element inside div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');?

Body:
try to understand...
this ?

const arr = [ 'a','b','c'];

const div = document.querySelector('#container')

div.innerHTML = arr.map((val,i)=>`<div>${val} - ${i}</div>`).join('');

#container div {
  display: inline-block;
  border: 2px solid grey;
  background-color: burlywood;
  color: white;
  width: 4em;
  height: 2.5em;
  text-align: center;
  line-height: 2.6em;
  margin: 1em;
}

<div id="container"></div>


来源: stackexchange

问:
VBA Deleting Active Sheet
I am trying to create a macro that deletes the active sheet without displaying the prompt. Which is what the code below does...This works great until the last sheet. I get the prompt no matter what. I do not want to delete the last sheet and at the same time, I don't want the error '1004' message to come up. Is there a way to change the code above to not delete my last sheet and not display the error message at the same time?</p>

```<code>Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True
</code>```

答:
If the idea is to delete the ActiveSheet and only it, this is something that will work, until there is only 1 sheet in the workbook:

```<code>Sub DeleteActiveSheet()

    If ThisWorkbook.Worksheets.Count = 1 Then
        Exit Sub
    Else
        Application.DisplayAlerts = False
        ThisWorkbook.ActiveSheet.Delete
        Application.DisplayAlerts = True
    End If

End Sub
</code>```

If the idea is to delete all worksheets, but the last, then follow this sequence:

assign a worksheet variable wksToStay from the type Worksheet and set it to the last worksheet in the workbook;

loop through all the Worksheets in the Workbook.Worksheets collection, starting from the last one;

always perform a check, whether the worksheet to be deleted wksToDelete has the same name as the wksToStay;

delete, if the name is not the same;

it will delete all the worksheets, including the hidden and the very hidden ones;

```<code>Sub DeleteAllButLast()

    Dim wksToStay As Worksheet
    Dim wksToDelete As Worksheet
    Dim i As Long

    Set wksToStay = ThisWorkbook.Worksheets(Worksheets.Count)

    For i = Worksheets.Count To 1 Step -1
        Set wksToDelete = ThisWorkbook.Worksheets(i)
        If wksToDelete.Name <> wksToStay.Name Then
            Application.DisplayAlerts = False
            wksToDelete.Delete
            Application.DisplayAlerts = True
        End If
    Next

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: VBA Deleting Active Sheet

Body:
I am trying to create a macro that deletes the active sheet without displaying the prompt. Which is what the code below does...This works great until the last sheet. I get the prompt no matter what. I do not want to delete the last sheet and at the same time, I don't want the error '1004' message to come up. Is there a way to change the code above to not delete my last sheet and not display the error message at the same time?

Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True

Body:
If the idea is to delete the ActiveSheet and only it, this is something that will work, until there is only 1 sheet in the workbook:

Sub DeleteActiveSheet()

    If ThisWorkbook.Worksheets.Count = 1 Then
        Exit Sub
    Else
        Application.DisplayAlerts = False
        ThisWorkbook.ActiveSheet.Delete
        Application.DisplayAlerts = True
    End If

End Sub

If the idea is to delete all worksheets, but the last, then follow this sequence:

assign a worksheet variable wksToStay from the type Worksheet and set it to the last worksheet in the workbook;

loop through all the Worksheets in the Workbook.Worksheets collection, starting from the last one;

always perform a check, whether the worksheet to be deleted wksToDelete has the same name as the wksToStay;

delete, if the name is not the same;

it will delete all the worksheets, including the hidden and the very hidden ones;

Sub DeleteAllButLast()

    Dim wksToStay As Worksheet
    Dim wksToDelete As Worksheet
    Dim i As Long

    Set wksToStay = ThisWorkbook.Worksheets(Worksheets.Count)

    For i = Worksheets.Count To 1 Step -1
        Set wksToDelete = ThisWorkbook.Worksheets(i)
        If wksToDelete.Name <> wksToStay.Name Then
            Application.DisplayAlerts = False
            wksToDelete.Delete
            Application.DisplayAlerts = True
        End If
    Next

End Sub


问:
MassTransit RabbitMq Sending Messages
I am not able to figure out on how to specify the Exchange and Queue in my GetSendEndpoint()) task when sending / publishing messages?

As per MassTransit documentation https://masstransit-project.com/usage/producers.html#send you can specify the exchange and queue like

```<code>GetSendEndpoint(new Uri("queue:input-queue"))
</code>```

However, I can only do one or the other?

Is there an alternative way of sending with exchange and queue specified?

I am doing this in Asp.Net Core so here are my configuration:

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
   services.AddMassTransit();

   services.AddSingleton(p => Bus.Factory.CreateUsingRabbitMq(cfg =>
   {
         cfg.Host("rabbitmq://localhost", h =>
         {
             h.Username("admin");
             h.Password("admin");
         });
   }));

   services.AddSingleton<IBus>(p => p.GetRequiredService<IBusControl>());
   services.AddSingleton<IHostedService, BusService>();
}
</code>```

And this is how send the message

```<code>var endpoint = await _bus.GetSendEndpoint(new Uri(queue:Test.Queue));
await endpoint.Send(new Message()
{
     Text = "This is a test message"
});
</code>```

As you can see I can only specify the queue name.

答:
If you specify an exchange, only the exchange is declared on the broker. The message will be sent directly to the exchange.

```<code>"exchange:your-exchange-name"
</code>```

If you specify a queue, the queue along with an exchange of the same name will be declared and the exchange will be bound to the queue. Messages will be delivered to the exchange of the same name, which will deliver them to the queue.

```<code>"queue:your-queue-name"
</code>```

If you want a different exchange and queue name, you can specify both using:

```<code>"exchange:your-exchange-name?bind=true&queue=your-queue-name"
</code>```

Or you could simplify, but it's a little confusing with two queues:

```<code>"queue:your-exchange-name&queue=your-queue-name"
</code>```

Title: MassTransit RabbitMq Sending Messages

Body:
I am not able to figure out on how to specify the Exchange and Queue in my GetSendEndpoint()) task when sending / publishing messages?

As per MassTransit documentation https://masstransit-project.com/usage/producers.html#send you can specify the exchange and queue like

GetSendEndpoint(new Uri("queue:input-queue"))

However, I can only do one or the other?

Is there an alternative way of sending with exchange and queue specified?

I am doing this in Asp.Net Core so here are my configuration:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
   services.AddMassTransit();

   services.AddSingleton(p => Bus.Factory.CreateUsingRabbitMq(cfg =>
   {
         cfg.Host("rabbitmq://localhost", h =>
         {
             h.Username("admin");
             h.Password("admin");
         });
   }));

   services.AddSingleton<IBus>(p => p.GetRequiredService<IBusControl>());
   services.AddSingleton<IHostedService, BusService>();
}

And this is how send the message

var endpoint = await _bus.GetSendEndpoint(new Uri(queue:Test.Queue));
await endpoint.Send(new Message()
{
     Text = "This is a test message"
});

As you can see I can only specify the queue name.

Body:
If you specify an exchange, only the exchange is declared on the broker. The message will be sent directly to the exchange.

"exchange:your-exchange-name"

If you specify a queue, the queue along with an exchange of the same name will be declared and the exchange will be bound to the queue. Messages will be delivered to the exchange of the same name, which will deliver them to the queue.

"queue:your-queue-name"

If you want a different exchange and queue name, you can specify both using:

"exchange:your-exchange-name?bind=true&queue=your-queue-name"

Or you could simplify, but it's a little confusing with two queues:

"queue:your-exchange-name&queue=your-queue-name"


问:
I want to group list of list
The structure of class along with sample data here.

```<code>class Student
{
    public Int32 Id { get; set; }

    public string Name { get; set; }

    public Int32 Age { get; set; }

    public List<string> subjects { get; set; }

}

class Program
{
    static void Main( string[] )
    {
        List<Student> students = new List<Student>()
        {
           new Student(){ Id=1 ,Name="Pratik", Age=24, subjects=new List<string>(){"s1", "s2"}},
           new Student(){ Id=2, Name="Ashish", Age=28, subjects=new List<string>{"s1", "s4"}},
           new Student(){ Id=3, Name="Umesh", Age=24, subjects=new List<string>(){"s1" }},
           new Student(){ Id=4, Name="Ajay", Age=28, subjects=new List<string>(){"s5", "s1"}},
           new Student(){ Id=5, Name="Vijay", Age=24, subjects=new List<string>(){"s1"}},
           new Student(){ Id=6, Name="Shital", Age=24, subjects=new List<string>(){"s2", "s3"}}
        };

        ...
    }
</code>```

I want to group subjects on Names for ex.

```<code>s2 Pratik, Shital
</code>```

答:
If you want to group on subjecs yous should flatten with a help of SelectMany before GroupBy:

```<code>   var result = students
     .SelectMany(student => student.subjects.Select(subject => new {
        subject,
        student
      }))
     .GroupBy(item => item.subject,
              item => item.student)
     .OrderBy(group => group.Key);  // Let's order by subjects' names
</code>```

Having students  grouped by subject, you can easily add Select. For instance, let's print out students' Names who attend each subject:

```<code>  string report = string.Join(Environment.NewLine, result
    .Select(group => $"{group.Key} : {string.Join(", ", group.Select(s => s.Name))}"));

  Console.Write(report);
</code>```

Outcome:

```<code>s1 : Pratik, Ashish, Umesh, Ajay, Vijay
s2 : Pratik, Shital
s3 : Shital
s4 : Ashish
s5 : Ajay
</code>```

Title: I want to group list of list

Body:
The structure of class along with sample data here.

class Student
{
    public Int32 Id { get; set; }

    public string Name { get; set; }

    public Int32 Age { get; set; }

    public List<string> subjects { get; set; }

}

class Program
{
    static void Main( string[] )
    {
        List<Student> students = new List<Student>()
        {
           new Student(){ Id=1 ,Name="Pratik", Age=24, subjects=new List<string>(){"s1", "s2"}},
           new Student(){ Id=2, Name="Ashish", Age=28, subjects=new List<string>{"s1", "s4"}},
           new Student(){ Id=3, Name="Umesh", Age=24, subjects=new List<string>(){"s1" }},
           new Student(){ Id=4, Name="Ajay", Age=28, subjects=new List<string>(){"s5", "s1"}},
           new Student(){ Id=5, Name="Vijay", Age=24, subjects=new List<string>(){"s1"}},
           new Student(){ Id=6, Name="Shital", Age=24, subjects=new List<string>(){"s2", "s3"}}
        };

        ...
    }

I want to group subjects on Names for ex.

s2 Pratik, Shital

Body:
If you want to group on subjecs yous should flatten with a help of SelectMany before GroupBy:

   var result = students
     .SelectMany(student => student.subjects.Select(subject => new {
        subject,
        student
      }))
     .GroupBy(item => item.subject,
              item => item.student)
     .OrderBy(group => group.Key);  // Let's order by subjects' names

Having students  grouped by subject, you can easily add Select. For instance, let's print out students' Names who attend each subject:

  string report = string.Join(Environment.NewLine, result
    .Select(group => $"{group.Key} : {string.Join(", ", group.Select(s => s.Name))}"));

  Console.Write(report);

Outcome:

s1 : Pratik, Ashish, Umesh, Ajay, Vijay
s2 : Pratik, Shital
s3 : Shital
s4 : Ashish
s5 : Ajay


问:
npgsql executescalar() allways returns nothing
I'm using npgsql as a nuget package in visual studio 2017 with visual basic.
Various commands do work very well but an ExecuteScalar allways returns 'nothing' although it should give a result.

The command looks like this:

```<code>   Dim ser As Integer
   Dim find = New NpgsqlCommand("SELECT serial from dbo.foreigncode WHERE code = '@code';", conn)
   Dim fcode = New NpgsqlParameter("code", NpgsqlTypes.NpgsqlDbType.Varchar)

   find.Parameters.Add(fcode)
   find.Prepare()

   fcode.Value = "XYZ"

   ser = find.ExecuteScalar()     ==>  nothing
</code>```

When the command string is copied as a value during debugging and pasted into the query tool of PGADMIN it delivers the correct result. The row is definitely there.

Different Commands executed with ExecuteNonQuery() work well, including ones performing UPDATE statements on the row in question.

When I look into the properties of the parameter fcode immediately before the ExecuteScalar it shows 'fcode.DataTypeName' caused an exception 'System.NotImplementedException'.

If I change my prepared statement to "SELECT @code" and set the value of the parameter to an arbitrary value just this value is returned. There is no access to the table taking place because the table name is not part of the SELECT in this case. If I remove the WHERE CLAUSE in the SELECT and just select one column, I would also expect that something has to be returned. But again it is nothing.

Yes there is a column named serial. It is of type bigint and can not contain NULL.
A Query shows that there is no single row that contains NULL in any column.

Latest findings:
I queried a different table where the search column and the result column happen to have the same datatype. It works, so syntax, passing of parameter, prepare etc. seems to work in principal.
The System.NotImplementedException in the DataTypeName property of the parameter occurs as well but it works anyway.
I rebuilt the index of the table in question. No change.
Still: when I copy/paste the CommandText and execute it in PGAdmin it shows the correct result.
Modifying the Command and using plain text there without parameter and without prepare still does yield nothing. The plain text CommandText was copy/pasted from PGAdmin where it was successfully executed before.
Very strange.

Reverting search column and result column also gives nothing as a result.

答:
Please try these two alternatives and post back your results:

```<code>' Alternative 1: fetch the entire row, see what's returned
Dim dr  = find.ExecuteReader()
While (dr.Read())
  Console.Write("{0}\t{1} \n", dr[0], dr[1])
End While

' Alternative 2: Check if "ExecuteScalar()" returns something other than an int
Dim result = find.ExecuteScalar()
</code>```

... and (I just noticed Honeyboy Wilson's response!) ...

Fix your syntax:

```<code>' Try this first: remove the single quotes around "@code"!
Dim find = New NpgsqlCommand("SELECT serial from dbo.foreigncode WHERE code = @code;", conn)
</code>```

Update 1

Please try this:

```<code> Dim find = New NpgsqlCommand("SELECT * from dbo.foreigncode;", conn)
</code>```

Q: Does this return anything?

```<code>Dim dr  = find.ExecuteReader()
While (dr.Read())
  Console.Write("{0}\t{1} \n", dr[0], dr[1])
End While
</code>```

Q: Does this?

```<code>Dim result = find.ExecuteScalar()
</code>```

Q: Do you happen to have a column named "serial"?  What is it's data type? Is it non-null for the row(s) with 'XYZ'?

Please update your original post with this information.

Update 2

You seem to be doing ":everything right":

You've confirmed that you can connect,

You've confirmed that non-query updates to the same table work (with npgsql),

You've confirmed that the SQL queries themselves are valid (by copying/pasting the same SQL into PGAdmin and getting valid results).

As Shay Rojansky said, "System.NotImplementedException in the DataTypeName property" is a known issue stepping through the debugger. It has nothing to do with your problem: https://github.com/npgsql/npgsql/issues/2520

SUGGESTIONS (I'm grasping at straws)::

Double-check "permissions" on your database and your table.

Consider installing a different version of npgsql.

Be sure your code is detecting any/all error returns and exceptions (it sounds like you're probably already doing this, but it never hurts to ask)

... and ...

Enable verbose logging, both client- and server-side:

https://www.npgsql.org/doc/logging.html

https://www.postgresql.org/docs/9.0/runtime-config-logging.html

... Finally ...

Q: Can you make ANY query, from ANY table, using ANY query method (ExecuteReader(), ExecuteScalar(), ... ANYTHING) from your npgsql/.Net client AT ALL?

Body:
I'm using npgsql as a nuget package in visual studio 2017 with visual basic.
Various commands do work very well but an ExecuteScalar allways returns 'nothing' although it should give a result.

The command looks like this:

   Dim ser As Integer
   Dim find = New NpgsqlCommand("SELECT serial from dbo.foreigncode WHERE code = '@code';", conn)
   Dim fcode = New NpgsqlParameter("code", NpgsqlTypes.NpgsqlDbType.Varchar)

   find.Parameters.Add(fcode)
   find.Prepare()

   fcode.Value = "XYZ"

   ser = find.ExecuteScalar()     ==>  nothing

When the command string is copied as a value during debugging and pasted into the query tool of PGADMIN it delivers the correct result. The row is definitely there.

Different Commands executed with ExecuteNonQuery() work well, including ones performing UPDATE statements on the row in question.

When I look into the properties of the parameter fcode immediately before the ExecuteScalar it shows 'fcode.DataTypeName' caused an exception 'System.NotImplementedException'.

If I change my prepared statement to "SELECT @code" and set the value of the parameter to an arbitrary value just this value is returned. There is no access to the table taking place because the table name is not part of the SELECT in this case. If I remove the WHERE CLAUSE in the SELECT and just select one column, I would also expect that something has to be returned. But again it is nothing.

Yes there is a column named serial. It is of type bigint and can not contain NULL.
A Query shows that there is no single row that contains NULL in any column.

Latest findings:
I queried a different table where the search column and the result column happen to have the same datatype. It works, so syntax, passing of parameter, prepare etc. seems to work in principal.
The System.NotImplementedException in the DataTypeName property of the parameter occurs as well but it works anyway.
I rebuilt the index of the table in question. No change.
Still: when I copy/paste the CommandText and execute it in PGAdmin it shows the correct result.
Modifying the Command and using plain text there without parameter and without prepare still does yield nothing. The plain text CommandText was copy/pasted from PGAdmin where it was successfully executed before.
Very strange.

Reverting search column and result column also gives nothing as a result.

Body:
Please try these two alternatives and post back your results:

' Alternative 1: fetch the entire row, see what's returned
Dim dr  = find.ExecuteReader()
While (dr.Read())
  Console.Write("{0}\t{1} \n", dr[0], dr[1])
End While

' Alternative 2: Check if "ExecuteScalar()" returns something other than an int
Dim result = find.ExecuteScalar()

... and (I just noticed Honeyboy Wilson's response!) ...

Fix your syntax:

' Try this first: remove the single quotes around "@code"!
Dim find = New NpgsqlCommand("SELECT serial from dbo.foreigncode WHERE code = @code;", conn)

Update 1

Please try this:

 Dim find = New NpgsqlCommand("SELECT * from dbo.foreigncode;", conn)

Q: Does this return anything?

Dim dr  = find.ExecuteReader()
While (dr.Read())
  Console.Write("{0}\t{1} \n", dr[0], dr[1])
End While

Q: Does this?

Dim result = find.ExecuteScalar()

Q: Do you happen to have a column named "serial"?  What is it's data type? Is it non-null for the row(s) with 'XYZ'?

Please update your original post with this information.

Update 2

You seem to be doing ":everything right":

You've confirmed that you can connect,

You've confirmed that non-query updates to the same table work (with npgsql),

You've confirmed that the SQL queries themselves are valid (by copying/pasting the same SQL into PGAdmin and getting valid results).

As Shay Rojansky said, "System.NotImplementedException in the DataTypeName property" is a known issue stepping through the debugger. It has nothing to do with your problem: https://github.com/npgsql/npgsql/issues/2520

SUGGESTIONS (I'm grasping at straws)::

Double-check "permissions" on your database and your table.

Consider installing a different version of npgsql.

Be sure your code is detecting any/all error returns and exceptions (it sounds like you're probably already doing this, but it never hurts to ask)

... and ...

Enable verbose logging, both client- and server-side:

https://www.npgsql.org/doc/logging.html

https://www.postgresql.org/docs/9.0/runtime-config-logging.html

... Finally ...

Q: Can you make ANY query, from ANY table, using ANY query method (ExecuteReader(), ExecuteScalar(), ... ANYTHING) from your npgsql/.Net client AT ALL?


问:
How would you programmatically test a file for viruses?
I want to programmatically test a file for viruses.

I'm aware of this thread, which didn't get a satisfactory answer in my opinion, but I'm not looking for an API here. Any kind of workaround to make it possible to test a file would be fine.

Of course, an API would probably be the best solution (I'm using .net on a Windows platform), but maybe it's possible to drop the file in the folder, and to then check whether I can still open it or if it's been quarantined by the antivirus software.

Has someone run into the same sort of situation?

答:
Check out ClamAV.

Clam AntiVirus is an open source (GPL) anti-virus toolkit for UNIX, designed especially for e-mail scanning on mail gateways.

OwnerDisplayName: Brann

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: Aaron Digulla


答:
This should do what you're looking for:</p>

```<code><table>
  <tr>
    <td rowspan="2">A</td>
    <td rowspan="2">B</td>
    <td>C</td>
    <td>D</td>
  </tr>
  <tr>
    <td>E</td>
    <td>F</td>
  </tr>
</table>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do I create this table?

Body:
----------------------------
|     |       |  C   |  D  |
|  A  |   B   |------+-----|
|     |       | E    | F   |
----------------------------

Both A and B need a ROWSPAN of 2. What's the HTML for that?

Body:
This should do what you're looking for:

<table>
  <tr>
    <td rowspan="2">A</td>
    <td rowspan="2">B</td>
    <td>C</td>
    <td>D</td>
  </tr>
  <tr>
    <td>E</td>
    <td>F</td>
  </tr>
</table>


问:
Cart empty after add to cart method
I am working on one functionality for WC variable product. It will be ticket with various "levels", for each level another price. User should pick number of tickets he wants, after that form should be created in which he can add Name, Address and Ticket Level for each ticket(row). All this data should be after that sent to cart and saved to order.

EDIT 2

Hello guys, again.

I spent some more time on this and went further.

I almost did what i wanted:

User can choose number of tickets

User can fill additional info for each ticket (name, address, bio, ticket level)

All of these rows will be added to cart

All of these data are displayed in cart and checkout

All of these data will be send to order/email

Now i found problem (sure, there are maybe more problems). But, i was doing it the whole time as logged user in same windows of browser.
After that i realized that when i am using inkognito mode, or another browser with no session or cookies stored for this site, after adding items to cart, cart is empty.

When i tried to first add some other item that is using regular WC add to cart button it worked, after that i can add my tickets without problem.

But when i try to add tickets first, cart is empty. In my main browser as logged user i have no problem.

I did some research on this, but i was just trying. I dont really understand the problem so i am wasting time again.

If someone can help me or guide me towards solution i would be glad.

Thank you for your time.

Below is code from my plugin:

```<code>if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

    if ( ! class_exists( 'UberMike' ) ) {

        class UberMike{
            private static $farba_vlastnost = 'attribute_pa_level-bezca';
            private static $attributes_values = array();

            public function __construct() {
                self::$farba_vlastnost = self::$farba_vlastnost;
                self::$attributes_values = self::$attributes_values;
                // called only after woocommerce has finished loading
                add_action( 'woocommerce_init', array( &$this, 'woocommerce_loaded' ) );
                // called after all plugins have loaded
                add_action( 'plugins_loaded', array( &$this, 'plugins_loaded' ) );
                //enqueue scripts and css style
                add_action("wp_loaded", array( &$this, "enqueue_scripts") );
                //add custom actions
                //remove WC action completely
                add_action('woocommerce_single_product_summary', function () {
                    remove_action('woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30);
                }, -1000);
                //add custom add to cart
                add_action( 'woocommerce_variable_add_to_cart', array( $this, 'add_to_cart'), 30 );
                //create collapsible section input number and button
                add_action( 'woocommerce_variable_add_to_cart', array( $this, 'createCollapsibleSection') );
                //hide collapsible section in header
                add_action('wp_footer', array( $this, 'collapsibleSectionHeader') );
                //boot session
                // add_action('wp_head', array( $this, 'hook_cookie') );
                add_action('wp_head', array( $this, 'boot_session') );
                //display meta data to each item in cart anch checkout
                add_filter( 'woocommerce_get_item_data', array( $this, 'ubermike_render_meta_on_cart_and_checkout'), 20, 2 );
                //display grouped custom fields in checkout and order notes
                add_action( 'woocommerce_checkout_create_order', array( $this, 'my_custom_checkout_field') );
                add_action( 'woocommerce_after_order_notes', array( $this, 'my_custom_checkout_field') );
                //display fields in order and email
                add_action('woocommerce_checkout_create_order_line_item', array( $this, 'save_custom_order_item_meta_data'), 10, 4 );
            }
            /**
         * Take care of anything that needs woocommerce to be loaded.
         * For instance, if you need access to the $woocommerce global
         */
            public function woocommerce_loaded() {
                // ...
            }
            /**
             * Take care of anything that needs all plugins to be loaded
             */
            public function plugins_loaded() {
                // ...
            }
            //enqueue JS scripts and CSS style
            public function enqueue_scripts() {
                wp_register_style( 'ubermike_css', plugins_url('assets/ubermike.css', __FILE__) );
                wp_enqueue_style('ubermike_css');

                wp_register_script( 'ubermike_js', plugins_url('assets/ubermike.js',__FILE__ ), array( 'jquery' ));
                wp_enqueue_script('ubermike_js');
            }

            //add to cart replacement
            public function add_to_cart($allsets){
                global $product, $post, $woocommerce;

                //check product category
                $is_ticket = false;
                $terms = get_the_terms( $post->ID, 'product_cat' );
                foreach ($terms as $t){
                    if ($t->slug=='ticket'){
                        $is_ticket = true;
                        break;
                    }
                }

                //if the category is other than ticket, basic WC single variable product will be displayed on frontend
                if (!method_exists($product,'get_variation_attributes') || !$is_ticket) {
                    wp_enqueue_script( 'wc-add-to-cart-variation' );

                    wc_get_template( 'single-product/add-to-cart/variable.php', array(
                        'available_variations'  => $product->get_available_variations(),
                        'attributes'            => $product->get_variation_attributes(),
                        'selected_attributes'   => $product->get_default_attributes()
                        ) );
                    return;
                }

                //get product variations
                $variations = $product->get_available_variations();
                //storing variables of product and each variation of this product
                //product ID and quantity (default 1 piece for row)
                $custom_product_id = $product->get_id();
                $custom_product_quantity = 1;
                //storing variations data to variables with index
                $index_n = 1;
                ?>
                <div id="hidden-variables-container">
                <?php
                foreach($variations as $var) {
                    $product_variation = new WC_Product_Variation($var['variation_id']);
                    //here i used ->id before
                    // $somevar = $this->_fillAttributeValues($product, $product_variation->get_id());
                    $this->_fillAttributeValues($product, $product_variation->id);
                    //variation attribute name json encode
                    $attr_text[$index_n] = json_encode($var['attributes']);
                    //variation name to display in frontend
                    $variation_name_to_display[$index_n] = self::_getAttributeValue($var['attributes']);
                    //variation attribute name json encode htmlspecialchars
                    $variation_name_full[$index_n] = htmlspecialchars($attr_text[$index_n]);
                    //variation id
                    $variation_id[$index_n] = $var['variation_id'];

                    ?>
                        <!-- Variables to frontend for JS use -->
                        <div class="hidden-variable <?php echo $index_n; ?>">
                        <span class="um_variation_name_frontend <?php echo $index_n; ?>"><?php echo $variation_name_to_display[$index_n]; ?></span>
                        <span class="um_variation_attribute_name <?php echo $index_n; ?>"><?php echo  $variation_name_full[$index_n]; ?></span>
                        <span class="um_variation_id <?php echo $index_n; ?>"><?php echo  $variation_id[$index_n];?></span>
                    </div>
                    <?php
                    $index_n++;
                }
                ?>
                </div>
                <?php
            }

            //get values of attributes
            private function _getAttributeValue($get_attributes){
                $text = '';
                foreach ($get_attributes as $name=>$attribute){
                    if ($name==self::$farba_vlastnost){
                        if (isset(self::$attributes_values['pa_level-bezca'][$attribute])) $text = self::$attributes_values['pa_level-bezca'][$attribute];
                        break;
                    }
                }
                if (empty($text)){
                    $text = [];
                    foreach ($get_attributes as $name=>$attribute){
                        if (isset(self::$attributes_values[substr($name, strlen('attribute_'))][$attribute])) $text[] = self::$attributes_values[substr($name, strlen('attribute_'))][$attribute];
                    }
                    $text = join(', ', $text);
                }
                return $text;
            }

            //fill attribute values to display name in frontend
            private function _fillAttributeValues($product, $product_variation_id){
                $attributes = $product->get_attributes();
                foreach ($attributes as $attribute){
                    if ($attribute['is_taxonomy']){
                        $post_terms = wp_get_post_terms( $product_variation_id, $attribute[ 'name' ] );
                        foreach ( $post_terms as $term ) {
                            self::$attributes_values[$term->taxonomy][$term->slug] = esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) );
                        }
                    }
                }
            }

        function createCollapsibleSection(){
            global $product, $post, $woocommerce;
            //check if product term is ticket
            $is_ticket = false;
            $terms = get_the_terms( $post->ID, 'product_cat' );
            foreach ($terms as $t){
                if ($t->slug=='ticket'){
                    $is_textil = true;
                } else{
                }
            }
            ?>

            <!-- Input type number for JS created fields -->
            <div class="quantity">
                <label class="tickets-quantity" for="number-of-tickets">Vyberte počet lístkov</label>
                <input type="number" id="number-of-tickets" class="" step="1" min="1" max="" name="number-of-tickets" value="1" title="Počet" size="4" inputmode="numeric">
            </div>
            <!-- This span opens hidden modal with input rows -->
            <span class="open-modal"> Vyplniť údaje  </span>
                <?php
            }

            function collapsibleSectionHeader(){
                global $product, $post, $woocommerce;
                ?>
                            <!-- Form with input fields and select for variation -->
                            <div id="clone-wrapper-bigbranding" class="collapsible-wrapper-bigbranding hidenx">
                                <div class="uber-modal">
                                <span class="close-modal">Zatvoriť</span>
                                <form id="form-motherboard" action="#" method="post">
                                    <input type="hidden" name="product_id" value="<?php $product->id; ?>">
                                    <input type="hidden" name="ubermike" value="1">
                                <input class="do-kosika" type="submit" name="submit" value="Pridať do košíka" />
                                <?php
                                        if (isset($_POST['ubermike'])){
                                            $product_id = absint($_POST['product_id']);
                                            // This loops through rows and adds products to cart
                                            $cnt = count($_POST['ticketLevel']);
                                            $quantity_total = 0;

                                                for($i=0;$i<$cnt;$i++){
                                                        $cats = explode("|", $_POST['ticketLevel'][$i]);
                                                        $selected_val = $cats[0]; // cat_id
                                                        $selected_level = $cats[1]; // cat_name
                                                        $customer_name = $_POST['name'][$i];
                                                        $customer_address = $_POST['address'][$i];
                                                        $customer_bio = $_POST['bio'][$i];
                                                        $custom_data = array(); // Initializing

                                                        $custom_data['custom_data']['name'] = array(
                                                                'label' => 'Meno',
                                                                'value' => $customer_name
                                                        );
                                                        $custom_data['custom_data']['address'] = array(
                                                                'label' => 'Adresa',
                                                                'value' => $customer_address
                                                        );
                                                        $custom_data['custom_data']['bio'] = array(
                                                                'label' => 'Bio',
                                                                'value' => $customer_bio
                                                        );
                                                        $custom_data['custom_data']['level'] = array(
                                                                'label' => 'Level',
                                                                'value' => $selected_level
                                                        );

                                                        $quantity = 1;

                                                        WC()->cart->add_to_cart( $product_id, $quantity, $selected_val, array(), $custom_data );

                                                        do_action( 'woocommerce_set_cart_cookies', TRUE );

                                                        $quantity_total += $quantity;

                                                }

                                                if ($quantity_total) wc_add_to_cart_message( array( $product_id => $quantity_total ), true );
                                        }
                                 ?>
                                </form>
                                    </div>
                                </div>
                                <?
            }

            function ubermike_render_meta_on_cart_and_checkout( $cart_data, $cart_item ){
                    $custom_items = array();

                    if( !empty( $cart_data ) )
                            $custom_items = $cart_data;

                    if( isset( $cart_item['custom_data'] ) ) {
                            foreach( $cart_item['custom_data'] as $key => $custom_data ){
                                    if( $key != 'key' ){
                                            $custom_items[] = array(
                                                    'name' => $custom_data['label'],
                                                    'value' => $custom_data['value'],
                                            );
                                    }
                            }
                    }
                    return $custom_items;
            }

            function my_custom_checkout_field( $checkout ) {
                    global $woocommerce;

                    echo '<div id="my_custom_checkout_field"><h2>' . __('Údaje objednávky') . '</h2>';
                    $indexing = 1;
                    foreach ( $woocommerce->cart->get_cart() as $cart_item ) {
                            if( isset($cart_item['custom_data']) ) {

                                echo '<div class="uber-ticket-wrapper">';
                                echo '<div class="uber-ticket">Ticket ' . $indexing . ' </div>';
                                    foreach( $cart_item['custom_data'] as $key => $custom_data ){
                                            if( $key != 'key' ){
                                                            echo $custom_data['label'];
                                                            echo("<br>");
                                                            echo $custom_data['value'];
                                                            echo("<br>");
                                            }
                                    }
                                    echo "</div>";
                                    $indexing++;
                            }
                    }
                    echo '</div>';
            }

            // Save cart item custom data as order item meta data and display it everywhere in Orders and email notifications
            function save_custom_order_item_meta_data( $item, $cart_item_key, $values, $order ) {
                if (isset($values['custom_data'])) {
                    foreach( $values['custom_data'] as $key => $custom_data ){
                            if( $key != 'key' ){
                                $item->update_meta_data( $custom_data['label'], $custom_data['value'] );
                            }
                    }
                }
            }

            function boot_session() {
                session_start();
            }
        }
        //instantiate plugin class and add it to the set of globals
        $GLOBALS['ubermike'] = new UberMike();
    }
}
</code>```

Here is picture that shows single-product and then form in modal

答:
Solved with this answer:
https://stackoverflow.com/a/53422060/12897376

You need to initiate Woocommerce User session when it's not logged in. So you will use the following:

```<code>add_action( 'woocommerce_init', 'force_non_logged_user_wc_session' );
function force_non_logged_user_wc_session(){
    if( is_user_logged_in() || is_admin() )
       return;

    if ( ! WC()->session->has_session() )
       WC()->session->set_customer_session_cookie( true );
}
</code>```

Many thanks.

Title: Cart empty after add to cart method

Body:
I am working on one functionality for WC variable product. It will be ticket with various "levels", for each level another price. User should pick number of tickets he wants, after that form should be created in which he can add Name, Address and Ticket Level for each ticket(row). All this data should be after that sent to cart and saved to order.

EDIT 2

Hello guys, again.

I spent some more time on this and went further.

I almost did what i wanted:

User can choose number of tickets

User can fill additional info for each ticket (name, address, bio, ticket level)

All of these rows will be added to cart

All of these data are displayed in cart and checkout

All of these data will be send to order/email

Now i found problem (sure, there are maybe more problems). But, i was doing it the whole time as logged user in same windows of browser.
After that i realized that when i am using inkognito mode, or another browser with no session or cookies stored for this site, after adding items to cart, cart is empty.

When i tried to first add some other item that is using regular WC add to cart button it worked, after that i can add my tickets without problem.

But when i try to add tickets first, cart is empty. In my main browser as logged user i have no problem.

I did some research on this, but i was just trying. I dont really understand the problem so i am wasting time again.

If someone can help me or guide me towards solution i would be glad.

Thank you for your time.

Below is code from my plugin:

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

    if ( ! class_exists( 'UberMike' ) ) {

        class UberMike{
            private static $farba_vlastnost = 'attribute_pa_level-bezca';
            private static $attributes_values = array();

            public function __construct() {
                self::$farba_vlastnost = self::$farba_vlastnost;
                self::$attributes_values = self::$attributes_values;
                // called only after woocommerce has finished loading
                add_action( 'woocommerce_init', array( &$this, 'woocommerce_loaded' ) );
                // called after all plugins have loaded
                add_action( 'plugins_loaded', array( &$this, 'plugins_loaded' ) );
                //enqueue scripts and css style
                add_action("wp_loaded", array( &$this, "enqueue_scripts") );
                //add custom actions
                //remove WC action completely
                add_action('woocommerce_single_product_summary', function () {
                    remove_action('woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30);
                }, -1000);
                //add custom add to cart
                add_action( 'woocommerce_variable_add_to_cart', array( $this, 'add_to_cart'), 30 );
                //create collapsible section input number and button
                add_action( 'woocommerce_variable_add_to_cart', array( $this, 'createCollapsibleSection') );
                //hide collapsible section in header
                add_action('wp_footer', array( $this, 'collapsibleSectionHeader') );
                //boot session
                // add_action('wp_head', array( $this, 'hook_cookie') );
                add_action('wp_head', array( $this, 'boot_session') );
                //display meta data to each item in cart anch checkout
                add_filter( 'woocommerce_get_item_data', array( $this, 'ubermike_render_meta_on_cart_and_checkout'), 20, 2 );
                //display grouped custom fields in checkout and order notes
                add_action( 'woocommerce_checkout_create_order', array( $this, 'my_custom_checkout_field') );
                add_action( 'woocommerce_after_order_notes', array( $this, 'my_custom_checkout_field') );
                //display fields in order and email
                add_action('woocommerce_checkout_create_order_line_item', array( $this, 'save_custom_order_item_meta_data'), 10, 4 );
            }
            /**
         * Take care of anything that needs woocommerce to be loaded.
         * For instance, if you need access to the $woocommerce global
         */
            public function woocommerce_loaded() {
                // ...
            }
            /**
             * Take care of anything that needs all plugins to be loaded
             */
            public function plugins_loaded() {
                // ...
            }
            //enqueue JS scripts and CSS style
            public function enqueue_scripts() {
                wp_register_style( 'ubermike_css', plugins_url('assets/ubermike.css', __FILE__) );
                wp_enqueue_style('ubermike_css');

                wp_register_script( 'ubermike_js', plugins_url('assets/ubermike.js',__FILE__ ), array( 'jquery' ));
                wp_enqueue_script('ubermike_js');
            }

            //add to cart replacement
            public function add_to_cart($allsets){
                global $product, $post, $woocommerce;

                //check product category
                $is_ticket = false;
                $terms = get_the_terms( $post->ID, 'product_cat' );
                foreach ($terms as $t){
                    if ($t->slug=='ticket'){
                        $is_ticket = true;
                        break;
                    }
                }

                //if the category is other than ticket, basic WC single variable product will be displayed on frontend
                if (!method_exists($product,'get_variation_attributes') || !$is_ticket) {
                    wp_enqueue_script( 'wc-add-to-cart-variation' );

                    wc_get_template( 'single-product/add-to-cart/variable.php', array(
                        'available_variations'  => $product->get_available_variations(),
                        'attributes'            => $product->get_variation_attributes(),
                        'selected_attributes'   => $product->get_default_attributes()
                        ) );
                    return;
                }

                //get product variations
                $variations = $product->get_available_variations();
                //storing variables of product and each variation of this product
                //product ID and quantity (default 1 piece for row)
                $custom_product_id = $product->get_id();
                $custom_product_quantity = 1;
                //storing variations data to variables with index
                $index_n = 1;
                ?>

                <?php
                foreach($variations as $var) {
                    $product_variation = new WC_Product_Variation($var['variation_id']);
                    //here i used ->id before
                    // $somevar = $this->_fillAttributeValues($product, $product_variation->get_id());
                    $this->_fillAttributeValues($product, $product_variation->id);
                    //variation attribute name json encode
                    $attr_text[$index_n] = json_encode($var['attributes']);
                    //variation name to display in frontend
                    $variation_name_to_display[$index_n] = self::_getAttributeValue($var['attributes']);
                    //variation attribute name json encode htmlspecialchars
                    $variation_name_full[$index_n] = htmlspecialchars($attr_text[$index_n]);
                    //variation id
                    $variation_id[$index_n] = $var['variation_id'];

                    ?>

                        <div class="hidden-variable <?php echo $index_n; ?>">
                        <span class="um_variation_name_frontend <?php echo $index_n; ?>"><?php echo $variation_name_to_display[$index_n]; ?>
                        <span class="um_variation_attribute_name <?php echo $index_n; ?>"><?php echo  $variation_name_full[$index_n]; ?>
                        <span class="um_variation_id <?php echo $index_n; ?>"><?php echo  $variation_id[$index_n];?>

                    <?php
                    $index_n++;
                }
                ?>

                <?php
            }

            //get values of attributes
            private function _getAttributeValue($get_attributes){
                $text = '';
                foreach ($get_attributes as $name=>$attribute){
                    if ($name==self::$farba_vlastnost){
                        if (isset(self::$attributes_values['pa_level-bezca'][$attribute])) $text = self::$attributes_values['pa_level-bezca'][$attribute];
                        break;
                    }
                }
                if (empty($text)){
                    $text = [];
                    foreach ($get_attributes as $name=>$attribute){
                        if (isset(self::$attributes_values[substr($name, strlen('attribute_'))][$attribute])) $text[] = self::$attributes_values[substr($name, strlen('attribute_'))][$attribute];
                    }
                    $text = join(', ', $text);
                }
                return $text;
            }

            //fill attribute values to display name in frontend
            private function _fillAttributeValues($product, $product_variation_id){
                $attributes = $product->get_attributes();
                foreach ($attributes as $attribute){
                    if ($attribute['is_taxonomy']){
                        $post_terms = wp_get_post_terms( $product_variation_id, $attribute[ 'name' ] );
                        foreach ( $post_terms as $term ) {
                            self::$attributes_values[$term->taxonomy][$term->slug] = esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) );
                        }
                    }
                }
            }

        function createCollapsibleSection(){
            global $product, $post, $woocommerce;
            //check if product term is ticket
            $is_ticket = false;
            $terms = get_the_terms( $post->ID, 'product_cat' );
            foreach ($terms as $t){
                if ($t->slug=='ticket'){
                    $is_textil = true;
                } else{
                }
            }
            ?>

                Vyberte počet lístkov
                <input type="number" id="number-of-tickets" class="" step="1" min="1" max="" name="number-of-tickets" value="1" title="Počet" size="4" inputmode="numeric">

             Vyplniť údaje
                <?php
            }

            function collapsibleSectionHeader(){
                global $product, $post, $woocommerce;
                ?>

                                Zatvoriť
                                <form id="form-motherboard" action="#" method="post">
                                    <input type="hidden" name="product_id" value="<?php $product->id; ?>">
                                    <input type="hidden" name="ubermike" value="1">
                                <input class="do-kosika" type="submit" name="submit" value="Pridať do košíka" />
                                <?php
                                        if (isset($_POST['ubermike'])){
                                            $product_id = absint($_POST['product_id']);
                                            // This loops through rows and adds products to cart
                                            $cnt = count($_POST['ticketLevel']);
                                            $quantity_total = 0;

                                                for($i=0;$i<$cnt;$i++){
                                                        $cats = explode("|", $_POST['ticketLevel'][$i]);
                                                        $selected_val = $cats[0]; // cat_id
                                                        $selected_level = $cats[1]; // cat_name
                                                        $customer_name = $_POST['name'][$i];
                                                        $customer_address = $_POST['address'][$i];
                                                        $customer_bio = $_POST['bio'][$i];
                                                        $custom_data = array(); // Initializing

                                                        $custom_data['custom_data']['name'] = array(
                                                                'label' => 'Meno',
                                                                'value' => $customer_name
                                                        );
                                                        $custom_data['custom_data']['address'] = array(
                                                                'label' => 'Adresa',
                                                                'value' => $customer_address
                                                        );
                                                        $custom_data['custom_data']['bio'] = array(
                                                                'label' => 'Bio',
                                                                'value' => $customer_bio
                                                        );
                                                        $custom_data['custom_data']['level'] = array(
                                                                'label' => 'Level',
                                                                'value' => $selected_level
                                                        );

                                                        $quantity = 1;

                                                        WC()->cart->add_to_cart( $product_id, $quantity, $selected_val, array(), $custom_data );

                                                        do_action( 'woocommerce_set_cart_cookies', TRUE );

                                                        $quantity_total += $quantity;

                                                }

                                                if ($quantity_total) wc_add_to_cart_message( array( $product_id => $quantity_total ), true );
                                        }
                                 ?>
                                </form>

                                <?
            }

            function ubermike_render_meta_on_cart_and_checkout( $cart_data, $cart_item ){
                    $custom_items = array();

                    if( !empty( $cart_data ) )
                            $custom_items = $cart_data;

                    if( isset( $cart_item['custom_data'] ) ) {
                            foreach( $cart_item['custom_data'] as $key => $custom_data ){
                                    if( $key != 'key' ){
                                            $custom_items[] = array(
                                                    'name' => $custom_data['label'],
                                                    'value' => $custom_data['value'],
                                            );
                                    }
                            }
                    }
                    return $custom_items;
            }

            function my_custom_checkout_field( $checkout ) {
                    global $woocommerce;

                    echo '

' . __('Údaje objednávky') . '
';
                    $indexing = 1;
                    foreach ( $woocommerce->cart->get_cart() as $cart_item ) {
                            if( isset($cart_item['custom_data']) ) {

                                echo '
';
                                echo '
Ticket ' . $indexing . '
';
                                    foreach( $cart_item['custom_data'] as $key => $custom_data ){
                                            if( $key != 'key' ){
                                                            echo $custom_data['label'];
                                                            echo("
");
                                                            echo $custom_data['value'];
                                                            echo("
");
                                            }
                                    }
                                    echo "
";
                                    $indexing++;
                            }
                    }
                    echo '
';
            }

            // Save cart item custom data as order item meta data and display it everywhere in Orders and email notifications
            function save_custom_order_item_meta_data( $item, $cart_item_key, $values, $order ) {
                if (isset($values['custom_data'])) {
                    foreach( $values['custom_data'] as $key => $custom_data ){
                            if( $key != 'key' ){
                                $item->update_meta_data( $custom_data['label'], $custom_data['value'] );
                            }
                    }
                }
            }

            function boot_session() {
                session_start();
            }
        }
        //instantiate plugin class and add it to the set of globals
        $GLOBALS['ubermike'] = new UberMike();
    }
}

Here is picture that shows single-product and then form in modal

Body:
Solved with this answer:
https://stackoverflow.com/a/53422060/12897376

You need to initiate Woocommerce User session when it's not logged in. So you will use the following:

add_action( 'woocommerce_init', 'force_non_logged_user_wc_session' );
function force_non_logged_user_wc_session(){
    if( is_user_logged_in() || is_admin() )
       return;

    if ( ! WC()->session->has_session() )
       WC()->session->set_customer_session_cookie( true );
}

Many thanks.


问:
Hibernate error: Invocation of init method failed; nested exception is org.hibernate.boot.archive.spi.ArchiveException: Could not build ClassFile
I'm trying to deploy a backend app with a REST API that I have created. Program runs perfectly fine when I'm running from my console however when I try to create a jar file and execute it. I am running into a lot of errors when I'm trying to run a jar file that I have created from my maven project, however I can't execute the jar file due to this Hibernate error. I've tried adding dependencies to my pom.xml file but nothing seems to be working.

I removed duplicated files in the Hibernate-core folder and some errors have been fixed but I still get an archive exception error.
error message

```<code>    log4j: Adding appender named [consoleAppender] to category [root].
    18 Jul 2019 12:05:21  INFO Version - HV000001: Hibernate Validator 6.0.17.Final

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.1.6.RELEASE)

    18 Jul 2019 12:05:22  INFO MainRun - Starting MainRun v4.0.0 on LAPTOP-SBPKOCKV with PID 2744 (C:\Internship2019\examples-master\ctakes-web-client\target\ctakes-web-client.jar started by user in C:\Internship2019\examples-master\ctakes-web-client\target)
    18 Jul 2019 12:05:22  INFO MainRun - No active profile set, falling back to default profiles: default
    18 Jul 2019 12:05:23  INFO TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
    Jul 18, 2019 12:05:23 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service [Tomcat]
    Jul 18, 2019 12:05:23 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet engine: [Apache Tomcat/9.0.21]
    Jul 18, 2019 12:05:24 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring embedded WebApplicationContext
    18 Jul 2019 12:05:24  INFO ContextLoader - Root WebApplicationContext: initialization completed in 1781 ms
    18 Jul 2019 12:05:24  INFO EmbeddedDatabaseFactory - Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
    18 Jul 2019 12:05:24  INFO LogHelper - HHH000204: Processing PersistenceUnitInfo [
            name: default
            ...]
    18 Jul 2019 12:05:24  INFO Version - HHH000412: Hibernate Core {5.3.10.Final}
    18 Jul 2019 12:05:24  INFO Environment - HHH000206: hibernate.properties not found
    18 Jul 2019 12:05:24  INFO Version - HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
    18 Jul 2019 12:05:24  WARN AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.boot.archive.spi.ArchiveException: Could not build ClassFile
    18 Jul 2019 12:05:24  INFO EmbeddedDatabaseFactory - Shutting down embedded database: url='jdbc:hsqldb:mem:testdb'
    Jul 18, 2019 12:05:24 PM org.apache.catalina.core.StandardService stopInternal
    INFO: Stopping service [Tomcat]
    18 Jul 2019 12:05:24  INFO ConditionEvaluationReportLoggingListener -

    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    18 Jul 2019 12:05:24 ERROR SpringApplication - Application run failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.boot.archive.spi.ArchiveException: Could not build ClassFile
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
</code>```

```<code><repository>
    <id>apache.snapshots</id>
    <name>Apache Development Snapshot Repository</name>
    <url>https://repository.apache.org/content/repositories/snapshots/</url>
    <releases>
        <enabled>false</enabled>
    </releases>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>
</repositories>

    <dependencies>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.2.10.v20150310</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>ctakes-web-client</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-Xlint</compilerArgument>
                </configuration>
            </plugin>
            <plugin>
                <!-- Build an executable JAR -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>org.apache.ctakes.web.client.servlet.MainRun</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

```<code>
</code>```

答:
Check your dependency tree (make sure you use verbose command to show duplicates).

```<code>mvn dependency:tree -Dverbose
</code>```

then, exclude any javassist that is not inside hibernate. For instance:

```<code><dependency>
<groupId>xxx.xxxxxxxx</groupId>
<artifactId>xxxxxxx</artifactId>
<version>${version}</version>
<exclusions>
    <exclusion>
        <artifactId>javassist</artifactId>
        <groupId>org.javassist</groupId>
    </exclusion>
</exclusions>
</code>```

Where:
"xxx.xxxxxxxx" from groupId that you identified on dependency tree.
"xxxxxxx" from artifactId that you identified on dependency tree.

Body:
I'm trying to deploy a backend app with a REST API that I have created. Program runs perfectly fine when I'm running from my console however when I try to create a jar file and execute it. I am running into a lot of errors when I'm trying to run a jar file that I have created from my maven project, however I can't execute the jar file due to this Hibernate error. I've tried adding dependencies to my pom.xml file but nothing seems to be working.

I removed duplicated files in the Hibernate-core folder and some errors have been fixed but I still get an archive exception error.
error message

    log4j: Adding appender named [consoleAppender] to category [root].
    18 Jul 2019 12:05:21  INFO Version - HV000001: Hibernate Validator 6.0.17.Final

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.1.6.RELEASE)

    18 Jul 2019 12:05:22  INFO MainRun - Starting MainRun v4.0.0 on LAPTOP-SBPKOCKV with PID 2744 (C:\Internship2019\examples-master\ctakes-web-client\target\ctakes-web-client.jar started by user in C:\Internship2019\examples-master\ctakes-web-client\target)
    18 Jul 2019 12:05:22  INFO MainRun - No active profile set, falling back to default profiles: default
    18 Jul 2019 12:05:23  INFO TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
    Jul 18, 2019 12:05:23 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service [Tomcat]
    Jul 18, 2019 12:05:23 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet engine: [Apache Tomcat/9.0.21]
    Jul 18, 2019 12:05:24 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring embedded WebApplicationContext
    18 Jul 2019 12:05:24  INFO ContextLoader - Root WebApplicationContext: initialization completed in 1781 ms
    18 Jul 2019 12:05:24  INFO EmbeddedDatabaseFactory - Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
    18 Jul 2019 12:05:24  INFO LogHelper - HHH000204: Processing PersistenceUnitInfo [
            name: default
            ...]
    18 Jul 2019 12:05:24  INFO Version - HHH000412: Hibernate Core {5.3.10.Final}
    18 Jul 2019 12:05:24  INFO Environment - HHH000206: hibernate.properties not found
    18 Jul 2019 12:05:24  INFO Version - HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
    18 Jul 2019 12:05:24  WARN AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.boot.archive.spi.ArchiveException: Could not build ClassFile
    18 Jul 2019 12:05:24  INFO EmbeddedDatabaseFactory - Shutting down embedded database: url='jdbc:hsqldb:mem:testdb'
    Jul 18, 2019 12:05:24 PM org.apache.catalina.core.StandardService stopInternal
    INFO: Stopping service [Tomcat]
    18 Jul 2019 12:05:24  INFO ConditionEvaluationReportLoggingListener -

    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    18 Jul 2019 12:05:24 ERROR SpringApplication - Application run failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.boot.archive.spi.ArchiveException: Could not build ClassFile
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)

<repository>
    <id>apache.snapshots</id>
    <name>Apache Development Snapshot Repository</name>
    <url>https://repository.apache.org/content/repositories/snapshots/</url>
    <releases>
        <enabled>false</enabled>
    </releases>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>
</repositories>

    <dependencies>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.2.10.v20150310</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>ctakes-web-client</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-Xlint</compilerArgument>
                </configuration>
            </plugin>
            <plugin>

                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>org.apache.ctakes.web.client.servlet.MainRun</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Body:
Check your dependency tree (make sure you use verbose command to show duplicates).

mvn dependency:tree -Dverbose

then, exclude any javassist that is not inside hibernate. For instance:

<dependency>
<groupId>xxx.xxxxxxxx</groupId>
<artifactId>xxxxxxx</artifactId>
<version>${version}</version>
<exclusions>
    <exclusion>
        <artifactId>javassist</artifactId>
        <groupId>org.javassist</groupId>
    </exclusion>
</exclusions>

Where:
"xxx.xxxxxxxx" from groupId that you identified on dependency tree.
"xxxxxxx" from artifactId that you identified on dependency tree.


问:
Google play store app signing key issue with 105 char hex
I'm trying to add my keystore to google play app signing.

The guide mentions

```<code>java -jar pepk.jar --keystore = foo.keystore --alias = foo --output = output.zip --encryptionkey = The_Hex_Which_Is_105_Char
</code>```

The_Hex_Which_Is_105_Char is a 105 char hex provided by google in the instructions.

which I had to remove the extra spaces to make it to work.

```<code>java -jar pepk.jar --keystore=my.keystore --alias=myAlias --output=output.zip --encryptionkey=The_Hex_Which_Is_105_Char
</code>```

but running this I get an error:

```<code>Error: Unable to export or encrypt the private key
java.lang.IllegalArgumentException: Hex encoded byte array must have even length but instead has length: 105. Hex encoded string: The_Hex_Which_Is_105_Char
    at com.google.wireless.android.vending.developer.signing.tools.extern.export.ExportEncryptedPrivateKeyTool.fromHex(ExportEncryptedPrivateKeyTool.java:225)
    at com.google.wireless.android.vending.developer.signing.tools.extern.export.ExportEncryptedPrivateKeyTool.run(ExportEncryptedPrivateKeyTool.java:149)
    at com.google.wireless.android.vending.developer.signing.tools.extern.export.ExportEncryptedPrivateKeyTool.main(ExportEncryptedPrivateKeyTool.java:110)
</code>```

How should the key be generated? Why does google give me a 105 char hex key and the pepk tool doesn't work with?

答:
There were 3 options

Have Google create and manage app signature keys (recommended)

Export and upload a key and a certificate from a Java Keystore

Export and upload a key and certificate (not from a Java keystore)

I was using option 2 as my keystore was already created.

I got it to work by using the encryptionkey provided in option 3 (136 characters)

Export and upload a key and certificate (not from a Java keystore)

```<code> java -jar pepk.jar --keystore = foo.keystore --alias = foo --output =
 output.zip --encryptionkey = KeyFromOption3WorksHere136CharactersLong
</code>```

Body:
I'm trying to add my keystore to google play app signing.

The guide mentions

java -jar pepk.jar --keystore = foo.keystore --alias = foo --output = output.zip --encryptionkey = The_Hex_Which_Is_105_Char

The_Hex_Which_Is_105_Char is a 105 char hex provided by google in the instructions.

which I had to remove the extra spaces to make it to work.

java -jar pepk.jar --keystore=my.keystore --alias=myAlias --output=output.zip --encryptionkey=The_Hex_Which_Is_105_Char

but running this I get an error:

Error: Unable to export or encrypt the private key
java.lang.IllegalArgumentException: Hex encoded byte array must have even length but instead has length: 105. Hex encoded string: The_Hex_Which_Is_105_Char
    at com.google.wireless.android.vending.developer.signing.tools.extern.export.ExportEncryptedPrivateKeyTool.fromHex(ExportEncryptedPrivateKeyTool.java:225)
    at com.google.wireless.android.vending.developer.signing.tools.extern.export.ExportEncryptedPrivateKeyTool.run(ExportEncryptedPrivateKeyTool.java:149)
    at com.google.wireless.android.vending.developer.signing.tools.extern.export.ExportEncryptedPrivateKeyTool.main(ExportEncryptedPrivateKeyTool.java:110)

How should the key be generated? Why does google give me a 105 char hex key and the pepk tool doesn't work with?

Body:
There were 3 options

Have Google create and manage app signature keys (recommended)

Export and upload a key and a certificate from a Java Keystore

Export and upload a key and certificate (not from a Java keystore)

I was using option 2 as my keystore was already created.

I got it to work by using the encryptionkey provided in option 3 (136 characters)

Export and upload a key and certificate (not from a Java keystore)

 java -jar pepk.jar --keystore = foo.keystore --alias = foo --output =
 output.zip --encryptionkey = KeyFromOption3WorksHere136CharactersLong


问:
how to bitwise shift a string in php?
i want to shift a 16-bit variable in Php.
but my code is not working.
its just shifts the Lowest nibbles of each Byte. and leave The High nibble unchanged.
first and third nibble shifts fine.
but second and fourth is not.</p>

```<code>public static function leftShift2Byte($in){
     $strarr = str_split($in);
     if($strarr[1]>chr(127)){
         $strarr[1] = $strarr[1]<<1;
         $strarr[0] = $strarr[0]<<1;
         $strarr[0]++;
     }else{
         $strarr[1] = $strarr[1]<<1;
         $strarr[0] = $strarr[0]<<1;
     }
     return $strarr[0].$strarr[1];
 }
</code>```

答:
Bitwise operator << or >> left or right </p>

```<code>
echo 1010<<2 ;

</code>```

Title: how to bitwise shift a string in php?

Body:
i want to shift a 16-bit variable in Php.
but my code is not working.
its just shifts the Lowest nibbles of each Byte. and leave The High nibble unchanged.
first and third nibble shifts fine.
but second and fourth is not.

public static function leftShift2Byte($in){
     $strarr = str_split($in);
     if($strarr[1]>chr(127)){
         $strarr[1] = $strarr[1]<<1;
         $strarr[0] = $strarr[0]<<1;
         $strarr[0]++;
     }else{
         $strarr[1] = $strarr[1]<<1;
         $strarr[0] = $strarr[0]<<1;
     }
     return $strarr[0].$strarr[1];
 }

Body:
Bitwise operator << or >> left or right

echo 1010<<2 ;


问:
VirtualBox the windows of virtual machines list disappears
How can I show the windows of the virtual machine list again?

Like this:
The windows disappear

答:
I was facing the same issue and was able to restore the list by deleting the configuration file under $HOME\.VirtualBox\VirtualBox.xml (Windows host)

On Linux and MacOS, the path should be something like

$HOME/.config/VirtualBox (Linux host)

$HOME/Library/VirtualBox (MacOS host)

I'm sure this is not the most elegant solution but it seems to restore the default settings wihtout hassle

Hope I could help, Cheers
JR

Edit: Annoyingly (albeit naturally) this also resets all kinds of pop-ups and warning that you might have to accept again...


问:
Data binding in React
What I want to do is when I type some text in an input field, it should appear in another place realtime.

Below is my input;

    <input className='post_data_input_overlay' placeholder="Ask your question here" ref="postTxt"/>

```

How can I achieve that?

答:
I think @Richard Garside is correct.

I suggest some changes to clear even more the code.

Change this

```<code>onChange={(e) => this.update("field2", e)}
</code>```

To this

```<code>onChange={this.handleOnChange}
</code>```

And also, change this

```<code>this.setState({ [name]: e.target.value });
</code>```

To this

```<code>this.setState({ [e.target.name]: e.target.value})
</code>```

Besides, you have to add the "name" attribute to the field with a value that relates with the key on the state object.

Title: Data binding in React

Body:
What I want to do is when I type some text in an input field, it should appear in another place realtime.

Below is my input;

    <input className='post_data_input_overlay' placeholder="Ask your question here" ref="postTxt"/>

How can I achieve that?

Body:
I think @Richard Garside is correct.

I suggest some changes to clear even more the code.

Change this

onChange={(e) => this.update("field2", e)}

To this

onChange={this.handleOnChange}

And also, change this

this.setState({ [name]: e.target.value });

To this

this.setState({ [e.target.name]: e.target.value})

Besides, you have to add the "name" attribute to the field with a value that relates with the key on the state object.


问:
Error SQL0204 - Not found HTTPCLOB in SYSTOOOLS type *N
I am trying to use HTTPCLOB function to issue a POST request to a web service, but when I run the program I get the error as in the title, no matter my efforts to match the fields' type of my SQL statement to those of the function.
Here D-specifications:

```<code>D url             s           1024a   varying
D httpHeader      s           1024a   varying inz
D requestMsg      s          32000a   varying inz
D resHttpHeader   s          32000a   varying inz
D resMsg          s          32000a   varying inz
</code>```

This is the SQL statement:

```<code>url = 'https://labelservice.gls-italy.com/AddParcel';
requestMsg = 'XMLInfoParcel: ' + xmlData;
httpHeader = 'Content-Type: application/x-www-form-urlencoded;'
           + ' Content-Length: ' + %char(%len(requestMsg))
           ;
exec sql
  select cast(responseMsg as clob(2G))
  //   , cast(responseHttpHeader as varchar(512))
  into :resMsg
  // , :resHttpHeader
  from table(systoools.HTTPCLOB(
          URL => cast(:url
                 as varchar(2048)),
          HTTPMETHOD => 'POST',
          HTTPHEADER => cast(:httpHeader
                 as clob(10K)),
          REQUESTMSG => cast(:requestMsg
                 as clob(2G))
             )
       ) as httpRequest
;
</code>```

where xmlData is an xml-variabile with some content in it.
I assume there might be other errors because this is my first try using this function.
Anyway, as for the IBM documentation here
https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_73/rzajq/rzajqudfhttpclob.htm
variables' types match.
What am I doing wrong?

答:
SYSTOOLS has two 'O's, not three.

IE: SYSTOOLS vs SYSTOOOLS

Body:
I am trying to use HTTPCLOB function to issue a POST request to a web service, but when I run the program I get the error as in the title, no matter my efforts to match the fields' type of my SQL statement to those of the function.
Here D-specifications:

D url             s           1024a   varying
D httpHeader      s           1024a   varying inz
D requestMsg      s          32000a   varying inz
D resHttpHeader   s          32000a   varying inz
D resMsg          s          32000a   varying inz

This is the SQL statement:

url = 'https://labelservice.gls-italy.com/AddParcel';
requestMsg = 'XMLInfoParcel: ' + xmlData;
httpHeader = 'Content-Type: application/x-www-form-urlencoded;'
           + ' Content-Length: ' + %char(%len(requestMsg))
           ;
exec sql
  select cast(responseMsg as clob(2G))
  //   , cast(responseHttpHeader as varchar(512))
  into :resMsg
  // , :resHttpHeader
  from table(systoools.HTTPCLOB(
          URL => cast(:url
                 as varchar(2048)),
          HTTPMETHOD => 'POST',
          HTTPHEADER => cast(:httpHeader
                 as clob(10K)),
          REQUESTMSG => cast(:requestMsg
                 as clob(2G))
             )
       ) as httpRequest
;

where xmlData is an xml-variabile with some content in it.
I assume there might be other errors because this is my first try using this function.
Anyway, as for the IBM documentation here
https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_73/rzajq/rzajqudfhttpclob.htm
variables' types match.
What am I doing wrong?


答:
I would select names where the subject matched.</p>

```<code>var matches = students.Where(x => x.subjects.Contains("s2")).Select(y => y.Name);
var names = string.Join(",", matches);
</code>```

Title: I want to group list of list

Body:
The structure of class along with sample data here.

class Student
{
    public Int32 Id { get; set; }

    public string Name { get; set; }

    public Int32 Age { get; set; }

    public List<string> subjects { get; set; }

}

class Program
{
    static void Main( string[] )
    {
        List<Student> students = new List<Student>()
        {
           new Student(){ Id=1 ,Name="Pratik", Age=24, subjects=new List<string>(){"s1", "s2"}},
           new Student(){ Id=2, Name="Ashish", Age=28, subjects=new List<string>{"s1", "s4"}},
           new Student(){ Id=3, Name="Umesh", Age=24, subjects=new List<string>(){"s1" }},
           new Student(){ Id=4, Name="Ajay", Age=28, subjects=new List<string>(){"s5", "s1"}},
           new Student(){ Id=5, Name="Vijay", Age=24, subjects=new List<string>(){"s1"}},
           new Student(){ Id=6, Name="Shital", Age=24, subjects=new List<string>(){"s2", "s3"}}
        };

        ...
    }

I want to group subjects on Names for ex.

s2 Pratik, Shital

Body:
I would select names where the subject matched.

var matches = students.Where(x => x.subjects.Contains("s2")).Select(y => y.Name);
var names = string.Join(",", matches);


问:
Why does the line marked with //1 print 57 instead of 39?
```<code>class X {
    protected int v = 0;

    public X() {
        v += 10;
    }

    public void proc(X p) {
        System.out.println(43);
    }
}

class Y extends X {
    public Y() {
        v += 5;
    }

    public void proc(X p) {
        System.out.println(57);
    }

    public int getV() {
        return v;
    }
}

class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        System.out.println(39);
    }
}

class Main {
    public static void main(String[] args) {
        X x = new Z();
        Y y = new Z();
        Z z = new Z();
        x.proc(z);// 1
        System.out.println(y.getV());
    }
}
</code>```

From what I can understand,the method proc() is called on an object of type X that "holds" a type Z and at runtime JVM checks the object's type and overrides the method with the proc() method from Y.But the method parameter is of type Z,why doesn't it call the overloaded method from the Z class?

答:
Because you're passing an X to proc, so the proc for class Y prevails.

If you passed an actual Z declared as a Z, it would have printed 39.

```<code>Z x = new Z();
X y = new Z();
Z z = new Z();

z.proc(x); // prints 39
z.proc(y); // prints 57
</code>```

Body:
class X {
    protected int v = 0;

    public X() {
        v += 10;
    }

    public void proc(X p) {
        System.out.println(43);
    }
}

class Y extends X {
    public Y() {
        v += 5;
    }

    public void proc(X p) {
        System.out.println(57);
    }

    public int getV() {
        return v;
    }
}

class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        System.out.println(39);
    }
}

class Main {
    public static void main(String[] args) {
        X x = new Z();
        Y y = new Z();
        Z z = new Z();
        x.proc(z);// 1
        System.out.println(y.getV());
    }
}

From what I can understand,the method proc() is called on an object of type X that "holds" a type Z and at runtime JVM checks the object's type and overrides the method with the proc() method from Y.But the method parameter is of type Z,why doesn't it call the overloaded method from the Z class?

Body:
Because you're passing an X to proc, so the proc for class Y prevails.

If you passed an actual Z declared as a Z, it would have printed 39.

Z x = new Z();
X y = new Z();
Z z = new Z();

z.proc(x); // prints 39
z.proc(y); // prints 57


问:
Finding frequency of range of numbers in Mathematica
Given a list of numbers in Mathematica, how would I extract from that list the total number of numbers between numbers a and b that I specify?

答:
Here is one approach that you can try:

```<code>freq[a_, b_, list_] := Total@Boole@Cases[list, x_ :> a <= x <= b]
lst = RandomInteger[10, 20]
Out = {6, 1, 1, 6, 3, 1, 10, 0, 2, 10, 3, 5, 9, 1, 5, 5, 3, 8, 2, 3}

freq[3, 6, lst]
Out = 9
</code>```

An alternate approach using IntervalMemberQ is

```<code>freq[a_, b_, list_] :=
 Total@Boole@IntervalMemberQ[Interval[{a, b}], list]
</code>```

Body:
Here is one approach that you can try:

freq[a_, b_, list_] := Total@Boole@Cases[list, x_ :> a <= x <= b]
lst = RandomInteger[10, 20]
Out = {6, 1, 1, 6, 3, 1, 10, 0, 2, 10, 3, 5, 9, 1, 5, 5, 3, 8, 2, 3}

freq[3, 6, lst]
Out = 9

An alternate approach using IntervalMemberQ is

freq[a_, b_, list_] :=
 Total@Boole@IntervalMemberQ[Interval[{a, b}], list]


答:
do you think the following is what you need ?</p>

```<code>WITH temp
AS (SELECT id,
           date,
           SUM(sales) AS n_Sale
    FROM dbo.t
    GROUP BY id,
             date)
SELECT *,
       SUM(t.n_Sale) OVER (ORDER BY date ASC ROWS 9 PRECEDING)
FROM temp AS t;
</code>```

Title: Get previous consecutive 10 rows sale to get sum

Body:
I have a table t1

**id**        **Date**             **Sales**
102         20180101                    50
102         20180102                    60
102         20180103                    70
102         20180104                    90
102         20180105                    10
102         20180105                   100
102         20180106                   100
102         20180107                    30
102         20180108                    20
102         20180109                    34
102         20180110                    40
102         20180111                    50
102         20180112                    60

Now I want the previous10 records for each row like for 20180111 sum of sale should be 464 which is the sum of the previous 10 records sale and for 20180112 it should be 474.

Body:
do you think the following is what you need ?

WITH temp
AS (SELECT id,
           date,
           SUM(sales) AS n_Sale
    FROM dbo.t
    GROUP BY id,
             date)
SELECT *,
       SUM(t.n_Sale) OVER (ORDER BY date ASC ROWS 9 PRECEDING)
FROM temp AS t;


问:
Load formgroup data into a anchor tag
I have something like this

```<code> **<div class="form-group col-md-3 col-sm-3 col-xs-12" *ngIf="isEdit">
    <label for="url">URL</label>
    <input id="url" [formControl]="fg.url" class="form-control" type="text" />
  </div>**
</code>```

Now I can see url data in the text box.How can I modify this code in the html file so I can see data as a clickable url link.I mean how can I use the anchor tag in this context.

Thanks

答:
If I get correctly what you want to do. Just add the anchor tag and put in the value between these {{}}.</p>

```<code><div class="form-group col-md-3 col-sm-3 col-xs-12" *ngIf="isEdit">
  <label for="url">
    <a [href]="form.controls.url.value">{{form.controls.url.value}}</a>
  </label>
  <input id="url" [formControl]="fg.url" class="form-control" type="text" />
</div>
</code>```

Title: Load formgroup data into a anchor tag

Body:
I have something like this

 **

    URL
    <input id="url" [formControl]="fg.url" class="form-control" type="text" />

**

Now I can see url data in the text box.How can I modify this code in the html file so I can see data as a clickable url link.I mean how can I use the anchor tag in this context.

Thanks

Body:
If I get correctly what you want to do. Just add the anchor tag and put in the value between these {{}}.

<div class="form-group col-md-3 col-sm-3 col-xs-12" *ngIf="isEdit">
  <label for="url">
    <a [href]="form.controls.url.value">{{form.controls.url.value}}</a>
  </label>
  <input id="url" [formControl]="fg.url" class="form-control" type="text" />
</div>