问:
ExecutorService should be alive for whole life of bean or should have narrow(method) scope
I have a method, which has to process thousand of documents.

It takes time in normal processing so I use ExecutorService to reduce processing time by having multiple threads working in parallel.

I have to use this method for processing of two long lists.

Approach 1 of handling ExecutorService:

Right now , I have initialized ExecutorService within method and shutting down it in same method. (which is called twice)

So it leads to creation and shutting down of ExecutorService twice.

```<code>  private List<DocDTO> convertData(args) {
    ExecutorService service = Executors.newFixedThreadPool(threads);

    List<Future<Set<DocDTO>>> futures = new ArrayList<Future<Set<DocDTO>>>();

    for (Pro pro : pros.getPros()) {
        Callable<Set<DocDTO>> callable = new Callable<Set<DocDTO>>() {
            public Set<DocDTO> call() throws Exception {
                for loop code
            }
        };
        futures.add(service.submit(callable));
    }

    service.shutdown();
    for (Future<Set<DocDTO>> future : futures) {
        if (future.get() != null) {
            list.addAll(future.get());
        }
    }
}
</code>```

Approach 2 of handling ExecutorService:

I was looking at below link:

http://programtalk.com/java/executorservice-not-shutting-down/

Author has created ExecutorService at Class level.

Could you please tell me if it is good idea to have ExecutorService created at method level or class level?

FYI , method in above code gets executed twice in a day

答:
Thanks Maleen and GhostCat for your valuable comments, i dropped plan of using multiple threads because of two reasons:

I was getting different results from the same method while running from single thread and multiple thread

ExecutorService does not work with Lazy relationship. So changing Entities' loading from Lazy to Eager might affect other functionality performance

Instead I optimized the way how I was loading entities rather than using multi threading. Previously, I was loading all static data from database one by one in for loop and saving it in EhCache .

After change I loaded all static data in one go using findall methods and saved in map and accessed same data from map in for loop . It increased performance of method a lot. Thank you again to both of you.

Body:
I have a method, which has to process thousand of documents.

It takes time in normal processing so I use ExecutorService to reduce processing time by having multiple threads working in parallel.

I have to use this method for processing of two long lists.

Approach 1 of handling ExecutorService:

Right now , I have initialized ExecutorService within method and shutting down it in same method. (which is called twice)

So it leads to creation and shutting down of ExecutorService twice.

  private List<DocDTO> convertData(args) {
    ExecutorService service = Executors.newFixedThreadPool(threads);

    List<Future<Set<DocDTO>>> futures = new ArrayList<Future<Set<DocDTO>>>();

    for (Pro pro : pros.getPros()) {
        Callable<Set<DocDTO>> callable = new Callable<Set<DocDTO>>() {
            public Set<DocDTO> call() throws Exception {
                for loop code
            }
        };
        futures.add(service.submit(callable));
    }

    service.shutdown();
    for (Future<Set<DocDTO>> future : futures) {
        if (future.get() != null) {
            list.addAll(future.get());
        }
    }
}

Approach 2 of handling ExecutorService:

I was looking at below link:

http://programtalk.com/java/executorservice-not-shutting-down/

Author has created ExecutorService at Class level.

Could you please tell me if it is good idea to have ExecutorService created at method level or class level?

FYI , method in above code gets executed twice in a day


来源: stackexchange

问:
error in establishing DB connection in Perl script?
I am using perl 5.24. I am trying to learn Perl.

I had written a simple Perl code to connect to a DB. But gives error stating

DBI connect('database=vms','DBA',...) failed: (no error string) at simpleperl.pl line 13.

The code is

```<code>#!/usr/bin/perl

use DBI;
use DBD::SQLAnywhere;

my $driver = "SQLAnywhere";
my $database = "vms";
my $dsn = "DBI:$driver:database=$database";
my $userid = "DBA";
my $password = "admin";
my $dbh = DBI->connect($dsn, $userid, $password,{RaiseError => 1}) or die ("died connection:$DBI::errstr");

if($dbh)
{
    print "Connection Established";
}
</code>```

Can anyone point out what might be the problem here?

答:
Note the following in DBD::SQLAnywhere documentation:

$dbh = DBI->connect( 'dbi:SQLAnywhere:ENG=demo', $userid, $passwd );

```<code>#!/usr/bin/perl

use strict;
use warnings;
use DBI;

my $driver = "SQLAnywhere";
my $database = "vms";
my $dsn = "DBI:$driver:ENG=$database";
my $userid = "DBA";
my $password = "admin";
my $dbh = DBI->connect($dsn, $userid, $password, {RaiseError => 1});

print "Connection established\n";

$dbh->disconnect;
</code>```

Note also the following:

Always use strict and warnings.

You do not need use DBD::SQLAnywhere;. DBI will pick the driver based on what you specify in the connection string.

You specified {RaiseError => 1} in your connection options. That means, there is no need for the or die. DBI will croak if connect fails.

You probably want AutoCommit => 0 to go with that RaiseError => 1.

There is no need for the if ($dbh) following the connection attempt. You won't get there unless connect succeeded.

Given that fixing the connection string did not solve the problem and I do not have an instance of a SQLAnywhere database to test things, I am going to recommend you add:

```<code>DBI->trace( 5 );
</code>```

before the connect call, and update your question with the trace information. See also TRACING.

ContentLicense: CC BY-SA 3.0

Body:
I am using perl 5.24. I am trying to learn Perl.

I had written a simple Perl code to connect to a DB. But gives error stating

DBI connect('database=vms','DBA',...) failed: (no error string) at simpleperl.pl line 13.

The code is

#!/usr/bin/perl

use DBI;
use DBD::SQLAnywhere;

my $driver = "SQLAnywhere";
my $database = "vms";
my $dsn = "DBI:$driver:database=$database";
my $userid = "DBA";
my $password = "admin";
my $dbh = DBI->connect($dsn, $userid, $password,{RaiseError => 1}) or die ("died connection:$DBI::errstr");

if($dbh)
{
    print "Connection Established";
}

Can anyone point out what might be the problem here?

Body:
Note the following in DBD::SQLAnywhere documentation:

$dbh = DBI->connect( 'dbi:SQLAnywhere:ENG=demo', $userid, $passwd );

#!/usr/bin/perl

use strict;
use warnings;
use DBI;

my $driver = "SQLAnywhere";
my $database = "vms";
my $dsn = "DBI:$driver:ENG=$database";
my $userid = "DBA";
my $password = "admin";
my $dbh = DBI->connect($dsn, $userid, $password, {RaiseError => 1});

print "Connection established\n";

$dbh->disconnect;

Note also the following:

Always use strict and warnings.

You do not need use DBD::SQLAnywhere;. DBI will pick the driver based on what you specify in the connection string.

You specified {RaiseError => 1} in your connection options. That means, there is no need for the or die. DBI will croak if connect fails.

You probably want AutoCommit => 0 to go with that RaiseError => 1.

There is no need for the if ($dbh) following the connection attempt. You won't get there unless connect succeeded.

Given that fixing the connection string did not solve the problem and I do not have an instance of a SQLAnywhere database to test things, I am going to recommend you add:

DBI->trace( 5 );

before the connect call, and update your question with the trace information. See also TRACING.


问:
Entity Framework 6 not saving changes
I've got an MVC5 web application that uses SQL Server 2008 as a back end database along with the Entity Framework 6. There's no error in adding code but data can not get stored in to database.

my model context.cs looks like

```<code>public partial class checkin_checkoutEntities2 : DbContext
    {
        public checkin_checkoutEntities2()
            : base("name=checkin_checkoutEntities2")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Advance_Booking> Advance_Bookings { get; set; }
        public virtual DbSet<employee_reg> employee_reg { get; set; }
        public virtual DbSet<Extend_Stay> Extend_Stay { get; set; }
        public virtual DbSet<Guest_reg> Guest_reg { get; set; }
        public virtual DbSet<RoomBooking> RoomBooking { get; set; }
        public virtual DbSet<Rooms_ms> Rooms_ms { get; set; }
    }
</code>```

and my adding method is as below

```<code> ab.Room_id = Convert.ToInt32(ab_rm_no.room_id);
 ab.Guest_id = Convert.ToInt32(frm["guest_id"].ToString());
 ab.Expected_checkin  = Convert.ToDateTime(frm["BookedDateFR"].ToString());
 ab.Expected_checkout = Convert.ToDateTime(frm["BookedDateTO"].ToString());

 db.Advance_Bookings.Add(ab);
 db.SaveChanges();
</code>```

答:
According to the comments, the db.SaveChanges(); was wrapped in a transaction

```<code>using (var transaction = new System.Transactions.TransactionScope())
{
    // some changes and db.SaveChanges();
}
</code>```

and it was working only without the transaction.

The reason is, that a transaction needs to be committed in order to persist the saved changes.

```<code>using (var transaction = new System.Transactions.TransactionScope())
{
    // some changes and db.SaveChanges();

    transaction.Commit();
}
</code>```

Otherwise the changes would be discarded at the end of the transaction block.

ContentLicense: CC BY-SA 4.0

Title: Entity Framework 6 not saving changes

Body:
I've got an MVC5 web application that uses SQL Server 2008 as a back end database along with the Entity Framework 6. There's no error in adding code but data can not get stored in to database.

my model context.cs looks like

public partial class checkin_checkoutEntities2 : DbContext
    {
        public checkin_checkoutEntities2()
            : base("name=checkin_checkoutEntities2")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Advance_Booking> Advance_Bookings { get; set; }
        public virtual DbSet<employee_reg> employee_reg { get; set; }
        public virtual DbSet<Extend_Stay> Extend_Stay { get; set; }
        public virtual DbSet<Guest_reg> Guest_reg { get; set; }
        public virtual DbSet<RoomBooking> RoomBooking { get; set; }
        public virtual DbSet<Rooms_ms> Rooms_ms { get; set; }
    }

and my adding method is as below

 ab.Room_id = Convert.ToInt32(ab_rm_no.room_id);
 ab.Guest_id = Convert.ToInt32(frm["guest_id"].ToString());
 ab.Expected_checkin  = Convert.ToDateTime(frm["BookedDateFR"].ToString());
 ab.Expected_checkout = Convert.ToDateTime(frm["BookedDateTO"].ToString());

 db.Advance_Bookings.Add(ab);
 db.SaveChanges();

Body:
According to the comments, the db.SaveChanges(); was wrapped in a transaction

using (var transaction = new System.Transactions.TransactionScope())
{
    // some changes and db.SaveChanges();
}

and it was working only without the transaction.

The reason is, that a transaction needs to be committed in order to persist the saved changes.

using (var transaction = new System.Transactions.TransactionScope())
{
    // some changes and db.SaveChanges();

    transaction.Commit();
}

Otherwise the changes would be discarded at the end of the transaction block.


问:
What's the best way to set a windows service description in .net
I have created a C# service using the VS2005 template. It works fine however the description of the service is blank in the Windows Services control applet.</p>

答: You can also set the service name and description from the IDE, by right clicking on the "serviceInstaller" icon in the design view of ProjectInstaller class.

OwnerDisplayName: Kevin Gale

ContentLicense: CC BY-SA 2.5


问:
php - How do I weed out similar items from an associative array?
UPDATE: someone edited my question incorrectly, but it's fixed now

Let's say I have the following associative array:

```<code>Array (
[Postponement no issue for Man Utd (BBC) ] => 8
[Postponement no issue for Man Utd ] => 7
[Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday's game at Chelsea being ... ] => 3
)
</code>```

You'll notice that the term "Postponement no issue for Man Utd" appears in all three keys. I want to turn this array into a new array like this:

```<code>Array ( [Postponement no issue for Man Utd] => 18 )
</code>```

Where 18 is the sum of all values where the key contains "Postponement no issue for Man Utd".

In other words: if one key appears inside another key, the latter is dropped fom the new array and it's value is added on to the former key's value.

Is this possible and how? Thanks in advance.

答:
```<code>foreach($array as $k1 => $v1)
        foreach($array as $k2 => $v2)
             if(strpos($k2, $k1) !== false) // or === 0
                   $result[$k1] = (isset($result[$k1]) ? $result[$k1] : 0) + $v2;
</code>```

untested

Body:
UPDATE: someone edited my question incorrectly, but it's fixed now

Let's say I have the following associative array:

Array (
[Postponement no issue for Man Utd (BBC) ] => 8
[Postponement no issue for Man Utd ] => 7
[Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday's game at Chelsea being ... ] => 3
)

You'll notice that the term "Postponement no issue for Man Utd" appears in all three keys. I want to turn this array into a new array like this:

Array ( [Postponement no issue for Man Utd] => 18 )

Where 18 is the sum of all values where the key contains "Postponement no issue for Man Utd".

In other words: if one key appears inside another key, the latter is dropped fom the new array and it's value is added on to the former key's value.

Is this possible and how? Thanks in advance.

Body:
foreach($array as $k1 => $v1)
        foreach($array as $k2 => $v2)
             if(strpos($k2, $k1) !== false) // or === 0
                   $result[$k1] = (isset($result[$k1]) ? $result[$k1] : 0) + $v2;

untested


问:
SQL Constraint Validation without incrementing the Sequence - Odoo 10
I made a SQL Constraint in a form but we when enter something wrong it give us the constraint error but the Form is still not saved, but the problem is behind,  the system make the incrementation of the sequence of this form. knowing that i make the sequence to get created only once the from get saved by super the create function.

How can make a validation of Constraint without incrementing the Sequence ?

This My Sequence Code

```<code>@api.model
def create(self, vals):
    if vals.get('name','/')=='/':
       sequence = self.env['ir.sequence'].next_by_code('archive.dossier')
       vals['name'] = sequence
    return super(oeArchiveDossier, self).create(vals)
</code>```

答:
There are two types (Implementation) of sequence used in odoo.

Standard

No Gap

Standard

If you selected this implementation type in sequence (it's default) then sequence will be created in postgresql and managed by postgresql. There is no such control over it. So in case any transactions gets failed then sequence (next number) won't rollbacked.

No Gap

If you select this implementation type then it will be managed by odoo, so in case any issue is there then no sequence number will be skipped.

To better control the validations there is an option in odoo to set method for constrains.

```<code>@api.constrains('field1', 'field2')
def check_validations(self):
      ## Perform Validation
      ## If condition not satisfied then raise an error.
      if validation_conditions:
          ## Raise an error
</code>```

Body:
I made a SQL Constraint in a form but we when enter something wrong it give us the constraint error but the Form is still not saved, but the problem is behind,  the system make the incrementation of the sequence of this form. knowing that i make the sequence to get created only once the from get saved by super the create function.

How can make a validation of Constraint without incrementing the Sequence ?

This My Sequence Code

@api.model
def create(self, vals):
    if vals.get('name','/')=='/':
       sequence = self.env['ir.sequence'].next_by_code('archive.dossier')
       vals['name'] = sequence
    return super(oeArchiveDossier, self).create(vals)

Body:
There are two types (Implementation) of sequence used in odoo.

Standard

No Gap

Standard

If you selected this implementation type in sequence (it's default) then sequence will be created in postgresql and managed by postgresql. There is no such control over it. So in case any transactions gets failed then sequence (next number) won't rollbacked.

No Gap

If you select this implementation type then it will be managed by odoo, so in case any issue is there then no sequence number will be skipped.

To better control the validations there is an option in odoo to set method for constrains.

@api.constrains('field1', 'field2')
def check_validations(self):
      ## Perform Validation
      ## If condition not satisfied then raise an error.
      if validation_conditions:
          ## Raise an error


问:
Python amend content of CSV and resave
Require the program to search for a row then adjust a particular element of the CSV before re-saving.

Any help appreciated!

```<code>import csv
import os
username=input('Enter username: ')
with open ('user.csv', 'r') as user:
    reader=csv.reader(user, delimiter=',')
    print(reader)

with open ('newuser.csv', 'w') as newdetail:
    writer=csv.writer(newdetail, delimiter=',')
    for colomn in reader:
        if username in coloum[1]:
            print('User found! \n')
            print('UserID: '+colomn[0])
            print('Username: '+colomn[1])
            print('Interest: '+colomn[2])
            change = (column[2])
            change = input("What is your new interest?")
            print(colomn[2]+' has been changed to ', change)
        writer.writerow(colomn)
os.remove('user.csv')
os.rename('newuser.csv', 'user.csv')
</code>```

The current error is:

```<code>dir/ line 10, in <module>
    for colomn in reader:
ValueError: I/O operation on closed file.
</code>```

Much appreciated, this is where I am up to now. Currently only prints the single line that's being edited and not all of the other movies that have not been adjusted.

```<code>import csv
import os
new = []
username=input('Enter movie: ')
with open ('movies.csv', 'r') as user:
    reader=csv.reader(user, delimiter=',')
    #print(reader)

    with open ('newmovies.csv', 'w') as newdetail:
        writer=csv.writer(newdetail, delimiter=',')
        for colomn in reader:
            if username in colomn[1]:
                print('Movie found!')
                print('MovieID: '+colomn[0])
                print('Movie name: '+colomn[1])
                print('Interest: '+colomn[2])
        choice = input("what is your new interest?")
        print('Interest has been changed to ', choice)
        new = [(colomn[0]),(colomn[1]),(choice)]
        writer.writerow(new)
os.remove('movies.csv')
os.rename('newmovies.csv', 'movies.csv')
</code>```

答:
reader object is not containing the data, but only has a direct access to the file. Once you close the user.csv file (when exiting from with scope) the reader is no more useful.

Try to put the second with inside the 1st scope:

```<code>with open ('user.csv', 'r') as user:
    reader=csv.reader(user, delimiter=',')
    print(reader)
    with open ('newuser.csv', 'w') as newdetail:
        writer=csv.writer(newdetail, delimiter=',')
        for colomn in reader:
            if username in colomn[1]:
                print('User found! \n')
                print('UserID: '+colomn[0])
                print('Username: '+colomn[1])
                print('Interest: '+colomn[2])
                change = (column[2])
                change = input("What is your new interest?")
                print(colomn[2]+' has been changed to ', change)
            writer.writerow(colomn)
</code>```

P.S. - fix the 11th line as well - colomn instead of coloum

Title: Python amend content of CSV and resave

Body:
Require the program to search for a row then adjust a particular element of the CSV before re-saving.

Any help appreciated!

import csv
import os
username=input('Enter username: ')
with open ('user.csv', 'r') as user:
    reader=csv.reader(user, delimiter=',')
    print(reader)

with open ('newuser.csv', 'w') as newdetail:
    writer=csv.writer(newdetail, delimiter=',')
    for colomn in reader:
        if username in coloum[1]:
            print('User found! \n')
            print('UserID: '+colomn[0])
            print('Username: '+colomn[1])
            print('Interest: '+colomn[2])
            change = (column[2])
            change = input("What is your new interest?")
            print(colomn[2]+' has been changed to ', change)
        writer.writerow(colomn)
os.remove('user.csv')
os.rename('newuser.csv', 'user.csv')

The current error is:

dir/ line 10, in <module>
    for colomn in reader:
ValueError: I/O operation on closed file.

Much appreciated, this is where I am up to now. Currently only prints the single line that's being edited and not all of the other movies that have not been adjusted.

import csv
import os
new = []
username=input('Enter movie: ')
with open ('movies.csv', 'r') as user:
    reader=csv.reader(user, delimiter=',')
    #print(reader)

    with open ('newmovies.csv', 'w') as newdetail:
        writer=csv.writer(newdetail, delimiter=',')
        for colomn in reader:
            if username in colomn[1]:
                print('Movie found!')
                print('MovieID: '+colomn[0])
                print('Movie name: '+colomn[1])
                print('Interest: '+colomn[2])
        choice = input("what is your new interest?")
        print('Interest has been changed to ', choice)
        new = [(colomn[0]),(colomn[1]),(choice)]
        writer.writerow(new)
os.remove('movies.csv')
os.rename('newmovies.csv', 'movies.csv')

Body:
reader object is not containing the data, but only has a direct access to the file. Once you close the user.csv file (when exiting from with scope) the reader is no more useful.

Try to put the second with inside the 1st scope:

with open ('user.csv', 'r') as user:
    reader=csv.reader(user, delimiter=',')
    print(reader)
    with open ('newuser.csv', 'w') as newdetail:
        writer=csv.writer(newdetail, delimiter=',')
        for colomn in reader:
            if username in colomn[1]:
                print('User found! \n')
                print('UserID: '+colomn[0])
                print('Username: '+colomn[1])
                print('Interest: '+colomn[2])
                change = (column[2])
                change = input("What is your new interest?")
                print(colomn[2]+' has been changed to ', change)
            writer.writerow(colomn)

P.S. - fix the 11th line as well - colomn instead of coloum


问:
converting a tuple consisting of floats and text to one single string
I'm trying to convert a tuple consisting of 2 floats and 3 parts of text to one string so I can use it in file.write() because it is not accepting tuples.

```<code>testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters'
test = open('testresults.txt' ,'w')
test.write(testr)
test.close()
</code>```

whenever I try to run the program it gives me this

```<code>    test.write(testr)
TypeError: must be str, not tuple
</code>```

答:
Thankfully, python 3.6 makes this very easy and readable for us:

```<code>testr = f'you went {speed} mph and stopped in {stop} metres'
test = open('testresults.txt' ,'w')
test.write(testr)
test.close()
</code>```

otherwise, the same thing is acheived by using the string.format(*args) as mentioned in another answer.

Body:
I'm trying to convert a tuple consisting of 2 floats and 3 parts of text to one string so I can use it in file.write() because it is not accepting tuples.

testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters'
test = open('testresults.txt' ,'w')
test.write(testr)
test.close()

whenever I try to run the program it gives me this

    test.write(testr)
TypeError: must be str, not tuple

Body:
Thankfully, python 3.6 makes this very easy and readable for us:

testr = f'you went {speed} mph and stopped in {stop} metres'
test = open('testresults.txt' ,'w')
test.write(testr)
test.close()

otherwise, the same thing is acheived by using the string.format(*args) as mentioned in another answer.


问:
How do I turn an image into a popup with only text
I'm trying to have a popup show when an image is clicked. All I can find is how to enlarge an image. Below is the code I have but it's not working. I'm not sure which part is wrong... Am I allowed to have a table in the span tag? </p>

```<code>.popup {
margin-top: 10%;
position: relative;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}

.popup .popuptext {
visibility: hidden;
width: 250px;
background-color: #5FACD7;
color: #000000;
text-align: center;
border-radius: 6px;
Padding: 8px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -80px;
</code>```

<p>}</p>

```<code>.popup .popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}

.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}

@-websit-keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}

@keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}

<div class="popup" onclick="popup1()">
<img src="../media/hours.jpg" alt="Hours of Operation" width="300"
height="200"/>
<span class="popuptext" id="myPopup">
    <table>
    <tr>
    <th>Day</th>
    <th>Times</th>
    </tr>
    <tr>
        <td> Monday - Wednesday</td>
        <td> Thursday</td>
        <td>Friday</td>
        <td>Saturday/Sunday</td>
    </tr>
    <tr>
        <td>9:00 a.m. - 6:00 p.m.</td>
        <td>9:00 a.m. - 9:00 p.m.</td>
        <td>9:00 a.m. - 8:00 p.m.</td>
        <td>10:00 a.m. - 6:00 p.m.</td>
    </tr>
    </table>
    </span>
</div>

<div class="popup" onClick="=popup2()">
<img src="../media/tickets.jpeg" alt="General Admission" width="300"
height="200"/>
<span class="popuptext" id="myPopup2">
<table>
    <tr>
    <th></th>
    <th>Prices</th>
    </tr>
    <tr>
        <td>Adults: </td>
        <td>Children (5-12): </td>
        <td>Seniors/Students with ID: </td>
        <td>Adult Members: </td>
        <td>Child Members: </td>
    </tr>
    <tr>
        <td>$12.00</td>
        <td>$6.00</td>
        <td>$8.00</td>
        <td>Free</td>
        <td>Free</td>
    </tr>
    </table>
    </span>
</div>
</code>```

答:
Check This.

function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.popup {
  margin-top:10%;
    position: relative;
    display: inline-block;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.popup .popuptext {
    visibility: hidden;
    width: 250px;
    background-color: red;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 8px 0;
    position: absolute;
    z-index: 1;
    bottom: 125%;
    left: 50%;
    margin-left: -80px;
}

.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}</code>```

  This is a popup text

```

Body:
I'm trying to have a popup show when an image is clicked. All I can find is how to enlarge an image. Below is the code I have but it's not working. I'm not sure which part is wrong... Am I allowed to have a table in the span tag?

.popup {
margin-top: 10%;
position: relative;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}

.popup .popuptext {
visibility: hidden;
width: 250px;
background-color: #5FACD7;
color: #000000;
text-align: center;
border-radius: 6px;
Padding: 8px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -80px;

}

.popup .popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}

.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}

@-websit-keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}

@keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}

    Day
    Times

         Monday - Wednesday
         Thursday
        Friday
        Saturday/Sunday

        9:00 a.m. - 6:00 p.m.
        9:00 a.m. - 9:00 p.m.
        9:00 a.m. - 8:00 p.m.
        10:00 a.m. - 6:00 p.m.

    Prices

        Adults:
        Children (5-12):
        Seniors/Students with ID:
        Adult Members:
        Child Members:

        $12.00
        $6.00
        $8.00
        Free
        Free

Body:
Check This.

function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}

.popup {
  margin-top:10%;
    position: relative;
    display: inline-block;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.popup .popuptext {
    visibility: hidden;
    width: 250px;
    background-color: red;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 8px 0;
    position: absolute;
    z-index: 1;
    bottom: 125%;
    left: 50%;
    margin-left: -80px;
}

.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}

<div class="popup" onclick="myFunction()"><img src="http://abravmsd.com/images/ab_fb.png" width="30" height="30">
  <span class="popuptext" id="myPopup">This is a popup text</span>
</div>


问:
Problems with SQLite database, error when creating
i got this error when i start my app:

12-20 22:27:01.447: ERROR/Database(716): Failure 1 (near ":00": syntax error) on 0x1a4338 when preparing 'CREATE TABLE permission ( fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, validated tinyint(4) default 0, hour1 time default 08:00:00, hour2 time default 20:00:00, date1 date default NULL, date2 date default NULL, weekend tinyint(4) default 0, fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))'.

here is the code where i am creating the database:

```<code>private static final String PERMISSION_TABLE_CREATE =
"CREATE TABLE permission ("
"fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, "
"validated tinyint(4) default 0, hour1 time default 08:00:00, "
"hour2 time default 20:00:00, date1 date default NULL, "
"date2 date default NULL, weekend tinyint(4) default 0, "
"fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))";

private static final String USER_TABLE_CREATE = "CREATE TABLE user ( "
"email varchar(100) NOT NULL, password varchar(45) default NULL, "
"fullName varchar(80) default NULL, "
"mobilePhone varchar(14) default NULL, "
"mobileOperatingSystem varchar(20) default NULL, PRIMARY KEY  (email))";
</code>```

what i am doing bad?

答:
Obviously definition of your time row is wrong

Please check SQLite docs

You can try "YYYY-MM-DD HH:MM:SS.SSS" format, but better store value as an INTEGER (Unix Time)

Body:
i got this error when i start my app:

12-20 22:27:01.447: ERROR/Database(716): Failure 1 (near ":00": syntax error) on 0x1a4338 when preparing 'CREATE TABLE permission ( fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, validated tinyint(4) default 0, hour1 time default 08:00:00, hour2 time default 20:00:00, date1 date default NULL, date2 date default NULL, weekend tinyint(4) default 0, fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))'.

here is the code where i am creating the database:

private static final String PERMISSION_TABLE_CREATE =
"CREATE TABLE permission ("
"fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, "
"validated tinyint(4) default 0, hour1 time default 08:00:00, "
"hour2 time default 20:00:00, date1 date default NULL, "
"date2 date default NULL, weekend tinyint(4) default 0, "
"fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))";

private static final String USER_TABLE_CREATE = "CREATE TABLE user ( "
"email varchar(100) NOT NULL, password varchar(45) default NULL, "
"fullName varchar(80) default NULL, "
"mobilePhone varchar(14) default NULL, "
"mobileOperatingSystem varchar(20) default NULL, PRIMARY KEY  (email))";

what i am doing bad?


问:
SQL operand performing single row,column
enter image description here  My sql query:-

```<code>SELECT
(s.Mark*0.8+((i.OutOf)*sum(i.Mark)/9000)+((ai.OutOf)*sum(ai.Mark) /180)+a.Mark)
AS final
from mark_semester s,
     mark_assignment ai,
     mark_internaltest i,
     mark_attendance a,
     master_student ms
WHERE s.SubjectId=i.SubjectId and
      s.SubjectId=ai.SubjectId
      and s.SubjectId=a.SubjectId
      and s.SubjectId='1'
      AND s.RegNo=i.RegNo
      and s.RegNo=ai.RegNo
      and s.RegNo=a.RegNo
      and s.RegNo=ms.RegNo
      and s.RegNo='100'
      and s.Semester=i.Semester
      and s.Semester=ai.Semester
      and s.Semester=a.Semester
      and s.Semester='1'
</code>```

In this query i want to enter multiple subjectids and regnos to get data

can any one help me to solve this.

答:
You can use the IN MySQL operator to handle multiple SubjectId and RegNo, like this:

```<code>SELECT (s.Mark*0.8+((i.OutOf)*sum(i.Mark)/9000)+((ai.OutOf)*sum(ai.Mark)/180)+a.Mark) AS final
from mark_semester s
    join mark_assignment ai on s.SubjectId=ai.SubjectId
    join mark_internaltest i on s.SubjectId=i.SubjectId
    join mark_attendance a on s.SubjectId=a.SubjectId
    join master_student ms on s.RegNo=ms.RegNo
WHERE
    s.SubjectId in ('1','2') AND
    s.RegNo in ('100','101') and
    s.Semester='1'
</code>```

Body:
enter image description here  My sql query:-

SELECT
(s.Mark*0.8+((i.OutOf)*sum(i.Mark)/9000)+((ai.OutOf)*sum(ai.Mark) /180)+a.Mark)
AS final
from mark_semester s,
     mark_assignment ai,
     mark_internaltest i,
     mark_attendance a,
     master_student ms
WHERE s.SubjectId=i.SubjectId and
      s.SubjectId=ai.SubjectId
      and s.SubjectId=a.SubjectId
      and s.SubjectId='1'
      AND s.RegNo=i.RegNo
      and s.RegNo=ai.RegNo
      and s.RegNo=a.RegNo
      and s.RegNo=ms.RegNo
      and s.RegNo='100'
      and s.Semester=i.Semester
      and s.Semester=ai.Semester
      and s.Semester=a.Semester
      and s.Semester='1'

In this query i want to enter multiple subjectids and regnos to get data

can any one help me to solve this.

Body:
You can use the IN MySQL operator to handle multiple SubjectId and RegNo, like this:

SELECT (s.Mark*0.8+((i.OutOf)*sum(i.Mark)/9000)+((ai.OutOf)*sum(ai.Mark)/180)+a.Mark) AS final
from mark_semester s
    join mark_assignment ai on s.SubjectId=ai.SubjectId
    join mark_internaltest i on s.SubjectId=i.SubjectId
    join mark_attendance a on s.SubjectId=a.SubjectId
    join master_student ms on s.RegNo=ms.RegNo
WHERE
    s.SubjectId in ('1','2') AND
    s.RegNo in ('100','101') and
    s.Semester='1'


问:
Store different templated classes in one container without losing information about it's type
I'm currently working on a project where a client part of my application has to be able to create custom templated classes on the server. The server part has to keep track of these created classes and has to remember the types with which the classes has been instantiated. The problem is, that there are around 36 different class-template-combinations that are valid in my application. I'm currently struggling to keep track of these different types in a collection without losing information about my instances.

I'm currently using something like this:

```<code>#include <memory>
#include <type_traits>
#include <vector>

enum class data_type : std::uint8_t {
    type_int = 1,
    type_float,
    type_double
};

enum class class_type : std:: uint8_t {
    type_A = 1,
    type_B
};

struct X {
    virtual data_type get_data_type() = 0;
    virtual class_type get_class_type() = 0;
};

template <typename T>
struct A : X {
    data_type get_data_type() override
    {
        if (std::is_same<T, int>::value) {
            return data_type::type_int;
        } else if (std::is_same<T, float>::value) {
            return data_type::type_float;
        } else if (std::is_same<T, double>::value) {
            return data_type::type_double;
        } else {
            /* ... */
        }
    }

    class_type get_class_type() override
    {
        return class_type::type_A;
    }
};

template <typename T>
struct B : X {
    data_type get_data_type() override
    {
        if (std::is_same<T, int>::value) {
            return data_type::type_int;
        } else if (std::is_same<T, float>::value) {
            return data_type::type_float;
        } else if (std::is_same<T, double>::value) {
            return data_type::type_double;
        } else {
            /* ... */
        }
    }

    class_type get_class_type() override
    {
        return class_type::type_B;
    }
};

struct Storage {

    template <typename T, template <typename> class Class>
    void create() {
        Class<T>* t = new Class<T>();
        _classes.push_back(std::unique_ptr<X>(t));
    }

    std::vector<std::unique_ptr<X>> _classes;
};
</code>```

but I'm wondering if this is the way to go or if there is a more elegant way. Here I would have to always switch through the enums to get the full type out of my Storage class, something like:

```<code>switch(_classes.front()->get_class_type()) {
case class_type::type_A:
{
    switch(_classes.front()->get_data_type()) {
    case data_type::type_int:
    {
         /* I finally know that it is A<int> */
    }
/* ... */
</code>```

Thanks in advance.

答:
You can consider using std::variant and the std::visit pattern

```<code>auto var = std::variant<int, float, double>{};
// assign var to value
std::visit([](auto& value) {
    using Type = std::decay_t<decltype(value)>;
    if constexpr (std::is_same<Type, int>{}) {
        // is an int
    } else if (std::is_same<Type, float>{}) {
        // is float
    } else if (std::is_same<Type, double>{}) {
        // is double
    }
}, var);
</code>```

If the if constexpr looks ugly to you then you can substitute it with a handrolled visitor class as well.

```<code>class Visitor {
public:
    void operator()(int& value) { ... }
    void operator()(float& value) { ... }
    void operator()(double& value) { ... }
};

auto var = std::variant<int, float, double>{};
// assign var to value
std::visit(Visitor{}, var);
</code>```

Body:
I'm currently working on a project where a client part of my application has to be able to create custom templated classes on the server. The server part has to keep track of these created classes and has to remember the types with which the classes has been instantiated. The problem is, that there are around 36 different class-template-combinations that are valid in my application. I'm currently struggling to keep track of these different types in a collection without losing information about my instances.

I'm currently using something like this:

#include <memory>
#include <type_traits>
#include <vector>

enum class data_type : std::uint8_t {
    type_int = 1,
    type_float,
    type_double
};

enum class class_type : std:: uint8_t {
    type_A = 1,
    type_B
};

struct X {
    virtual data_type get_data_type() = 0;
    virtual class_type get_class_type() = 0;
};

template <typename T>
struct A : X {
    data_type get_data_type() override
    {
        if (std::is_same<T, int>::value) {
            return data_type::type_int;
        } else if (std::is_same<T, float>::value) {
            return data_type::type_float;
        } else if (std::is_same<T, double>::value) {
            return data_type::type_double;
        } else {
            /* ... */
        }
    }

    class_type get_class_type() override
    {
        return class_type::type_A;
    }
};

template <typename T>
struct B : X {
    data_type get_data_type() override
    {
        if (std::is_same<T, int>::value) {
            return data_type::type_int;
        } else if (std::is_same<T, float>::value) {
            return data_type::type_float;
        } else if (std::is_same<T, double>::value) {
            return data_type::type_double;
        } else {
            /* ... */
        }
    }

    class_type get_class_type() override
    {
        return class_type::type_B;
    }
};

struct Storage {

    template <typename T, template <typename> class Class>
    void create() {
        Class<T>* t = new Class<T>();
        _classes.push_back(std::unique_ptr<X>(t));
    }

    std::vector<std::unique_ptr<X>> _classes;
};

but I'm wondering if this is the way to go or if there is a more elegant way. Here I would have to always switch through the enums to get the full type out of my Storage class, something like:

switch(_classes.front()->get_class_type()) {
case class_type::type_A:
{
    switch(_classes.front()->get_data_type()) {
    case data_type::type_int:
    {
         /* I finally know that it is A<int> */
    }
/* ... */

Thanks in advance.

Body:
You can consider using std::variant and the std::visit pattern

auto var = std::variant<int, float, double>{};
// assign var to value
std::visit([](auto& value) {
    using Type = std::decay_t<decltype(value)>;
    if constexpr (std::is_same<Type, int>{}) {
        // is an int
    } else if (std::is_same<Type, float>{}) {
        // is float
    } else if (std::is_same<Type, double>{}) {
        // is double
    }
}, var);

If the if constexpr looks ugly to you then you can substitute it with a handrolled visitor class as well.

class Visitor {
public:
    void operator()(int& value) { ... }
    void operator()(float& value) { ... }
    void operator()(double& value) { ... }
};

auto var = std::variant<int, float, double>{};
// assign var to value
std::visit(Visitor{}, var);


问:
neo4jClient create node with dynamic label using paramters
I am building an app that give users the ability to construct there own graphs. I have been using parameters for all queries and creates. But when I want to give users the ability to create a node where they can also Label it anything they want(respecting neo4j restrictions on empty string labels). How would I parameterize this type of transaction?

I tried this:

```<code>.CREATE("(a:{dynamicLabel})").WithParams(new {dynamicLabel = dlabel})...
</code>```

But this yields a syntax error with neo. I am tempted to concatenate, but am worried that this may expose an injection risk to my application.

I am tempted to build up my-own class that reads the intended string and rejects any type of neo syntax, but this would limit my users a bit and I would rather not.

答:
If you are using a Java client, then you can do it like this.

```<code>        Node node = GraphDatabaseService.createNode();

        Label label = new Label() {
            @Override
            public String name() {
                return dynamicLabelVal;
            }
        };

        node.addLabel(label);
</code>```

You can then have a LabelCache which will avoid Label object creation for every node.

Body:
I am building an app that give users the ability to construct there own graphs. I have been using parameters for all queries and creates. But when I want to give users the ability to create a node where they can also Label it anything they want(respecting neo4j restrictions on empty string labels). How would I parameterize this type of transaction?

I tried this:

.CREATE("(a:{dynamicLabel})").WithParams(new {dynamicLabel = dlabel})...

But this yields a syntax error with neo. I am tempted to concatenate, but am worried that this may expose an injection risk to my application.

I am tempted to build up my-own class that reads the intended string and rejects any type of neo syntax, but this would limit my users a bit and I would rather not.

Body:
If you are using a Java client, then you can do it like this.

        Node node = GraphDatabaseService.createNode();

        Label label = new Label() {
            @Override
            public String name() {
                return dynamicLabelVal;
            }
        };

        node.addLabel(label);

You can then have a LabelCache which will avoid Label object creation for every node.


问:
MYSQL multiple like search for locations
I have a large database with over 310 k rows. Each row has the fields :

Country

Region

City

Here is my query - I am using php pdo to query my properties db :

```<code>$sql =  'SELECT * FROM properties
          WHERE ( Country = "'.$searchString.'" OR Region = "'.$searchString.'"
                  OR City = "'.$searchString.'") LIMIT 100';
$stmt = $pdo->query($sql);
</code>```

Now all though this works fine but I know it is messy and resource intensive can anyone explain to me a cleaner faster way of doing this also Indexes confuse me with mysql, should I set an index up for the three columns and what kind of index would you advise.

Any help or pointers would be greatly appreciated

答:
Indexes are not going to help, as you have written the query.  You could write add an index on properties(Country, Region, City) and use a query like this:

```<code>select p.*
from properties p
where country = @searchString
union all
select p.*
from properties p
where region = @searchString and country <> @searchString
union all
select p.*
from properties p
where city = @searchString and region <> @searchString and country <> @searchString;
</code>```

This might help, but often an or query returns so many rows that indexes are not particularly helpful.

Body:
I have a large database with over 310 k rows. Each row has the fields :

Country

Region

City

Here is my query - I am using php pdo to query my properties db :

$sql =  'SELECT * FROM properties
          WHERE ( Country = "'.$searchString.'" OR Region = "'.$searchString.'"
                  OR City = "'.$searchString.'") LIMIT 100';
$stmt = $pdo->query($sql);

Now all though this works fine but I know it is messy and resource intensive can anyone explain to me a cleaner faster way of doing this also Indexes confuse me with mysql, should I set an index up for the three columns and what kind of index would you advise.

Any help or pointers would be greatly appreciated

Body:
Indexes are not going to help, as you have written the query.  You could write add an index on properties(Country, Region, City) and use a query like this:

select p.*
from properties p
where country = @searchString
union all
select p.*
from properties p
where region = @searchString and country <> @searchString
union all
select p.*
from properties p
where city = @searchString and region <> @searchString and country <> @searchString;

This might help, but often an or query returns so many rows that indexes are not particularly helpful.


问:
Hitting urls using threads
I am using threads to hit the urls in an arrayList. Need to store the not working urls in another arraylist. However the list of not-working urls changes everytime. Getting a malformed url exception. This exception occurs even for working urls (When tried hitting them manually). </p>

```<code>public class ThreadTest {

static int i = 0;
static ArrayList<String> arrayOfNotWorking = new ArrayList<>();

public static void main(String[] args) {
    ArrayList<String> arrayOfUrl = new ArrayList<>();

    ThreadTest threadTest = new ThreadTest();
    arrayOfUrl.add("https://www.parkbus.ca");
    arrayOfUrl.add("https://affectingchange.com/projects/fogo-island-");
    arrayOfUrl.add("https://skoll.socialedge.org/?293@@.1ad86d9e");
    arrayOfUrl.add("https://skollsocialedge.org?293@@.1ad86");
    arrayOfUrl.add("https://www.jitabangladesh.com");
    arrayOfUrl.add("https://www.ngobiz.org/picture/File/Social Enterpeuneur-The Case of Definition.pdf");
    arrayOfUrl.add("https://www.mealshare.ca/en/home/");
    arrayOfUrl.add("https://www.oecd.org/cfe/leed/38870491.pdf");
    arrayOfUrl.add("https://doi.org/10.1787/tour-2016-en");
    arrayOfUrl.add("https://www.youtube.com/user/PlaneterraCares");

    try {
        ExecutorService threadPool = Executors.newFixedThreadPool(arrayOfUrl.size());
        for (i = 0; i < arrayOfUrl.size(); i++) {
            threadPool.submit(new Runnable() {
                public void run() {
                    threadTest.hitUrl(arrayOfUrl.get(i));
                }
            });
        }
        threadPool.shutdown();
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        for (String string : arrayOfNotWorking) {
            System.out.println(string);
        }
    } catch (InterruptedException ex) {
        System.out.println(ex.getMessage());
    }
}

public static void hitUrl(String actualUrl) {
    try {
        URL obj = new URL(actualUrl);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        if (responseCode > 199 && responseCode < 400) {
        }
    } catch (Exception ex) {
        arrayOfNotWorking.add(actualUrl);
    }
}
</code>```

<p>}</p>

答:
You have defined notWorkingUrl within the hitUrl method, so each time the method is called the variable gets initialised.

You should define a list of type String in the class, and add the not working URLs to that.

Title: Hitting urls using threads

Body:
I am using threads to hit the urls in an arrayList. Need to store the not working urls in another arraylist. However the list of not-working urls changes everytime. Getting a malformed url exception. This exception occurs even for working urls (When tried hitting them manually).

public class ThreadTest {

static int i = 0;
static ArrayList<String> arrayOfNotWorking = new ArrayList<>();

public static void main(String[] args) {
    ArrayList<String> arrayOfUrl = new ArrayList<>();

    ThreadTest threadTest = new ThreadTest();
    arrayOfUrl.add("https://www.parkbus.ca");
    arrayOfUrl.add("https://affectingchange.com/projects/fogo-island-");
    arrayOfUrl.add("https://skoll.socialedge.org/?293@@.1ad86d9e");
    arrayOfUrl.add("https://skollsocialedge.org?293@@.1ad86");
    arrayOfUrl.add("https://www.jitabangladesh.com");
    arrayOfUrl.add("https://www.ngobiz.org/picture/File/Social Enterpeuneur-The Case of Definition.pdf");
    arrayOfUrl.add("https://www.mealshare.ca/en/home/");
    arrayOfUrl.add("https://www.oecd.org/cfe/leed/38870491.pdf");
    arrayOfUrl.add("https://doi.org/10.1787/tour-2016-en");
    arrayOfUrl.add("https://www.youtube.com/user/PlaneterraCares");

    try {
        ExecutorService threadPool = Executors.newFixedThreadPool(arrayOfUrl.size());
        for (i = 0; i < arrayOfUrl.size(); i++) {
            threadPool.submit(new Runnable() {
                public void run() {
                    threadTest.hitUrl(arrayOfUrl.get(i));
                }
            });
        }
        threadPool.shutdown();
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        for (String string : arrayOfNotWorking) {
            System.out.println(string);
        }
    } catch (InterruptedException ex) {
        System.out.println(ex.getMessage());
    }
}

public static void hitUrl(String actualUrl) {
    try {
        URL obj = new URL(actualUrl);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        if (responseCode > 199 && responseCode < 400) {
        }
    } catch (Exception ex) {
        arrayOfNotWorking.add(actualUrl);
    }
}

}


问:
add one button in shopify site header using shopify app in ROR
I need to insert one button after search icon in shopify sites throgh the shopify app.Give me some suggestions.

Thanks in Advance.

答:
Hopefully you should replace/overwrite your snippets/header.liquid file in your store's theme with the help of Shopify API as below:

In your app, try the below in your root function as:

```<code>header = ShopifyAPI::Asset.find("sections/header.liquid")
header.value # returns the contents of the header.liquid
</code>```

update your header.value using rails sub! as:

```<code>#this will add the button at appropriate place instead `{% endif %}`
header.value.sub!("{% endif %}", "<button type='button'>Click Button</button> {% endif %}")

#do save
header.save
</code>```

Hope this will help you!!

Body:
Hopefully you should replace/overwrite your snippets/header.liquid file in your store's theme with the help of Shopify API as below:

In your app, try the below in your root function as:

header = ShopifyAPI::Asset.find("sections/header.liquid")
header.value # returns the contents of the header.liquid

update your header.value using rails sub! as:

#this will add the button at appropriate place instead `{% endif %}`
header.value.sub!("{% endif %}", "<button type='button'>Click Button</button> {% endif %}")

#do save
header.save

Hope this will help you!!


问:
HttpsUrlconnection accept any certificate when connecting
I am trying to make an app that pins an ssl certificate. I have a class that create a connection the server using HttpsURLConnection. When I connect using a normal internet connection it connects fine. When I use a proxy (mitmproxy) it fails when I don't have the certificate installed. Is there a way to get HttpsURLConnection to accept any SSL certificate.

This is the error that I get when the certificate is not install Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

```<code>protected Boolean doInBackground(Void... params) {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };
    final SSLContext sc;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

    String https_url = "https://www.prisonvoicemail.com/";

    URL url;
    try {
        url = new URL(https_url);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection con = (HttpsURLConnection)url.openConnection();

        JSONObject array = print_https_cert(con);
        try {
            Log.d(LOG_TAG, array.toString(4));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        this.success = true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return this.success;
}

private JSONObject print_https_cert(HttpsURLConnection con){
    BASE64Encoder base64Encoder;
    JSONObject certificateInfo = new JSONObject();

    if(con!=null){
        try {
            System.out.println("Response Code : " + con.getResponseCode());
            System.out.println("Cipher Suite : " + con.getCipherSuite());
            System.out.println("\n");

            try {
                Certificate[] certs = con.getServerCertificates();
                MessageDigest mg = MessageDigest.getInstance("SHa-256");

                Certificate originalCert = certs[0];
                byte[] originalPublicKey = mg.digest(originalCert.getPublicKey().getEncoded());
                base64Encoder = new BASE64Encoder();
                String originalKey = base64Encoder.encode(originalPublicKey);

                //Get ip address
                Document doc = Jsoup.connect("http://checkip.org/").get();
                String ip = doc.getElementById("yourip").select("h1").first().select("span").text();

                try {
                    certificateInfo.put("ip", ip);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                JSONObject certificates = new JSONObject();
                int index = 1;
                if(!originalKey.equals("Z12bL041tx\/0Hb8fNmTsL7ztXex\/02WlawBoMWMFRmc=")){
                    for(Certificate cert : certs){
                        //Data to write to json
                        //Get serial number
                        X509Certificate x509Certificate = (X509Certificate) cert;
                        BigInteger serial = x509Certificate.getSerialNumber();
                        //Get public key in sha-256 base64
                        byte[] publicKey = mg.digest(cert.getPublicKey().getEncoded());
                        base64Encoder = new BASE64Encoder();
                        String key = base64Encoder.encode(publicKey);
                        //getIssuer
                        Principal issuer = x509Certificate.getIssuerDN();

                        JSONObject values = new JSONObject();
                        try {
                            values.put("serial", serial.toString(16));
                            values.put("public-key", key);
                            values.put("issuer", issuer);
                            certificates.put(String.valueOf(index), values);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        index++;
                    }
                }

                try {
                    certificateInfo.put("certificates", certificates);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                for(Certificate cert : certs){
                    byte[] publicKey = mg.digest(cert.getPublicKey().getEncoded());
                    base64Encoder = new BASE64Encoder();
                    String key = base64Encoder.encode(publicKey);
                    X509Certificate x509Certificate = (X509Certificate) cert;
                    BigInteger serial = x509Certificate.getSerialNumber();
                    System.out.println("Cert Public Key: " + key);
                    System.out.println("Cert Serial number: " + serial.toString(16));
                    System.out.println("\n");
                }

            } catch (NoSuchAlgorithmException e){
                e.printStackTrace();
            }
        } catch (IOException e){
            e.printStackTrace();
        }

    }

    return certificateInfo;
}
</code>```

We want to be able to log when a user makes a connection with an invalid certificate. I want it to be able to connect to any certificate without the need for it to be installed. When people use the app I don't want the hackers cert to be install before connecting. I've tried creating a TrustManager but it doesn't work.

答: I figured it out. I was having build issues and the version I was using wasn't the version with the TrustManager.</p>

Body:
I am trying to make an app that pins an ssl certificate. I have a class that create a connection the server using HttpsURLConnection. When I connect using a normal internet connection it connects fine. When I use a proxy (mitmproxy) it fails when I don't have the certificate installed. Is there a way to get HttpsURLConnection to accept any SSL certificate.

This is the error that I get when the certificate is not install Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

protected Boolean doInBackground(Void... params) {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };
    final SSLContext sc;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

    String https_url = "https://www.prisonvoicemail.com/";

    URL url;
    try {
        url = new URL(https_url);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection con = (HttpsURLConnection)url.openConnection();

        JSONObject array = print_https_cert(con);
        try {
            Log.d(LOG_TAG, array.toString(4));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        this.success = true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return this.success;
}

private JSONObject print_https_cert(HttpsURLConnection con){
    BASE64Encoder base64Encoder;
    JSONObject certificateInfo = new JSONObject();

    if(con!=null){
        try {
            System.out.println("Response Code : " + con.getResponseCode());
            System.out.println("Cipher Suite : " + con.getCipherSuite());
            System.out.println("\n");

            try {
                Certificate[] certs = con.getServerCertificates();
                MessageDigest mg = MessageDigest.getInstance("SHa-256");

                Certificate originalCert = certs[0];
                byte[] originalPublicKey = mg.digest(originalCert.getPublicKey().getEncoded());
                base64Encoder = new BASE64Encoder();
                String originalKey = base64Encoder.encode(originalPublicKey);

                //Get ip address
                Document doc = Jsoup.connect("http://checkip.org/").get();
                String ip = doc.getElementById("yourip").select("h1").first().select("span").text();

                try {
                    certificateInfo.put("ip", ip);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                JSONObject certificates = new JSONObject();
                int index = 1;
                if(!originalKey.equals("Z12bL041tx\/0Hb8fNmTsL7ztXex\/02WlawBoMWMFRmc=")){
                    for(Certificate cert : certs){
                        //Data to write to json
                        //Get serial number
                        X509Certificate x509Certificate = (X509Certificate) cert;
                        BigInteger serial = x509Certificate.getSerialNumber();
                        //Get public key in sha-256 base64
                        byte[] publicKey = mg.digest(cert.getPublicKey().getEncoded());
                        base64Encoder = new BASE64Encoder();
                        String key = base64Encoder.encode(publicKey);
                        //getIssuer
                        Principal issuer = x509Certificate.getIssuerDN();

                        JSONObject values = new JSONObject();
                        try {
                            values.put("serial", serial.toString(16));
                            values.put("public-key", key);
                            values.put("issuer", issuer);
                            certificates.put(String.valueOf(index), values);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        index++;
                    }
                }

                try {
                    certificateInfo.put("certificates", certificates);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                for(Certificate cert : certs){
                    byte[] publicKey = mg.digest(cert.getPublicKey().getEncoded());
                    base64Encoder = new BASE64Encoder();
                    String key = base64Encoder.encode(publicKey);
                    X509Certificate x509Certificate = (X509Certificate) cert;
                    BigInteger serial = x509Certificate.getSerialNumber();
                    System.out.println("Cert Public Key: " + key);
                    System.out.println("Cert Serial number: " + serial.toString(16));
                    System.out.println("\n");
                }

            } catch (NoSuchAlgorithmException e){
                e.printStackTrace();
            }
        } catch (IOException e){
            e.printStackTrace();
        }

    }

    return certificateInfo;
}

We want to be able to log when a user makes a connection with an invalid certificate. I want it to be able to connect to any certificate without the need for it to be installed. When people use the app I don't want the hackers cert to be install before connecting. I've tried creating a TrustManager but it doesn't work.


问:
Powerbuilder 7 - Only print header on first page and footer on last page
I need to only print header on the first page and footer on the last page. Please help. Thanks.</p>

答: You could create a group in your DW which would change only as the invoice changes - say on the invoice number.  Move your header information (the stuff you only want to print on the first page of the invoice) into the group band.  Now if you have a multi page invoice the header will only print on the first page.</p>


问:
FolderBrowsingDialog doesn't open the next FolderBrowsingDialog
FolderBrowsingDialog doesnt load the next one. i tried f1 and f2 alone, and it shows me the desktop folder. But when i tried f1&f2 together. only f1 loads

```<code>        public Form1()
    {
        InitializeComponent();

        FolderBrowserDialog f1 = new FolderBrowserDialog();
        FolderBrowserDialog f2 = new FolderBrowserDialog();

        f1.ShowNewFolderButton = true;
        f2.ShowNewFolderButton = true;

        f1.RootFolder = Environment.SpecialFolder.Desktop;
        f2.RootFolder = Environment.SpecialFolder.Desktop;

        //f1.Description = "Source";
        //f2.Description = "Destination";

        string folderPathCopy = string.Empty;
        string folderPathPaste = string.Empty;

        if (f1.ShowDialog() == DialogResult.OK)
        {
            folderPathCopy = f1.SelectedPath;
        }

        if (f2.ShowDialog() == DialogResult.OK)//Debugging stops here
        {
            folderPathPaste = f2.SelectedPath;
        }
    }
</code>```

the problem is, f2 doesnt run.

答:
Move the code into the "Shown" event:</p>

```<code>     public Form1()
      {
         InitializeComponent();
         this.Shown += Form1_Shown;

      }

      private void Form1_Shown( object sender, EventArgs e )
      {
         FolderBrowserDialog f1 = new FolderBrowserDialog();
         FolderBrowserDialog f2 = new FolderBrowserDialog();

         f1.ShowNewFolderButton = true;
         f2.ShowNewFolderButton = true;

         f1.RootFolder = Environment.SpecialFolder.Desktop;
         f2.RootFolder = Environment.SpecialFolder.Desktop;

         //f1.Description = "Source";
         //f2.Description = "Destination";

         string folderPathCopy = string.Empty;
         string folderPathPaste = string.Empty;

         if ( f1.ShowDialog() == DialogResult.OK )
         {
            folderPathCopy = f1.SelectedPath;
         }

         if ( f2.ShowDialog() == DialogResult.OK )//Debugging stops here
         {
            folderPathPaste = f2.SelectedPath;
         }
      }
</code>```

Body:
FolderBrowsingDialog doesnt load the next one. i tried f1 and f2 alone, and it shows me the desktop folder. But when i tried f1&f2 together. only f1 loads

        public Form1()
    {
        InitializeComponent();

        FolderBrowserDialog f1 = new FolderBrowserDialog();
        FolderBrowserDialog f2 = new FolderBrowserDialog();

        f1.ShowNewFolderButton = true;
        f2.ShowNewFolderButton = true;

        f1.RootFolder = Environment.SpecialFolder.Desktop;
        f2.RootFolder = Environment.SpecialFolder.Desktop;

        //f1.Description = "Source";
        //f2.Description = "Destination";

        string folderPathCopy = string.Empty;
        string folderPathPaste = string.Empty;

        if (f1.ShowDialog() == DialogResult.OK)
        {
            folderPathCopy = f1.SelectedPath;
        }

        if (f2.ShowDialog() == DialogResult.OK)//Debugging stops here
        {
            folderPathPaste = f2.SelectedPath;
        }
    }

the problem is, f2 doesnt run.

Body:
Move the code into the "Shown" event:

     public Form1()
      {
         InitializeComponent();
         this.Shown += Form1_Shown;

      }

      private void Form1_Shown( object sender, EventArgs e )
      {
         FolderBrowserDialog f1 = new FolderBrowserDialog();
         FolderBrowserDialog f2 = new FolderBrowserDialog();

         f1.ShowNewFolderButton = true;
         f2.ShowNewFolderButton = true;

         f1.RootFolder = Environment.SpecialFolder.Desktop;
         f2.RootFolder = Environment.SpecialFolder.Desktop;

         //f1.Description = "Source";
         //f2.Description = "Destination";

         string folderPathCopy = string.Empty;
         string folderPathPaste = string.Empty;

         if ( f1.ShowDialog() == DialogResult.OK )
         {
            folderPathCopy = f1.SelectedPath;
         }

         if ( f2.ShowDialog() == DialogResult.OK )//Debugging stops here
         {
            folderPathPaste = f2.SelectedPath;
         }
      }


问:
Java and Python Together in Single Google App Engine Project
I currently have a Java application running on Google App Engine, but I want to add the features that the Python module's SearchableModel provides (for search features of course).  Is it possible to run python code in the same project as Java code, just under a different version?  If not, could they be two separate apps (current Java app and a new Python-based search app) running against a single datastore, but I don't think that is possible.</p>

答:
It is possible to run Python and Java applications on different versions.

From:

Last but not least: remember that you can have different version of your app (using the same datastore) some of which are implemented with the Python runtime, some with the Java runtime, and you can access versions that differ from the "default/active" one with explicit URLs.


问:
Name does not exist in the current context
So, I'm working on this project between my laptop and my desktop.

The project works on the laptop, but now having copied the updated source code onto the desktop, I have over 500 errors in the project, all of them are...

The name  does not exist in the current context

Here's one example...

Jobs.aspx

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Members/Members.master" AutoEventWireup="true" CodeFile="Jobs.aspx.cs" Inherits="Members_Jobs" %>

<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" TagPrefix="aj" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:UpdatePanel runat="server" ID="upJobs">
        <ContentTemplate>
            <!-- page content goes here -->
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>
</code>```

Jobs.aspx.cs

```<code>public partial class Members_Jobs : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadJobs();
            gvItems.Visible = false;
            loadComplexes();
            loadBusinesses();
            loadSubcontractors();
            loadInsurers();

            pnlCallback.Visible = false;
            pnlInsurer.Visible = false;
        }
    }

    // more goes down here
}
</code>```

Here's a sample of the designer.cs file...

```<code>namespace stman.Members {

    public partial class Jobs {

        /// <summary>
        /// upJobs control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel upJobs;
    }
}
</code>```

I know this error means that the control being referenced generally doesn't exist or is not a part of the class that's referencing it, but as far as I can see, that isn't the case here.

Can anyone provide some insight?

答:
I had this problem in my main project when I referenced a dll file.

The problem was that the main project that referenced the dll was targeting a lower framework version than that of the dll.

So I upped my target framework version (Right-click project -> Application -> Target framework) and the error disappeared.

Body:
So, I'm working on this project between my laptop and my desktop.

The project works on the laptop, but now having copied the updated source code onto the desktop, I have over 500 errors in the project, all of them are...

The name  does not exist in the current context

Here's one example...

Jobs.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Members/Members.master" AutoEventWireup="true" CodeFile="Jobs.aspx.cs" Inherits="Members_Jobs" %>

<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" TagPrefix="aj" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:UpdatePanel runat="server" ID="upJobs">
        <ContentTemplate>

        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

Jobs.aspx.cs

public partial class Members_Jobs : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadJobs();
            gvItems.Visible = false;
            loadComplexes();
            loadBusinesses();
            loadSubcontractors();
            loadInsurers();

            pnlCallback.Visible = false;
            pnlInsurer.Visible = false;
        }
    }

    // more goes down here
}

Here's a sample of the designer.cs file...

namespace stman.Members {

    public partial class Jobs {

        ///
        /// upJobs control.
        ///
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel upJobs;
    }
}

I know this error means that the control being referenced generally doesn't exist or is not a part of the class that's referencing it, but as far as I can see, that isn't the case here.

Can anyone provide some insight?


问:
Calling method Design in Java
I have one interface named HasDescription

```<code>public interface HasDescription {

    String getDescription();

    void setDescription(String description);
}
</code>```

It has getter and setter method declarations.

I have another abstract class called ResidentialProperty that implements this interface.

```<code>public abstract class ResidentialProperty
        extends AbstractProperty
        implements HasDescription {
    .....
    private String description;

    @Override
    public String getDescription() {
        return description;
    }

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

}
</code>```

I have another class called Flat. In this class, i have delegated one descriptionSupportinstance. My thought is that, using this instance, i want to call ResidentialProperty's getter and setter method. I am coding this DescriptionSupport. Please assist me how i can do this?

```<code>public class Flat
extends ResidentialProperty {
 private final DescriptionSupport descriptionSupport = new DescriptionSupport();
 @Override
 public String getDescription() {
  return descriptionSupport.getDescription(this);
 }

 @Override
 public void setDescription(String description) {
  descriptionSupport.setDescription(this, description);
 }
}

public class DescriptionSupport {
 public < T extends HasDescription > String getDescription(T property) {
  //i want to call ResidentialProperty's getDescription method

 }

 public < T extends HasDescription > void setDescription(T property, String description) {
  //i want to call ResidentialProperty's setDescription method
 }
}
</code>```

答:
I'm not sure I understand what You're trying to do, but You could do something like this:</p>

```<code>public class Flat
        extends ResidentialProperty {

    private final DescriptionSupport descriptionSupport = new DescriptionSupport();
    private final HasDescription superDesc = new HasDescription() {
        @Override
        public String getDescription() {
            return getSuperDescription();
        }

        @Override
        public void setDescription(String description) {
            setSuperDescription(description);
        }
    };

    @Override
    public String getDescription() {
        return descriptionSupport.getDescription(superDesc);
    }

    @Override
    public void setDescription(String description) {
        descriptionSupport.setDescription(superDesc, description);
    }

    private String getSuperDescription() {
        return super.getDescription();
    }

    private void setSuperDescription(String description) {
        super.setDescription(description);
    }
}

public class DescriptionSupport {
    public < T extends HasDescription> String getDescription(T property) {
        return property.getDescription();
    }

    public < T extends HasDescription> void setDescription(T property, String description) {
        property.setDescription(description);
    }
}
</code>```

Title: Calling method Design in Java

Body:
I have one interface named HasDescription

public interface HasDescription {

    String getDescription();

    void setDescription(String description);
}

It has getter and setter method declarations.

I have another abstract class called ResidentialProperty that implements this interface.

public abstract class ResidentialProperty
        extends AbstractProperty
        implements HasDescription {
    .....
    private String description;

    @Override
    public String getDescription() {
        return description;
    }

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

}

I have another class called Flat. In this class, i have delegated one descriptionSupportinstance. My thought is that, using this instance, i want to call ResidentialProperty's getter and setter method. I am coding this DescriptionSupport. Please assist me how i can do this?

public class Flat
extends ResidentialProperty {
 private final DescriptionSupport descriptionSupport = new DescriptionSupport();
 @Override
 public String getDescription() {
  return descriptionSupport.getDescription(this);
 }

 @Override
 public void setDescription(String description) {
  descriptionSupport.setDescription(this, description);
 }
}

public class DescriptionSupport {
 public < T extends HasDescription > String getDescription(T property) {
  //i want to call ResidentialProperty's getDescription method

 }

 public < T extends HasDescription > void setDescription(T property, String description) {
  //i want to call ResidentialProperty's setDescription method
 }
}

Body:
I'm not sure I understand what You're trying to do, but You could do something like this:

public class Flat
        extends ResidentialProperty {

    private final DescriptionSupport descriptionSupport = new DescriptionSupport();
    private final HasDescription superDesc = new HasDescription() {
        @Override
        public String getDescription() {
            return getSuperDescription();
        }

        @Override
        public void setDescription(String description) {
            setSuperDescription(description);
        }
    };

    @Override
    public String getDescription() {
        return descriptionSupport.getDescription(superDesc);
    }

    @Override
    public void setDescription(String description) {
        descriptionSupport.setDescription(superDesc, description);
    }

    private String getSuperDescription() {
        return super.getDescription();
    }

    private void setSuperDescription(String description) {
        super.setDescription(description);
    }
}

public class DescriptionSupport {
    public < T extends HasDescription> String getDescription(T property) {
        return property.getDescription();
    }

    public < T extends HasDescription> void setDescription(T property, String description) {
        property.setDescription(description);
    }
}


问:
Method generalization in Scala
I tried to generalize a method to provide a type safe API as follows:

```<code>abstract class AbstractCommand {
  type T = this.type
  def shuffler(s: T => Seq[AbstractCommand])
}

class TestCommand extends AbstractCommand {
  override def shuffler(s: (TestCommand) => Seq[AbstractCommand]): Unit = ??? //error
}
</code>```

I wanted the expected type of the function argument to be the most specific in this hierarchy. But it didn't work.

Is there a way to do something like that in Scala without introducing some helper type parameters?

答:
This looks like a perfect use-case for F-Bounded Polymorphism:

```<code>abstract class AbstractCommand[T <: AbstractCommand[T]] {
  self: T =>
  def shuffler(s: T => Seq[AbstractCommand[T]])
}

class TestCommand extends AbstractCommand[TestCommand] {
  override def shuffler(s: (TestCommand) => Seq[AbstractCommand[TestCommand]]): Unit = ???
}
</code>```

And with a type member instead of a type parameter (using the example provided by Attempting to model F-bounded polymorphism as a type member in Scala):

```<code>abstract class AbstractCommand { self =>
  type T >: self.type <: AbstractCommand
}

class TestCommand extends AbstractCommand {
  type T = TestCommand
}

class OtherCommand extends AbstractCommand {
  type T = OtherCommand
}
</code>```

Title: Method generalization in Scala

Body:
I tried to generalize a method to provide a type safe API as follows:

abstract class AbstractCommand {
  type T = this.type
  def shuffler(s: T => Seq[AbstractCommand])
}

class TestCommand extends AbstractCommand {
  override def shuffler(s: (TestCommand) => Seq[AbstractCommand]): Unit = ??? //error
}

I wanted the expected type of the function argument to be the most specific in this hierarchy. But it didn't work.

Is there a way to do something like that in Scala without introducing some helper type parameters?

Body:
This looks like a perfect use-case for F-Bounded Polymorphism:

abstract class AbstractCommand[T <: AbstractCommand[T]] {
  self: T =>
  def shuffler(s: T => Seq[AbstractCommand[T]])
}

class TestCommand extends AbstractCommand[TestCommand] {
  override def shuffler(s: (TestCommand) => Seq[AbstractCommand[TestCommand]]): Unit = ???
}

And with a type member instead of a type parameter (using the example provided by Attempting to model F-bounded polymorphism as a type member in Scala):

abstract class AbstractCommand { self =>
  type T >: self.type <: AbstractCommand
}

class TestCommand extends AbstractCommand {
  type T = TestCommand
}

class OtherCommand extends AbstractCommand {
  type T = OtherCommand
}


问:
Transfer iOS app from one Apple account to other
I want to transfer my iOS app from one apple store account to other. For both accounts I have team agent role and I have logged in with same access details.

At documentation, I found this article and I want to follow similar steps from my side - Transferring and Deleting Apps

But at above reference link, I found this option/link - Transfer App:

When I actually logged into my account, I can't able to find this kind of option to move app from one account to another. Here is screenshot for my account:

So actually where is the app transfer option?

答: Your App status says "Prepare for submission" and there is no published version so you have to get your app published first and as mentioned in the Apple's documentation "The app should have at least one published version for transfer".


问:
TChart with TKnobGauge creates shifted labels at runtime
Following code creates knob with labels shifted to the right:

```<code>procedure TForm1.FormShow(Sender: TObject);
begin
  _chart := TChart.Create(Self);
  _chart.Parent := Self;
  _chart.Align := alClient;

  _knob := TKnobGauge.Create(Self);
  _knob.ParentChart := _chart;
  _knob.RotateLabels := False;
  _knob.RotationAngle := 180;
end;
</code>```

The same code as DFM produces the right knob.

What could be wrong?

TeeChart Pro v2015.16.150901 32bit VCL

Delphi 10

答:
There is a bug in TChart. When I set

```<code>_chart.Title.Text.Text := 'Some title';
</code>```

labels are on their places.

When I do

```<code>_chart.Title.Text.Text := '';
</code>```

or

```<code>_chart.Title.Visible := False;
</code>```

they are shifted.

The reason why the same code in DFM produced the right knob is that the visual designer extends my minimal chart declaration by adding several properties automatically. Among these properties was a chart title too. It is automatically filled by "TChart" text.

Body:
Following code creates knob with labels shifted to the right:

procedure TForm1.FormShow(Sender: TObject);
begin
  _chart := TChart.Create(Self);
  _chart.Parent := Self;
  _chart.Align := alClient;

  _knob := TKnobGauge.Create(Self);
  _knob.ParentChart := _chart;
  _knob.RotateLabels := False;
  _knob.RotationAngle := 180;
end;

The same code as DFM produces the right knob.

What could be wrong?

TeeChart Pro v2015.16.150901 32bit VCL

Delphi 10

Body:
There is a bug in TChart. When I set

_chart.Title.Text.Text := 'Some title';

labels are on their places.

When I do

_chart.Title.Text.Text := '';

or

_chart.Title.Visible := False;

they are shifted.

The reason why the same code in DFM produced the right knob is that the visual designer extends my minimal chart declaration by adding several properties automatically. Among these properties was a chart title too. It is automatically filled by "TChart" text.


问:
Return the contents of an image in php file?
I really do not know any PHP but I'd love to do one simple thing:

I access a php page from within a  and I'd like to have an image returned from another URL.

I came up with:

```<code><?php
header('Content-Type: image/png');
readfile('i' . rand(1,3) . '.png');
exit;
</code>```

And it works:

Avatar selection http://vercas.webuda.com/img.php?.png

(Reload the page a few times!)

答:
Check out readfile().

The basic idea is you send the appropriate MIME type headers (using header()) then deliver the file contents using readfile().

For example

```<code><?php
// myhumbleimage.php

// Do whatever myhumbleimage.php does before the image is delivered

header('Content-Type: image/jpeg');
readfile('path/or/url/of/image/file.jpg');
exit;
</code>```

Body:
I really do not know any PHP but I'd love to do one simple thing:

I access a php page from within a  and I'd like to have an image returned from another URL.

I came up with:

<?php
header('Content-Type: image/png');
readfile('i' . rand(1,3) . '.png');
exit;

And it works:

Avatar selection http://vercas.webuda.com/img.php?.png

(Reload the page a few times!)

Body:
Check out readfile().

The basic idea is you send the appropriate MIME type headers (using header()) then deliver the file contents using readfile().

For example

<?php
// myhumbleimage.php

// Do whatever myhumbleimage.php does before the image is delivered

header('Content-Type: image/jpeg');
readfile('path/or/url/of/image/file.jpg');
exit;


问:
Sort by date ASC in qweb report odoo
I want sort data in my qweb report by date asc.

My example:

<t t-foreach="doc.line_ids" t-as="o">

</t>
```

答:
Hello user_odoo,

sorted()

returns a recordset sorted by the provided key function. If no key is provided, use the model's default sort order:

```<code>#sort records by name
records.sorted(key=lambda r: r.name)
</code>```

sorted(key=None, reverse=False)

Return the recordset self ordered by key.

Parameters

key -- either a function of one argument that returns a comparison key for each record, or None, in which case records are ordered according the default model's order

reverse -- if True, return the result in reverse order

Your problem solution is below code try,

```<code><tr t-foreach="doc.order_line.sorted(key=lambda record: record.name, reverse=False)" t-as="ol">
    <td class="text-right">
        <span t-field="ol.name"/>
    </td>
    ...
</tr>
</code>```

I hope my answer is helpful.

If any query so comments, Please.

Title: Sort by date ASC in qweb report odoo

Body:
Hello user_odoo,

sorted()

returns a recordset sorted by the provided key function. If no key is provided, use the model's default sort order:

#sort records by name
records.sorted(key=lambda r: r.name)

sorted(key=None, reverse=False)

Return the recordset self ordered by key.

Parameters

key -- either a function of one argument that returns a comparison key for each record, or None, in which case records are ordered according the default model's order

reverse -- if True, return the result in reverse order

Your problem solution is below code try,

<tr t-foreach="doc.order_line.sorted(key=lambda record: record.name, reverse=False)" t-as="ol">
    <td class="text-right">
        <span t-field="ol.name"/>
    </td>
    ...
</tr>

I hope my answer is helpful.

If any query so comments, Please.


问:
map values to a specific range
Let say we have some angular values from -inf to +inf as input.

I'd like to map them between only -180 and +180.

How could I properly achieve that?

Here's what I've found so far:

```<code>(i-180)%360-180
</code>```

It works fine, but it maps +180 to -180 which I would like to be +180->+180.

Technically it's the same for my purpose so it's not a big deal, but it would be aesthetically better.

I'm working with Python but it doesn't really matter here.

答:
If you don't value mathematical aestheticism as much, I think this could work</p>

```<code>def f(i):
    x = i % 360
    if x > 180:
        x -= 360
    elif x == 180 and i < 0:
        x = -x
    return x
</code>```

Title: map values to a specific range

Body:
Let say we have some angular values from -inf to +inf as input.

I'd like to map them between only -180 and +180.

How could I properly achieve that?

Here's what I've found so far:

(i-180)%360-180

It works fine, but it maps +180 to -180 which I would like to be +180->+180.

Technically it's the same for my purpose so it's not a big deal, but it would be aesthetically better.

I'm working with Python but it doesn't really matter here.

Body:
If you don't value mathematical aestheticism as much, I think this could work

def f(i):
    x = i % 360
    if x > 180:
        x -= 360
    elif x == 180 and i < 0:
        x = -x
    return x


问:
Is there a way to ignore a single FindBugs warning?
With PMD, if you want to ignore a specific warning, you can use // NOPMD to have that line be ignored.

Is there something similar for FindBugs?

答:
As others Mentioned, you can use the @SuppressFBWarnings Annotation.
If you don't want or can't add another Dependency to your code, you can add the Annotation to your Code yourself, Findbugs dosn't care in which Package the Annotation is.

```<code>@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
    /**
     * The set of FindBugs warnings that are to be suppressed in
     * annotated element. The value can be a bug category, kind or pattern.
     *
     */
    String[] value() default {};

    /**
     * Optional documentation of the reason why the warning is suppressed
     */
    String justification() default "";
}
</code>```

Source: https://sourceforge.net/p/findbugs/feature-requests/298/#5e88

Body:
As others Mentioned, you can use the @SuppressFBWarnings Annotation.
If you don't want or can't add another Dependency to your code, you can add the Annotation to your Code yourself, Findbugs dosn't care in which Package the Annotation is.

@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
    /**
     * The set of FindBugs warnings that are to be suppressed in
     * annotated element. The value can be a bug category, kind or pattern.
     *
     */
    String[] value() default {};

    /**
     * Optional documentation of the reason why the warning is suppressed
     */
    String justification() default "";
}

Source: https://sourceforge.net/p/findbugs/feature-requests/298/#5e88


问:
[orientdb]: get the current user when authenticating with tokens
How can i get the rid of the current user (OUser) via the binary api. I am using the inbuilt token based authentication.
I would expect two approaches:

a function like currentUserRID() or something. I looked in the documentation but found nothing.

decrypting the token to unlock the userId/name. I tried this approach but couldn't manage to. I looked here: https://github.com/orientechnologies/orientdb/issues/2229 and also https://groups.google.com/forum/#!topic/orient-database/6sUfSAd4LXo

答:
I find your post just now, may be is too late but you can do like this: </p>

<hr>

```<code>OServer server = OServerMain.create(); //  for exemple

ODatabaseDocumentTx db = new ODatabaseDocumentTx(BDDURL).open("admin","admin"); // admin is juste for this exemple

OTokenHandlerImpl handler = new OTokenHandlerImpl(server);

OToken tok = handler.parseWebToken(yourtoken);

OUser user =  tok.getUser(db);
</code>```

Body:
I find your post just now, may be is too late but you can do like this:

OServer server = OServerMain.create(); //  for exemple

ODatabaseDocumentTx db = new ODatabaseDocumentTx(BDDURL).open("admin","admin"); // admin is juste for this exemple

OTokenHandlerImpl handler = new OTokenHandlerImpl(server);

OToken tok = handler.parseWebToken(yourtoken);

OUser user =  tok.getUser(db);


问:
What is the difference between componentWillMount and componentDidMount in ReactJS?
I looked at Facebook's documentation at (React.Component)  and it mentions how componentWillMount is invoked on the client/server whereas componentDidMount is invoked only on the client. What does componentWillMount do to the server?

答:
componentWillMount is done before the INITIAL render of a component, and is used to assess props and do any extra logic based upon them (usually to also update state), and as such can be performed on the server in order to get the first server side rendered markup.

componentDidMount is performed AFTER the initial render when the DOM has been updated (but crucially BEFORE this DOM update is painted to the browser, allowing you to do all kinds of advanced interactions with the DOM itself). This of course can only happen in the browser itself and so does not occur as part of SSR, as the server can only generate markup and not the DOM itself, this is done after it gets sent to the browser if using SSR

Advanced interactions with the DOM you say? Whaaaat??... Yep - at this point because the DOM has been updated (but the user has not seen the update in browser yet) it is possible to intercept actual painting to the screen by using window.requestAnimationFrame and then do things like measure the actual DOM elements that will be output, to which you can perform further state changes, super useful for example animating to a height of an element that has unknown variable length contents (as you can now measure the contents and assign a height to the animation), or to avoid flash of content scenarios during some state change.

Be very careful though to guard state changes in any componentDid... as otherwise can cause an infinite loop because a state change will also cause a re-render, and hence another componentDid... and on and on and on