问:
Missing or invalid signature in iOS
I have not found any functional solution, between a great number of suggestion on internet. I don't know exactly where and when it stopped to work, but I have an app at Apple Store that is working fine and it is in the 1.7 version. One month ago, I have tried to implement Push Notification and, to this tool works, I have to create and manipulate some certificates (Apple Developer certificates, Keychain Access, etc). After that, when I try to upload a new version to Apple Store using Xcode, I receive the message “Upload Successful”. Some minutes after this, I receive this message in my email:

Dear developer,

We have discovered one or more issues with your recent delivery for "Habilidades Médicas". To process your delivery, the following issues must be corrected:

Missing or invalid signature -
  The bundle 'com.IvanSinigagliaApps.ChkList' at bundle path 'Payload/HabMed.app' is not signed using an Apple submission certificate.

Once these issues have been corrected, you can then redeliver the corrected binary. Regards, The App Store team”

I really don`t know what I did. Maybe, I can have deleted a key (keychain) or deleted a certificate or both. All the posts I have found about “Missing or Invalid Signature” didn’t work for me; many don't push me to my issue and many other are out of date for Xcode 8.3. I will post some screens with some doubts I have to show most information I can and I hope they can work as clues to help me to fix it.

Fig 01: My Keychain Access: I can found to Certificates: 1) iPhone Developer: QRL…, and 2) iPhone Distribution: C3D….

Fig 02: Apple Developer Provisioning Profiles:

Fig 03: iOs Certificates

Fig 04: Xcode (Certificate iPhone Developer QRL… ) ???

Fig 05: Xcode: even when manual provisioning is set up (C3D…) it doesn’t work.

Fig 06: Uploading App (Signing identity Distribution C3D…

Fig 07: Uploading (C3D…)

Fig 08: Upload Successful

UPDATE #1
This is happening the same way to my 4 apps, that were loading fine before.

Still not working, but after following the instructions at Apple Developer Troubleshotings technical Note TN2318, section: Resolving Signature Verification Failure, I run the Terminal with these instructions:

codesign --verify -vvvv -R='anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.1] exists and (certificate leaf[field.1.2.840.113635.100.6.1.2] exists or certificate leaf[field.1.2.840.113635.100.6.1.4] exists)' /path/to/the.app

I receive this message: code object is not signed at all

Now, I will try to go on this clue.

答:
Yes, it is done, after a lot of hard work.
I have a great help from Apple Developer technical Support and to short this issue what I did was trying to fix it editing my certificates. As the problems involved all my apps, it should be something with the certificates. So, the guy from Apple, John, told me to think about this information:

I see they were issuing an revoking their certificates throughout May
  and created the latest Certificate on June 1st. It is currently the
  only active certificate. When a Distribution/Development Cert is
  revoked, the associated provisioning profiles are invalidated and the
  apps will stop functioning. This is the expected behavior. Apps
  distributed via the App Store are not subject to this behavior. Only
  apps distributed using the Ad-Hoc distribution method.

So I went to my certificates, at Apple Developer site, and edited those that I had just revoked and edited them again. A new one was created for this particular app and I have downloaded it to my machine. I have done a new upload and now everything is working fine again, with all apps.

There was a big confusion with all my certificates and with all my apps that. This confusion came to create this issue. Now I have reorganized all this stuff and everything is fine.

That's my lesson from this issue: keep all your work organized.

I really hope someone with the same issue can fix them after reading all this post or at least find an orientation.

Thank you Apple Developer Support and everybody who has read this.

Title: Missing or invalid signature in iOS


来源: stackexchange

问:
Testing JNDI Spring Websphere Outside the Container
I have successfully tested some DAO outside a weblogic server by looking up the datasource information through jndi. I have search for a similar option with websphere and have to yet come accross a solution that does not involve hardcoding the username and password in some location within the application or something similar. Right now my jndi settings look like this inside spring:

```
<bean id="applicationServerEnviromentProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties"><props>
<prop key="java.naming.factory.initial">com.ibm.websphere.naming.WsnInitialContextFactory</prop>
<prop key="java.naming.provider.url">iiop://localhost:2809</prop>
</props>
</property>
</bean>

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName"><value>PeopleAppDS</value></property>
        <property name="jndiEnvironment"><ref local="applicationServerEnviromentProperties"/></property>
    </bean>
```

I have Tested the jndi connection and it is working when the application is loaded on to websphere. I would like to be able to test the daos inside eclipse for instance before the app is loaded. Any help would be much appreciated.

Here are the details for the test case.

-------BaseTestCase.java--------------------

```<code>import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"file:data-access-config.xml"})
public class BaseTestCase {

}
</code>```

-----PersonDaoTest.java----------------

```<code>import static org.junit.Assert.assertNotNull;

import java.util.List;<br>

import org.junit.Test;<br>
import org.springframework.beans.factory.annotation.Autowired;

import ....dao.PersonDao;<br>
import ....domain.Person;<br>

public class PersonDaoTest extends BaseTestCase {

    @Autowired
    private PersonDao personDao;

    @Test
    public void findByName() {
        List<Person>  people = personDao.listByName("j%", false, "userId");
        assertNotNull(people);
    }
}
</code>```

答: The right way to do it is to have a JNDI data source with a DriverManagerDataSource default.  If you run in the container, Spring will use the named data source; if the lookup fails, it'll use the non-JNDI data source.  </p>

ContentLicense: CC BY-SA 3.0

Body:
I have successfully tested some DAO outside a weblogic server by looking up the datasource information through jndi. I have search for a similar option with websphere and have to yet come accross a solution that does not involve hardcoding the username and password in some location within the application or something similar. Right now my jndi settings look like this inside spring:

<bean id="applicationServerEnviromentProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties"><props>
<prop key="java.naming.factory.initial">com.ibm.websphere.naming.WsnInitialContextFactory</prop>
<prop key="java.naming.provider.url">iiop://localhost:2809</prop>
</props>
</property>
</bean>

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName"><value>PeopleAppDS</value></property>
        <property name="jndiEnvironment"><ref local="applicationServerEnviromentProperties"/></property>
    </bean>

I have Tested the jndi connection and it is working when the application is loaded on to websphere. I would like to be able to test the daos inside eclipse for instance before the app is loaded. Any help would be much appreciated.

Here are the details for the test case.

-------BaseTestCase.java--------------------

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"file:data-access-config.xml"})
public class BaseTestCase {

}

-----PersonDaoTest.java----------------

import static org.junit.Assert.assertNotNull;

import java.util.List;

import org.junit.Test;

import org.springframework.beans.factory.annotation.Autowired;

import ....dao.PersonDao;

import ....domain.Person;

public class PersonDaoTest extends BaseTestCase {

    @Autowired
    private PersonDao personDao;

    @Test
    public void findByName() {
        List<Person>  people = personDao.listByName("j%", false, "userId");
        assertNotNull(people);
    }
}

ContentLicense: CC BY-SA 2.5


问:
Error while compiling a C++ application on a raspberry pi
I would like to ask where does this error come from:

```<code>c++: internal compiler error: Killed (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <https://github.com/archlinuxarm/PKGBUILDs/issues> for instructions.
CMakeFiles/supnsa_parser.dir/build.make:77: recipe for target 'CMakeFiles/supnsa_parser.dir/src/helper.cpp.o' failed
make[2]: *** [CMakeFiles/supnsa_parser.dir/src/helper.cpp.o] Error 4
CMakeFiles/Makefile2:60: recipe for target 'CMakeFiles/supnsa_parser.dir/all' failed
make[1]: *** [CMakeFiles/supnsa_parser.dir/all] Error 2
Makefile:76: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

I'm getting this on my raspberry pi when I launch the compilation of my C++ application.
Where does it come from? How can I solve this? Thank you

答:
Usually Killed message during compilation indicates out of memory issue as most of the compilation processes requires higher amount of memory, so you should either increase it (if you can, check with free -m or top command), or another solution is to create a swap file and re-run compilation again.

See also: Out Of Memory Management in Linux Kernel.

Body:
I would like to ask where does this error come from:

c++: internal compiler error: Killed (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <https://github.com/archlinuxarm/PKGBUILDs/issues> for instructions.
CMakeFiles/supnsa_parser.dir/build.make:77: recipe for target 'CMakeFiles/supnsa_parser.dir/src/helper.cpp.o' failed
make[2]: *** [CMakeFiles/supnsa_parser.dir/src/helper.cpp.o] Error 4
CMakeFiles/Makefile2:60: recipe for target 'CMakeFiles/supnsa_parser.dir/all' failed
make[1]: *** [CMakeFiles/supnsa_parser.dir/all] Error 2
Makefile:76: recipe for target 'all' failed
make: *** [all] Error 2

I'm getting this on my raspberry pi when I launch the compilation of my C++ application.
Where does it come from? How can I solve this? Thank you


问:
What does "⌨" mean as an Intellij keyboard shortcut?
In the Mac docs for IntelliJ Idea they use the keyboard icon (⌨) for some of the keyboard shortcuts. It implies one should hit all the keys, but on usb inputs you can only press six keys simultaneously (and this is the case on current Apple laptops).

Joking aside, how do you translate the following into plain English instructions?

⌥⌘⌨ *, 1

See an example in the docs here. Make sure to have your keymap set to Mac OS X (10.5+) (do this in the upper right hand corner)

答:
Apparently, it indicates that the symbol is on the NumPad section of the keyboard:

Meta+Alt+NumPad *, 1

Press the first 3 keys together, release them, then press 1.

⌨ (keyboard) emoji is a weird choice for NumPad and there is an open request to change it back to NumPad, feel free to vote.


问:
unexpected token error when using onclick
this is my code

```<code>  const products = productArray.map(product =>
`
<tr>
  <td>${product.id}</td>
  <td>${product.type}</td>
  <td>${product.price}</td>
  <td><button onclick="${() => console.log('hello world')}">Examine</button></td>
</tr>
`
  );
  return tableBody.innerHTML = products.join('');
</code>```

I just don't get why I'm getting this unexpected token error, that points to the html. I'm pretty sure It's a very stupid but I just cannot get where it is.

答:
I recommend You to use clientside templating engine to avoid such problems. For example mustachejs.

But about fix (try this one):

const tableBody = document.getElementById('productsTable');

const productArray = [
  {id: 1, type: 'something', price: 100},
  {id: 2, type: 'samething', price: 120}
];
const products = productArray.map(product =>
`

  ${product.id}
  ${product.type}
  ${product.price}
  <button onclick="(() => {alert('${product.id} ${product.type}');})()">Examine</button>

`
  );
tableBody.innerHTML = products.join('');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="productsTable">
</table></code>```

Body:
this is my code

  const products = productArray.map(product =>
`

  ${product.id}
  ${product.type}
  ${product.price}
  <button onclick="${() => console.log('hello world')}">Examine</button>

`
  );
  return tableBody.innerHTML = products.join('');

I just don't get why I'm getting this unexpected token error, that points to the html. I'm pretty sure It's a very stupid but I just cannot get where it is.

Body:
I recommend You to use clientside templating engine to avoid such problems. For example mustachejs.

But about fix (try this one):

const tableBody = document.getElementById('productsTable');

const productArray = [
  {id: 1, type: 'something', price: 100},
  {id: 2, type: 'samething', price: 120}
];
const products = productArray.map(product =>
`
<tr>
  <td>${product.id}</td>
  <td>${product.type}</td>
  <td>${product.price}</td>
  <td><button onclick="(() => {alert('${product.id} ${product.type}');})()">Examine</button></td>
</tr>
`
  );
tableBody.innerHTML = products.join('');

<table id="productsTable">
</table>


问:
edit associated model by input form?
```<code>Order has_many jobs
Job belongs to order
</code>```

And I want to edit attributes of @job.order:

```<code><% order = @job.order %>
<%= simple_form_for [@job, order],
  url: job_path(@job),
  method: :put,
  remote: true do |f| %>
    <%= f.input :order_status, input_html: {class: 'form-control'} %>
  (...)
<% end %>
</code>```

any way to do it by just using input in simple form?

答:
You can use the excellent Cocoon gem https://github.com/nathanvda/cocoon to manage nested relationships, including the ability to easily add new nested relationships.

```<code>class Job < ActiveRecord::Base
    has_many :orders
    accepts_nested_attributes_for :orders, reject_if: :all_blank, allow_destroy: true
end

class Order < ActiveRecord::Base
    belongs_to :job
end
</code>```

Note the pluralization.

_form.html.erb*

```<code><%= form_for @job do |f| %>
  <%= f.label :job_name %>
  <%= f.text_field :name %>
  <div id='order'>
    <%= f.fields_for :orders do |order| %>
       <%= render 'order_fields', f: order %>
    <% end %>
    <div class='links'>
       <%= link_to_add_association 'add order', f, :orders %>
    </div>
   <%= f.submit %>
 <% end %>
</code>```

_order_fields.html.erb partial

```<code><div class='nested-fields'>
   <%= f.label :order_name %>
   <%= f.text_field :order_name %>
</div>
<%= link_to_remove_association "remove order", f %>
</code>```

Title: edit associated model by input form?

Body:
Order has_many jobs
Job belongs to order

And I want to edit attributes of @job.order:

<% order = @job.order %>
<%= simple_form_for [@job, order],
  url: job_path(@job),
  method: :put,
  remote: true do |f| %>
    <%= f.input :order_status, input_html: {class: 'form-control'} %>
  (...)
<% end %>

any way to do it by just using input in simple form?

Body:
You can use the excellent Cocoon gem https://github.com/nathanvda/cocoon to manage nested relationships, including the ability to easily add new nested relationships.

class Job < ActiveRecord::Base
    has_many :orders
    accepts_nested_attributes_for :orders, reject_if: :all_blank, allow_destroy: true
end

class Order < ActiveRecord::Base
    belongs_to :job
end

Note the pluralization.

_form.html.erb*

<%= form_for @job do |f| %>
  <%= f.label :job_name %>
  <%= f.text_field :name %>
  <div id='order'>
    <%= f.fields_for :orders do |order| %>
       <%= render 'order_fields', f: order %>
    <% end %>
    <div class='links'>
       <%= link_to_add_association 'add order', f, :orders %>
    </div>
   <%= f.submit %>
 <% end %>

_order_fields.html.erb partial

<div class='nested-fields'>
   <%= f.label :order_name %>
   <%= f.text_field :order_name %>
</div>
<%= link_to_remove_association "remove order", f %>


问:
php opencart website 500 status
after 2 years, Suddenly if I try to visit an https://www.xxxx.com website built with opencart I get 500 status error, however, when I load the website dashboard and I logon, then I go back to  https://www.xxxx.com  and it works, I DO NOT get the 500 error status. I have tried the steps above on different clients (chrome) and I get 500 status unless I logon to the dashboard. I checked mysql and apache all running ok, I restarted the digital ocean server (ubuntu 14.04) without luck.I found the following log in the apache error

```<code>call to a member function getModule() on a non-object in /var/www/html/catalog/controller/common/footer_modules.php on line 23
</code>```

why suddenly I am getting this error? code not changed at all. I do not know how to troubleshoot it. I appreciate some detailed steps.

答: This is resolved by going to dashboard's Settings --> Store -- > maintenance and unchecking maintenance to No. Maintenance tickbox was set to Yes. Somehow the error does not indicate at all the cause. I set it to No and the error disappeared. I am investigating now whether someone hacked the server or someone had access to the server.</p>

Title: php opencart website 500 status

Body:
after 2 years, Suddenly if I try to visit an https://www.xxxx.com website built with opencart I get 500 status error, however, when I load the website dashboard and I logon, then I go back to  https://www.xxxx.com  and it works, I DO NOT get the 500 error status. I have tried the steps above on different clients (chrome) and I get 500 status unless I logon to the dashboard. I checked mysql and apache all running ok, I restarted the digital ocean server (ubuntu 14.04) without luck.I found the following log in the apache error

call to a member function getModule() on a non-object in /var/www/html/catalog/controller/common/footer_modules.php on line 23

why suddenly I am getting this error? code not changed at all. I do not know how to troubleshoot it. I appreciate some detailed steps.


问:
Fastest Way of Inserting in Entity Framework
I'm looking for the fastest way of inserting into Entity Framework.

I'm asking this because of the scenario where you have an active TransactionScope and the insertion is huge (4000+). It can potentially last more than 10 minutes (default timeout of transactions), and this will lead to an incomplete transaction.

答:
Use SqlBulkCopy:

```<code>void BulkInsert(GpsReceiverTrack[] gpsReceiverTracks)
{
    if (gpsReceiverTracks == null)
    {
        throw new ArgumentNullException(nameof(gpsReceiverTracks));
    }

    DataTable dataTable = new DataTable("GpsReceiverTracks");
    dataTable.Columns.Add("ID", typeof(int));
    dataTable.Columns.Add("DownloadedTrackID", typeof(int));
    dataTable.Columns.Add("Time", typeof(TimeSpan));
    dataTable.Columns.Add("Latitude", typeof(double));
    dataTable.Columns.Add("Longitude", typeof(double));
    dataTable.Columns.Add("Altitude", typeof(double));

    for (int i = 0; i < gpsReceiverTracks.Length; i++)
    {
        dataTable.Rows.Add
        (
            new object[]
            {
                    gpsReceiverTracks[i].ID,
                    gpsReceiverTracks[i].DownloadedTrackID,
                    gpsReceiverTracks[i].Time,
                    gpsReceiverTracks[i].Latitude,
                    gpsReceiverTracks[i].Longitude,
                    gpsReceiverTracks[i].Altitude
            }
        );
    }

    string connectionString = (new TeamTrackerEntities()).Database.Connection.ConnectionString;
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        using (var transaction = connection.BeginTransaction())
        {
            using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
            {
                sqlBulkCopy.DestinationTableName = dataTable.TableName;
                foreach (DataColumn column in dataTable.Columns)
                {
                    sqlBulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                }

                sqlBulkCopy.WriteToServer(dataTable);
            }
            transaction.Commit();
        }
    }

    return;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Use SqlBulkCopy:

void BulkInsert(GpsReceiverTrack[] gpsReceiverTracks)
{
    if (gpsReceiverTracks == null)
    {
        throw new ArgumentNullException(nameof(gpsReceiverTracks));
    }

    DataTable dataTable = new DataTable("GpsReceiverTracks");
    dataTable.Columns.Add("ID", typeof(int));
    dataTable.Columns.Add("DownloadedTrackID", typeof(int));
    dataTable.Columns.Add("Time", typeof(TimeSpan));
    dataTable.Columns.Add("Latitude", typeof(double));
    dataTable.Columns.Add("Longitude", typeof(double));
    dataTable.Columns.Add("Altitude", typeof(double));

    for (int i = 0; i < gpsReceiverTracks.Length; i++)
    {
        dataTable.Rows.Add
        (
            new object[]
            {
                    gpsReceiverTracks[i].ID,
                    gpsReceiverTracks[i].DownloadedTrackID,
                    gpsReceiverTracks[i].Time,
                    gpsReceiverTracks[i].Latitude,
                    gpsReceiverTracks[i].Longitude,
                    gpsReceiverTracks[i].Altitude
            }
        );
    }

    string connectionString = (new TeamTrackerEntities()).Database.Connection.ConnectionString;
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        using (var transaction = connection.BeginTransaction())
        {
            using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
            {
                sqlBulkCopy.DestinationTableName = dataTable.TableName;
                foreach (DataColumn column in dataTable.Columns)
                {
                    sqlBulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                }

                sqlBulkCopy.WriteToServer(dataTable);
            }
            transaction.Commit();
        }
    }

    return;
}


问:
What would we do without NULL?
I once read that having nullable types is an absolute evil. I believe it was in an article written by the very person who created them(in Ada?) I believe this is the article

Anyway, so what if by default a language like C# used non-nullable types? How would you replace some of the common idioms in C# or Ruby or any other common language where null is an acceptable value?

答:
Haskell is a powerful language that doesn't have the concept of nullity. Basically, every variable must be initialized to a non-null value. If you want to represent an "optional" variable (the variable may have a value but it may not), you can use a special "Maybe" type.

It's easier to implement this system in Haskell than C# because data is immutable in Haskell so it doesn't really make sense to have a null reference that you later populate. However, in C#, the last link in a linked list may have a null pointer to the next link, which is populated when the list expands. I don't know what a procedural language without null types would look like.

Also, note that many people above seem to be suggesting replacing nulls with type-specific logical "nothing" values (999-999-9999, "NULL", etc.). These values don't really solve anything because the problem people have with nulls is that they are a special case but people forget to code for the special case. With the type-specific logical nothing values, people STILL forget to code for the special case, yet they avoid errors that catch this mistake, which is a bad thing.

Title: What would we do without NULL?


问:
Reuse inheritance to define a method in Java
I'm a new Java developer and I met some difficulties with the concept of inheritance in java to define my classes...

In one side, I have a generic class named Vehicle that defines a decades of attributes (with their getters/setters). And I have a Vehicle1 class that extends Vehicle class.

In other side, I have a generic classe named VehicleFactory that defines one single static method like this :

```<code>public class VehicleFactory {

    protected static Vehicle makeResult() {
        Vehicle result = new Vehicle();

        result.setCode("1");
        result.setNumber("2");
        // other setters methods
        return result;
    }
</code>```

The problem is that I want to create a Vehicle1Factory class with its own makeResult method that USE the makeResult method of its parent class. But I failed to do this (the aim here is the optimisation since Vehicle1 has all the generic attributes of Vehicle classe but has some additional attributes).

What I tried to write is like this :

```<code>public class Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult() {
        Vehicle1 result = new Vehicle1();

         result = (Vehicle1) VehicleFactory.makeResult();

        // I want to reuse the makeResult of its parent class to define
        // its own makeResult method
    }
}
</code>```

But when I do this, Java told me that there a ClassCastException and that I can't use the cast here...

Is there any solution in that case?

答:
Once an instance of Something is created, it can never become an instance of something else. Since VehicleFactory.makeResult creates Vehicle instances, there's no way to transform that to Vehicle1.
You would have to create a new Vehicle1 for that.

A solution can be to move the code you want to reuse to a utility method, for example:

```<code>class Vehicle { }

class Bike extends Vehicle { }

class VehicleFactory {
    static Vehicle create() {
        Vehicle vehicle = new Vehicle();
        initialize(vehicle);
        return vehicle;
    }

    private static void initialize(Vehicle vehicle) {
        result.setCode("1");
        result.setNumber("2");
        // ...
    }
}

class BikeFactory {
    static Bike create() {
        Bike bike = new Bike();
        VehicleFactory.initialize(bike);
        return bike;
    }
}
</code>```

Body:
I'm a new Java developer and I met some difficulties with the concept of inheritance in java to define my classes...

In one side, I have a generic class named Vehicle that defines a decades of attributes (with their getters/setters). And I have a Vehicle1 class that extends Vehicle class.

In other side, I have a generic classe named VehicleFactory that defines one single static method like this :

public class VehicleFactory {

    protected static Vehicle makeResult() {
        Vehicle result = new Vehicle();

        result.setCode("1");
        result.setNumber("2");
        // other setters methods
        return result;
    }

The problem is that I want to create a Vehicle1Factory class with its own makeResult method that USE the makeResult method of its parent class. But I failed to do this (the aim here is the optimisation since Vehicle1 has all the generic attributes of Vehicle classe but has some additional attributes).

What I tried to write is like this :

public class Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult() {
        Vehicle1 result = new Vehicle1();

         result = (Vehicle1) VehicleFactory.makeResult();

        // I want to reuse the makeResult of its parent class to define
        // its own makeResult method
    }
}

But when I do this, Java told me that there a ClassCastException and that I can't use the cast here...

Is there any solution in that case?

Body:
Once an instance of Something is created, it can never become an instance of something else. Since VehicleFactory.makeResult creates Vehicle instances, there's no way to transform that to Vehicle1.
You would have to create a new Vehicle1 for that.

A solution can be to move the code you want to reuse to a utility method, for example:

class Vehicle { }

class Bike extends Vehicle { }

class VehicleFactory {
    static Vehicle create() {
        Vehicle vehicle = new Vehicle();
        initialize(vehicle);
        return vehicle;
    }

    private static void initialize(Vehicle vehicle) {
        result.setCode("1");
        result.setNumber("2");
        // ...
    }
}

class BikeFactory {
    static Bike create() {
        Bike bike = new Bike();
        VehicleFactory.initialize(bike);
        return bike;
    }
}


问:
Change innerHTML onmousemove event
i want to change the innerHTML of a div with onmousemove event.

Let's say that when the mouse move over the div, the innerHTML change to "Mouse is Moving". And when the mouse stop moving it return back to the default innerHTML value: "Mouse is not moving".

Pretty simple. I know there is a onmouseleave event you can use to undo onmouseenter or onmouseover actions but there is no "onmousecalm" event to undo onmousemove.

how to achieve that ?

答:
You can just use mousemove to set the innerHTML and every time the event fires, get a timestamp then use a setInterval with some sort of threshold to detect when the mouse has stopped moving to reset the innerHTML

var div = document.querySelector('div'),
    move = div.getAttribute('data-move'),
    pause = div.innerHTML,
    threshold = 500;

div.addEventListener('mousemove',function() {
  lastMoved = new Date().getTime();
  div.innerHTML = move;
  var timeout = setTimeout(function() {
    var nowTime = new Date().getTime();
    if (nowTime - lastMoved > threshold) {
      div.innerHTML = pause;
    }
  }, threshold)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  padding: 5em;
  border: 1px solid black;
}</code>```

mouse is not moving
```

Title: Change innerHTML onmousemove event

Body:
You can just use mousemove to set the innerHTML and every time the event fires, get a timestamp then use a setInterval with some sort of threshold to detect when the mouse has stopped moving to reset the innerHTML

var div = document.querySelector('div'),
    move = div.getAttribute('data-move'),
    pause = div.innerHTML,
    threshold = 500;

div.addEventListener('mousemove',function() {
  lastMoved = new Date().getTime();
  div.innerHTML = move;
  var timeout = setTimeout(function() {
    var nowTime = new Date().getTime();
    if (nowTime - lastMoved > threshold) {
      div.innerHTML = pause;
    }
  }, threshold)
});

div {
  padding: 5em;
  border: 1px solid black;
}

<div data-move="mouse is moving">mouse is not moving</div>


问:
Building android apk in ionic throws error
When i run ionic build android --prod --release its gives me below output

```<code>The build command has been renamed. To find out more, run:

  ionic cordova build --help
</code>```

I don't know why its give me this error
when i run

ionic info

```<code>global packages:

    @ionic/cli-utils : 1.3.0
    Ionic CLI        : 3.3.0

local packages:

    @ionic/app-scripts              : 1.3.7
    @ionic/cli-plugin-ionic-angular : 1.3.0
    Ionic Framework                 : ionic-angular 3.3.0

System:

    Node       : v6.10.3
    OS         : Windows 10
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed
</code>```

Please help me with above error

答:
in fact I faced this error with ionic 3.3 before update all thing.
so you need to reinstall the last version of cordova and ionic( now it is 3.3.2)<br>
or Simply, just you need to use </p>

```<code>ionic cordova build android --prod --release
</code>```

Body:
When i run ionic build android --prod --release its gives me below output

The build command has been renamed. To find out more, run:

  ionic cordova build --help

I don't know why its give me this error
when i run

ionic info

global packages:

    @ionic/cli-utils : 1.3.0
    Ionic CLI        : 3.3.0

local packages:

    @ionic/app-scripts              : 1.3.7
    @ionic/cli-plugin-ionic-angular : 1.3.0
    Ionic Framework                 : ionic-angular 3.3.0

System:

    Node       : v6.10.3
    OS         : Windows 10
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed

Please help me with above error

Body:
in fact I faced this error with ionic 3.3 before update all thing.
so you need to reinstall the last version of cordova and ionic( now it is 3.3.2)

or Simply, just you need to use

ionic cordova build android --prod --release


问:
Stopping a blinking cursor at end of css animation
I guys I have tried a lot of things that didn't work. I have a css animation with a blinking cursor. I am trying to use it in this game I'm developing.

Link to game for visual reference: https://code.sololearn.com/WF65X6DEns7o/#css

+++

so here is the code that is a problem

HTML:

```<code>   <div id = "Header"> <b>Real Estate Agent</b> </div>
</code>```

CSS:

```<code>#Header{
font-size:50px; color:darkOrange; text-shadow:3px 3pxblack;
overflow:hidden;
letter-spacing: .15em;
animation: typing 3.5s steps(60, end), blink-caret .65s step-end infinite;
white-space: nowrap;
border-right: .15em solid orange;
width:500px;
}

 @keyframes typing {
  from { width: 0 }
   to { width: 500px }
   }

@keyframes blink-caret {
from, to { border-color: orange }
 50% { border-color: transparent; }
   }
</code>```

+++++++++++++

currently the cursor blinks until all the text is done typing and then it keeps blink at the end of the words.

How can i make the cursor stop blinking at the end of the animation and stop the animation cycle.

As i have said i have tried a few things and nothing is working.

thanks

答:
Replace the infinite with 8 (experiment with the value to your liking) and set the initial color of the border to transparent.

```<code>animation: typing 3.5s steps(60, end), blink-caret .65s step-end 8;
white-space: nowrap;
border-right: .15em solid transparent;
</code>```

This way it will blink 8 times and then become invisible.

Body:
I guys I have tried a lot of things that didn't work. I have a css animation with a blinking cursor. I am trying to use it in this game I'm developing.

Link to game for visual reference: https://code.sololearn.com/WF65X6DEns7o/#css

+++

so here is the code that is a problem

HTML:

 Real Estate Agent

CSS:

#Header{
font-size:50px; color:darkOrange; text-shadow:3px 3pxblack;
overflow:hidden;
letter-spacing: .15em;
animation: typing 3.5s steps(60, end), blink-caret .65s step-end infinite;
white-space: nowrap;
border-right: .15em solid orange;
width:500px;
}

 @keyframes typing {
  from { width: 0 }
   to { width: 500px }
   }

@keyframes blink-caret {
from, to { border-color: orange }
 50% { border-color: transparent; }
   }

+++++++++++++

currently the cursor blinks until all the text is done typing and then it keeps blink at the end of the words.

How can i make the cursor stop blinking at the end of the animation and stop the animation cycle.

As i have said i have tried a few things and nothing is working.

thanks

Body:
Replace the infinite with 8 (experiment with the value to your liking) and set the initial color of the border to transparent.

animation: typing 3.5s steps(60, end), blink-caret .65s step-end 8;
white-space: nowrap;
border-right: .15em solid transparent;

This way it will blink 8 times and then become invisible.


问:
best practice json?
when using spring rest server side generate json, it will looks like below

```<code>{"userInfo":{"id":123,"userFullName":"full name"}}    with nested 'userInfo'
</code>```

should json generate this way is consider best practice or should just generate like below

{"id":88,"userFullName":"dfXXXXXXXXXX"}    without nested 'userinfo'

the reason i asking is, if i use the prior technique, on my client, i would need to Extract the user info as JSONObject then only can get json data . which way is better?

答: JSON's core tenet is to provide "object-oriented" notations to be used within JavaScript. and if you stick by that, i feel that your first construct, having nested userInfo is a more appropriate construct. otherwise, in the second case, you'll end up having to build the userInfo object from the other field data.

Title: best practice json?

Body:
when using spring rest server side generate json, it will looks like below

{"userInfo":{"id":123,"userFullName":"full name"}}    with nested 'userInfo'

should json generate this way is consider best practice or should just generate like below

{"id":88,"userFullName":"dfXXXXXXXXXX"}    without nested 'userinfo'

the reason i asking is, if i use the prior technique, on my client, i would need to Extract the user info as JSONObject then only can get json data . which way is better?


问:
Avoid page break between heading and first list item
I have an HTML document, and I'd like to ensure that when printed, page breaks never appear immediately after a heading.

In an ideal world, this would be as easy as setting .heading {page-break-after: avoid;}, but most browsers do not support page-break-after: avoid (or page-break-before: avoid), only page-break-inside: avoid.

When a stand-alone element like p follows my heading, I can wrap the heading and the paragraph in a
, and avoid page breaks inside the .nobreak elements.

But sometimes, a long list follows the heading:

```<code><h1>A list of things</h1>
<ol>
  <li>This is the first thing.</li>
  <li>This is the next thing.</li>
  ...
  <li>Many things later, we reach the end.</li>
</ol>
</code>```

I can wrap the h1 and the ol both in a div.nobreak, but this is too strict: it prevents page breaks from occurring at any point during the list, when really all I care about is preventing a break right before the first li.

For obvious reasons (the presence of the ol tag), I cannot wrap just the h1 and first li in a surrounding element.

Any ideas on how to achieve the desired effect here?

答:
```<code><style>
 h1 { margin-bottom: 0; padding-bottom:0;}
 ol, li:first-child { margin-top: 0; padding-top: 0; }
</style>
</code>```

Use the li:first-child subclass to style only the first element in a list.

Make sure therebis no other margins or padding between wrapping elements.

Body:
I have an HTML document, and I'd like to ensure that when printed, page breaks never appear immediately after a heading.

In an ideal world, this would be as easy as setting .heading {page-break-after: avoid;}, but most browsers do not support page-break-after: avoid (or page-break-before: avoid), only page-break-inside: avoid.

When a stand-alone element like p follows my heading, I can wrap the heading and the paragraph in a
, and avoid page breaks inside the .nobreak elements.

But sometimes, a long list follows the heading:

A list of things

This is the first thing.

This is the next thing.

  ...

Many things later, we reach the end.

I can wrap the h1 and the ol both in a div.nobreak, but this is too strict: it prevents page breaks from occurring at any point during the list, when really all I care about is preventing a break right before the first li.

For obvious reasons (the presence of the ol tag), I cannot wrap just the h1 and first li in a surrounding element.

Any ideas on how to achieve the desired effect here?

Body:
<style>
 h1 { margin-bottom: 0; padding-bottom:0;}
 ol, li:first-child { margin-top: 0; padding-top: 0; }
</style>

Use the li:first-child subclass to style only the first element in a list.

Make sure therebis no other margins or padding between wrapping elements.


问:
Concrete5 Add-Block panel opens when page placed in edit mode
With Concrete5 8.1, when I put the page in edit mode by clicking the button with tool tip "Edit this Page" (pencil icon), the page reloads and then the button with the "+" icon appears to have a click event, opening the Add Blocks panel.

I tried to write that as simple as possible so it's clear what is happening.  To be more technical, it appears that when the page reloads in edit mode, there is a click event called for the button that opens the blocks panel.  This panel shouldn't open unless I explicitly click the button to do so.  The edit button should only put the page in edit mode, allowing me to select existing blocks.

Once the blocks panel is opened, I can click the edit button again and the blocks panel will close, leaving the page in edit mode.  However, that second click should actually cause the page to exit edit mode.

Has someone else had a similar problem, and is there a fix for it?

Thanks

答:
Here's an answer, but it's not a fix.
The concrete5 dev team confirms it's a problem in 8.1 when C5 is running from a subfolder rather than the root of the web site, e.g (as described in the issue report referenced above) as http://mycompany.com/directory rather than http://mycompany.com.

So, one potential fix is to reconfigure your website to run as the top-level site in your domain.

If that's not possible, you could patch the file CookieMiddleware.php as described in the issue description (2 lines, simple fix).

Or you could wait for the next point release (8.2).  No indication from the dev team when that might be.


问:
Unable to Install Tensorflow (MemoryError)
I tried to install Tensorflow on Linux Ubuntu 16.04 from source and using pip and I keep getting the following error return base64.b64encode(b).decode("ascii")
MemoryError. I tried to google this problem but only found a website written in Chinese (probably) http://juncollin.hatenablog.com/entry/2017/03/05/025318 that doesn't really help.

答: Try installing without caching: pip install --no-cache-dir tensorflow.


问:
Waiting for async request to return before proceeding Google Apps Script
Some code in Google Apps Script I am currently producing has a need for an object to be completed with one of the properties being set by the result of an async request. This object, and specifically, this property are then used later down the line. However, because the request has not returned by the time the functions needing that property run, they are not evaluating properly.
My code is as follows:

```<code>function Thing(val) {
    var self = this

    var createSuccess = function(data) {
        self.foo = data;
    }

    var init = function(val) {
        google.script.run.withSuccessHandler(createSuccess).serverFunc(val);
    };

    init(val);
}

function objStuff() {
    var foobar = new Thing('bar');
    // Do stuff with foobar.foo
}

objStuff();
</code>```

Currently the stuff using foobar.foo does not work correctly, as the script has not waited for the return value of the script before proceeding.

Is there a way I can wait for the foo property to be evaluated with the async request before proceeding with the rest of my script?

答:
My recomendation would be to use the events module if you are making use of nodejs since it allows you to create an event listener.

So you could do something like

```<code>eventEmitter.on('listener_key', function(){
    //your code to be executed after the event
});

funtion emitStuffToListener(){
 eventEmitter.emit('listener_key');
}
</code>```

EDIT: sorry I missread the post but you can still do event oriented development with Google Apps Event Objects

Body:
Some code in Google Apps Script I am currently producing has a need for an object to be completed with one of the properties being set by the result of an async request. This object, and specifically, this property are then used later down the line. However, because the request has not returned by the time the functions needing that property run, they are not evaluating properly.
My code is as follows:

function Thing(val) {
    var self = this

    var createSuccess = function(data) {
        self.foo = data;
    }

    var init = function(val) {
        google.script.run.withSuccessHandler(createSuccess).serverFunc(val);
    };

    init(val);
}

function objStuff() {
    var foobar = new Thing('bar');
    // Do stuff with foobar.foo
}

objStuff();

Currently the stuff using foobar.foo does not work correctly, as the script has not waited for the return value of the script before proceeding.

Is there a way I can wait for the foo property to be evaluated with the async request before proceeding with the rest of my script?

Body:
My recomendation would be to use the events module if you are making use of nodejs since it allows you to create an event listener.

So you could do something like

eventEmitter.on('listener_key', function(){
    //your code to be executed after the event
});

funtion emitStuffToListener(){
 eventEmitter.emit('listener_key');
}

EDIT: sorry I missread the post but you can still do event oriented development with Google Apps Event Objects


问:
CMake add_custom_command run in background
I have a command executed in a POST_BUILD step using add_custom_command(). It takes quite some time, but I don't need the results to run the executable, I just want it to start after the build. Is there a way to run such a command in the background so that the executable can be run right after the build without waiting for the command to finish?

答:
If you are willing to use some platform-specific logic, one way is to use a shell script to launch the command you want to run in the background. A very crude example for Unix systems may look like this:

launcher.sh:

```<code>#!/bin/sh

"$@"&
</code>```

CMakeLists.txt:

```<code>add_custom_command(TARGET myTarget POST_BUILD
    COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/launcher.sh whateverYouWantToRun
)
</code>```

You could add something equivalent for Windows and then test the CMAKE_HOST_SYSTEM_NAME variable to choose which launcher script to use.

Body:
If you are willing to use some platform-specific logic, one way is to use a shell script to launch the command you want to run in the background. A very crude example for Unix systems may look like this:

launcher.sh:

#!/bin/sh

"$@"&

CMakeLists.txt:

add_custom_command(TARGET myTarget POST_BUILD
    COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/launcher.sh whateverYouWantToRun
)

You could add something equivalent for Windows and then test the CMAKE_HOST_SYSTEM_NAME variable to choose which launcher script to use.


问:
How to run two do loops at the same time on VBScript
I'm trying to make it so my code runs 2 do loops at a time so it can run the open disk drive code and spam caps lock code at the same time. Any way I could do this?</p>
```<code> Set oWMP = CreateObject("WMPlayer.OCX.7")
Set colCDROMs = oWMP.cdromCollection
x=msgbox("Keyboard error with key CAPS LOCK",0,"Critical Error")
x=msgbox("Error with CD Drive",0,"Critical Error")
Set wshShell =wscript.CreateObject("WScript.Shell")
message= "Critical Disk Drive Error Alert Call Microsoft Support at 0 3 4 4 8 0 0 2 4 0 0 to resolve the issue"
message1= "Caps Lock key Error"
Dim message, sapi
Set sapi=CreateObject("sapi.spvoice")
sapi.Speak message
sapi.Speak message1

do
if colCDROMs.Count >= 1 then
For i = 0 to colCDROMs.Count -1
colCDROMs.Item(i).Eject
Next
For i = 0 to colCDROMs.Count -1
colCDROMs.Item(i).Eject
Next
End If
wscript.sleep 100
wshshell.sendkeys "{CAPSLOCK}"
wscript.sleep 100
loop
</code>```

答:
Take a look at the below example:

CheckTask ' always at the begining of the script

LaunchTask "EjectCdRoms" ' friendly keep CD-ROMs opened
LaunchTask "MsgA" ' friendly show the message A
LaunchTask "MsgB" ' friendly show the message B
LaunchTask "Speak" ' friendly speak

' procedures to be launched asynchronously

Sub EjectCdRoms()
    Dim i
    On Error Resume Next
    Do
        With CreateObject("WMPlayer.OCX.7").cdromCollection
            For i = 0 To .Count - 1
                .Item(d).Eject
            Next
        End With
        WScript.Sleep 500
    Loop
End Sub

Sub MsgA()
    Do
        WScript.Sleep 3000
        MsgBox "Critical Disk Drive Error Alert Call Microsoft Support at 03448002400 to resolve the issue", 48, "Blah"
    Loop
End Sub

Sub MsgB()
    Do
        WScript.Sleep 5000
        MsgBox "Caps Lock key Error", 48, "Blah"
    Loop
End Sub

Sub Speak()
    Do
        With CreateObject("SAPI.SpVoice")
            WScript.Sleep 4000
            .Speak "Critical Disk Drive Error Alert Call Microsoft Support at 0 3 4 4 8 0 0 2 4 0 0 to resolve the issue"
            WScript.Sleep 4000
            .Speak "Caps Lock key Error"
        End With
    Loop
End Sub

' utility procedures, do not modify

Sub CheckTask()
    If WScript.Arguments.Named.Exists("task") Then
        On Error Resume Next
        Execute WScript.Arguments.Named.Item("task")
        WScript.Quit
    End If
End Sub

Sub LaunchTask(sTaskName)
    CreateObject("WScript.Shell").Exec """" & WScript.FullName & """ """ & WScript.ScriptFullName & """ ""/task:" & sTaskName & """"
End Sub
```

Body:
I'm trying to make it so my code runs 2 do loops at a time so it can run the open disk drive code and spam caps lock code at the same time. Any way I could do this?

 Set oWMP = CreateObject("WMPlayer.OCX.7")
Set colCDROMs = oWMP.cdromCollection
x=msgbox("Keyboard error with key CAPS LOCK",0,"Critical Error")
x=msgbox("Error with CD Drive",0,"Critical Error")
Set wshShell =wscript.CreateObject("WScript.Shell")
message= "Critical Disk Drive Error Alert Call Microsoft Support at 0 3 4 4 8 0 0 2 4 0 0 to resolve the issue"
message1= "Caps Lock key Error"
Dim message, sapi
Set sapi=CreateObject("sapi.spvoice")
sapi.Speak message
sapi.Speak message1

do
if colCDROMs.Count >= 1 then
For i = 0 to colCDROMs.Count -1
colCDROMs.Item(i).Eject
Next
For i = 0 to colCDROMs.Count -1
colCDROMs.Item(i).Eject
Next
End If
wscript.sleep 100
wshshell.sendkeys "{CAPSLOCK}"
wscript.sleep 100
loop


问:
How to a make an object call its constructor in an array?
```<code>public static void createPlayers(int x) {
    System.out.println("How many players/AI will be playing this game?");
    numOfPlayers = scan.nextInt();
    HoldEmTurns players[] = new HoldEmTurns[x];
    for (int c = 0; c < x; c++) {
        players[c] = new HoldEmTurns(players[c].getHuman(),players[c].getName());
    }
</code>```

}

Whenever I run this, it runs these two lines and then terminates:

```<code>System.out.println("How many players/AI will be playing this game?");
    numOfPlayers = scan.nextInt();
</code>```

So pretty much how to a make an object call its constructor in an array?

答:
Consider this example:

Suppose you have a class SomeClass and it contains two fields a String & an int

```<code>public class SomeClass {

    String aString;
    int someInteger;
    ...............
}
</code>```

You can create a constructor to be used every time an Instance of type SomeClass is created. So each Object of type SomeClass you create, you have to initialize it with the arguments. Eventually, it will exist, and its fields now have values instead of null:

```<code>public SomeClass(String aString, int someInteger){
    this.aString = aString;
    this.someInteger = someInteger;
}
</code>```

Furthermore, you can create another constructor that accepts no arguments/parameters (that's called Overloading). As a result, you can either create an instance of this class and initialize its attributes or create empty object that its attributes not yet initialized (so you assign them values via setters later after creating the object):

```<code>public SomeClass(){
// Empty constructor
}
</code>```

Now Consider this setter method which can be invoked on the created object. Via the methods you can set/ get the object attributes/fields. This method for example change the aString field value:

```<code>public void changeTheString(String newString){
        aString = newString;
}
</code>```

You can create other methods to manipulate the attributes of the created object, for example:

```<code>public void changeTheInteger(int newInteger){
    someInteger = newInteger;
}

public String getTheString(){
    return aString;
}
</code>```

Now let's test creating an array of Objects of type SomeClass, consider this array which can have up to 3 objects of type SomeClass:

```<code>SomeClass array[] = new SomeClass[3];
</code>```

Now the array is EMPTY, but it CAN hold up to THREE Objects of type SomeClass. At every index (whether you're using a loop or not), you have to add the Object and Initialize it like this:

```<code>for(int i=0; i<3; i++){
    array[i] = new SomeClass("Some String", i); // values are for example
}
</code>```

Now you can invoke the method upon the Objects created at every index, for example:

```<code>String theString = array[0].getTheString();
System.out.println(theString); //to print it out

// changing the String field for SomeClass Object/Instance at index 1 in the array
array[1].changeTheString("I am changing the String");

// and so on
array[2].changeTheInteger(5);
</code>```

Body:
public static void createPlayers(int x) {
    System.out.println("How many players/AI will be playing this game?");
    numOfPlayers = scan.nextInt();
    HoldEmTurns players[] = new HoldEmTurns[x];
    for (int c = 0; c < x; c++) {
        players[c] = new HoldEmTurns(players[c].getHuman(),players[c].getName());
    }

}

Whenever I run this, it runs these two lines and then terminates:

System.out.println("How many players/AI will be playing this game?");
    numOfPlayers = scan.nextInt();

So pretty much how to a make an object call its constructor in an array?

Body:
Consider this example:

Suppose you have a class SomeClass and it contains two fields a String & an int

public class SomeClass {

    String aString;
    int someInteger;
    ...............
}

You can create a constructor to be used every time an Instance of type SomeClass is created. So each Object of type SomeClass you create, you have to initialize it with the arguments. Eventually, it will exist, and its fields now have values instead of null:

public SomeClass(String aString, int someInteger){
    this.aString = aString;
    this.someInteger = someInteger;
}

Furthermore, you can create another constructor that accepts no arguments/parameters (that's called Overloading). As a result, you can either create an instance of this class and initialize its attributes or create empty object that its attributes not yet initialized (so you assign them values via setters later after creating the object):

public SomeClass(){
// Empty constructor
}

Now Consider this setter method which can be invoked on the created object. Via the methods you can set/ get the object attributes/fields. This method for example change the aString field value:

public void changeTheString(String newString){
        aString = newString;
}

You can create other methods to manipulate the attributes of the created object, for example:

public void changeTheInteger(int newInteger){
    someInteger = newInteger;
}

public String getTheString(){
    return aString;
}

Now let's test creating an array of Objects of type SomeClass, consider this array which can have up to 3 objects of type SomeClass:

SomeClass array[] = new SomeClass[3];

Now the array is EMPTY, but it CAN hold up to THREE Objects of type SomeClass. At every index (whether you're using a loop or not), you have to add the Object and Initialize it like this:

for(int i=0; i<3; i++){
    array[i] = new SomeClass("Some String", i); // values are for example
}

Now you can invoke the method upon the Objects created at every index, for example:

String theString = array[0].getTheString();
System.out.println(theString); //to print it out

// changing the String field for SomeClass Object/Instance at index 1 in the array
array[1].changeTheString("I am changing the String");

// and so on
array[2].changeTheInteger(5);


问:
How can i crawl web data that not in tags(class name is same)
Sorry.
I have asked a question like this.
After that i still have problem about data not in tag.
A few different the question i asked
(How can i crawl web data that not in tags)

```<code><div class="bbs" id="main-content">
    <div class="metaline">
        <span class="article-meta-tag">
             author
        </span>
        <span class="article-meta-value">
             Jorden
        </span>
    </div>
    <div class="metaline">
        <span class="article-meta-tag">
            board
        </span>
        <span class="article-meta-value">
            NBA
        </span>
    </div>

I am here

</div>
</code>```

I only need

I am here

答:
```<code>soup = BeautifulSoup(that_html)
div_tag = soup.div
required_string = div_tag.string
</code>```

go thought this documentation

Body:
Sorry.
I have asked a question like this.
After that i still have problem about data not in tag.
A few different the question i asked
(How can i crawl web data that not in tags)

             author

             Jorden

            board

            NBA

I am here

I only need

I am here

Body:
soup = BeautifulSoup(that_html)
div_tag = soup.div
required_string = div_tag.string

go thought this documentation


问:
Why does int(maxint) give a long, but int(int(maxint)) give an int? Is this a NumPy bug?
Pretty self-explanatory (I'm on Windows):

```<code>>>> import sys, numpy
>>> a = numpy.int_(sys.maxint)
>>> int(a).__class__
<type 'long'>
>>> int(int(a)).__class__
<type 'int'>
</code>```

Why does calling int once give me a long, whereas calling it twice gives me an int?

Is this a bug or a feature?

答:
This question is specific to Numpy and Python 2. In Python 3 there are no separate int and long types.

The behaviour happens due to an off-by-one error in numpy. int(x) with one argument converts x to number by calling PyNumber_Int(x). PyNumber_Int then specifically takes the path for int subclasses, as int64 returned by numpy.int_ is a subclass of int:

m = o->ob_type->tp_as_number;
if (m && m->nb_int) { /* This should include subclasses of int */
    /* Classic classes always take this branch. */
    PyObject *res = m->nb_int(o);
    if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
        PyErr_Format(PyExc_TypeError,
                     "__int__ returned non-int (type %.200s)",
                     res->ob_type->tp_name);
        Py_DECREF(res);
        return NULL;
    }
    return res;
}
```

<p>Now, for this code calls <code>a->ob_type->tp_as_number->nb_int</code>, which is implemented in numpy/core/src/umath/scalarmath.c.src. This is the location for code that is parametrized for different types; this one for <code><typename>_int</code> method that is used to fill the <code>nb_int</code> method slot. It has the following off-by one <code>if</code> there:</p>

```if(LONG_MIN < x && x < LONG_MAX)
    return PyInt_FromLong(x);
```

<p>both operators should be <code><=</code> instead. With <code><</code> there, neither <code>LONG_MIN</code> nor <code>LONG_MAX</code> pass the condition and they're instead are converted into a <code>PyLong</code> at line 1432:</p>

```return @func@(x);
```

with @func@ being replaced by PyLong_FromLongLong in the case of int_. Thus, long(sys.maxint) is returned.

Now, as the sys.maxint is still representable by int, int(long(sys.maxint)) returns an int; likewise int(sys.maxint + 1) returns a long.

Body:
Pretty self-explanatory (I'm on Windows):

>>> import sys, numpy
>>> a = numpy.int_(sys.maxint)
>>> int(a).__class__
<type 'long'>
>>> int(int(a)).__class__
<type 'int'>

Why does calling int once give me a long, whereas calling it twice gives me an int?

Is this a bug or a feature?

Body:
This question is specific to Numpy and Python 2. In Python 3 there are no separate int and long types.

The behaviour happens due to an off-by-one error in numpy. int(x) with one argument converts x to number by calling PyNumber_Int(x). PyNumber_Int then specifically takes the path for int subclasses, as int64 returned by numpy.int_ is a subclass of int:

m = o->ob_type->tp_as_number;
if (m && m->nb_int) { /* This should include subclasses of int */
    /* Classic classes always take this branch. */
    PyObject *res = m->nb_int(o);
    if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
        PyErr_Format(PyExc_TypeError,
                     "__int__ returned non-int (type %.200s)",
                     res->ob_type->tp_name);
        Py_DECREF(res);
        return NULL;
    }
    return res;
}

Now, for this code calls a->ob_type->tp_as_number->nb_int, which is implemented in numpy/core/src/umath/scalarmath.c.src. This is the location for code that is parametrized for different types; this one for <typename>_int method that is used to fill the nb_int method slot. It has the following off-by one if there:

if(LONG_MIN < x && x < LONG_MAX)
    return PyInt_FromLong(x);

both operators should be <= instead. With < there, neither LONG_MIN nor LONG_MAX pass the condition and they're instead are converted into a PyLong at line 1432:

return @func@(x);

with @func@ being replaced by PyLong_FromLongLong in the case of int_. Thus, long(sys.maxint) is returned.

Now, as the sys.maxint is still representable by int, int(long(sys.maxint)) returns an int; likewise int(sys.maxint + 1) returns a long.


问:
Why does the Android emulator report "unknown virtual device", when the device is in my user directory?
I installed all the prerequisites for Android development. I created a virtual device through Eclipse and tried to run the Hello World sample application in that device. I received the following error message.

emulator: ERROR: unknown virtual device name: 'Android21Device'

  emulator: could not find virtual device named 'Android21Device'

I get the same error when I try to start the device from the command line and through the SDK program.

I can see the device directory and files at

D:\Users\anthony\.android\avd\Android21Device.avd

答: You need to restart eclipse after closing it. File -> Restart will not help. </p>


问:
Eloquent does not recognize fillable fields when adding constructor to model
I have model Category as below:

```<code>namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * @var $fillable
     */
    protected $fillable = array('title', 'slug' , 'descriptoin', 'cover', 'logo', 'parent_id');

    /**
     * @var $category_logo_pathp
     */
    protected $category_logo_path ;

    /**
     * @var $category_cover_path
     */
    protected $category_cover_path ;

    /**
     * constructor
     */
    function __construct()
    {
        $this->category_cover_path = public_path() . '/upload/image/category/cover/';
        $this->category_logo_path = public_path() . '/upload/image/category/logo/';
    }

    /**
     * relation with itself
     */
    public function parent()
    {
        return self::where('id', $this->parent_id)->first();
    }

    public function coverPath()
    {
        return $this->category_cover_path;
    }

    public function logoPath()
    {
        return $this->category_logo_path;
    }
}
</code>```

When inserting a category instance with correct data into database , Eloquent does not recognize fillable fields of the model and then throws Illuminate\Database\QueryException but when i remove the constructor from category model , it works fine and fillable fields are recognized using Eloquent. what is causing this?

答:
For sure, you should run parent constructor and probably it's quite reasonable to use default Model signature, so your constructor should look like this:</p>

```<code>public function __construct(array $attributes = [])
{
   parent::__construct($attributes);
   $this->category_cover_path = public_path() . '/upload/image/category/cover/';
   $this->category_logo_path = public_path() . '/upload/image/category/logo/';
}
</code>```

Body:
I have model Category as below:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * @var $fillable
     */
    protected $fillable = array('title', 'slug' , 'descriptoin', 'cover', 'logo', 'parent_id');

    /**
     * @var $category_logo_pathp
     */
    protected $category_logo_path ;

    /**
     * @var $category_cover_path
     */
    protected $category_cover_path ;

    /**
     * constructor
     */
    function __construct()
    {
        $this->category_cover_path = public_path() . '/upload/image/category/cover/';
        $this->category_logo_path = public_path() . '/upload/image/category/logo/';
    }

    /**
     * relation with itself
     */
    public function parent()
    {
        return self::where('id', $this->parent_id)->first();
    }

    public function coverPath()
    {
        return $this->category_cover_path;
    }

    public function logoPath()
    {
        return $this->category_logo_path;
    }
}

When inserting a category instance with correct data into database , Eloquent does not recognize fillable fields of the model and then throws Illuminate\Database\QueryException but when i remove the constructor from category model , it works fine and fillable fields are recognized using Eloquent. what is causing this?

Body:
For sure, you should run parent constructor and probably it's quite reasonable to use default Model signature, so your constructor should look like this:

public function __construct(array $attributes = [])
{
   parent::__construct($attributes);
   $this->category_cover_path = public_path() . '/upload/image/category/cover/';
   $this->category_logo_path = public_path() . '/upload/image/category/logo/';
}


问:
Statement to create excel vba hyperlink throws Run-time '1004' Error
So I have had a couple of questions I've asked regarding excel VBA, and I appreciate you all bearing with me as I stumble through learning about all this. Your answers have been a tremendous help and learning experience.

So far, I have a subroutine whose main responsibility is to write all of the values collected through a user form with various validations and dynamic comboboxes. My final task is to get this Subroutine to assign a hyperlink to the location selected by an earlier loop. But with my current syntax, I'm getting a "run-time error '1004' method '_default' of object 'range' failed". Some research proved that the cell coordinates require a .address property after them in order to avert this error, but it did not resolve the issue. The code is below:

```<code>    Option Explicit
    Dim cnt As Integer
    Dim i As Long, rowOff As Long
    Dim dateSel As String
    Dim timeSel As String
    Dim branch As String
    Dim sht As Worksheet
    Dim cel As Range
    Dim matchingHeader As Range

    Public Sub UserForm_Initialize()
        'clear form
        BranchBox.Value = ""
        DateBox.Value = ""
        TimeBox.Value = ""

        'populate sheet names from each branch
        For Each sht In ActiveWorkbook.Sheets
          If sht.Name = "ApplicantInfo" Then
            'Do Nothing
          Else
            Me.BranchBox.AddItem sht.Name
          End If
        Next sht
    End Sub

    Public Sub HoldButton_Click() 'revisit... throwing Time message box regardless what's selected
        If TimeBox.Value <> "" Then
            If DateBox.Value <> "" Then
                If BranchBox.Value <> "" Then
                    sht.Cells(rowOff, i).Value = "-"
                    'Save workbook
                Else
                    MsgBox "You must select a branch for your appointment"
                End If
            Else
                MsgBox "You must select a date for your appointment"
            End If
        Else
            MsgBox "You must select a time for your appointment"
        End If
    End Sub

    Private Sub ResetButton_Click()
        FirstName.Value = ""
        LastName.Value = ""
        EMail.Value = ""
        Phone.Value = ""
        Skills.Value = ""
        'BranchBox.Value = "" throws error
        DateBox.Value = ""
        TimeBox.Value = ""
    End Sub

    Private Sub ScheduleButton_Click()
        Dim row As Long, column As Long
        Dim linkDisplay As String
        'test for RowOff and i <> 0
        If IsNull(BranchBox) = True Then
            MsgBox "Select a branch for you interview before you click schedule"
        Else
            If IsNull(DateBox) = True Then
                MsgBox "Select a date for you interview before you click schedule"
            Else
                If IsNull(TimeBox) = True Then
                    MsgBox "Select a time for you interview before you click schedule"
                Else
                    'find first empty row in applicant profile tab.
                    'Insert applicant information in free row
                    'parse applicant name as a link to found free row above
                    'replace "-" placeholder for held appointment with applicant name as a link

                    Call GetFirstEmptyRow
                    'write selected values into row
                    Dim InfoRow As Integer
                    InfoRow = ActiveCell.row
                    ActiveCell.Value = ActiveCell.Offset(-5, 0).Value + 5
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = LastName.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = FirstName.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = EMail.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = Phone.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = Skills.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = BranchBox.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = DateBox.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = TimeBox.Value

                    branch = BranchBox.Value
                    Set sht = ActiveWorkbook.Worksheets(branch)
                    dateSel = DateBox.Value
                    timeSel = TimeBox.Value

                    'scan for selected date
                    For i = 2 To sht.Rows.Count
                        Set cel = sht.Cells(i, 1)
                        If cel.Value = dateSel Then
                            column = i
                            Exit For
                        End If
                    Next i

                    'Scan for selected time
                    For i = 2 To sht.Columns.Count
                        Set cel = sht.Cells(1, i)
                        If CStr(cel.Value) = timeSel Then
                            row = i
                            Exit For
                        End If
                    Next i

                    linkDisplay = LastName.Value & ", " & FirstName.Value
'This is the error
                    sht.Hyperlinks.Add Anchor:=sht.Cells(row, column).Address, Address:="", SubAddress:=ActiveWorkbook.Worksheets("ApplicantInfo").Cells(InfoRow, 1).Address, TextToDisplay:=linkDisplay

                    'end of validations
                End If
            End If
        End If
    End Sub
    Public Sub GetFirstEmptyRow()
        Set sht = ActiveWorkbook.Worksheets("ApplicantInfo")
        sht.Activate
        Range("A1").Select
        Do
            If IsEmpty(ActiveCell) = False Then
                ActiveCell.Offset(1, 0).Select
            End If
        Loop Until IsEmpty(ActiveCell) = True

    End Sub
    Public Sub Save()

    End Sub
    Public Sub TimeBox_Change()

    End Sub

    Public Sub BranchBox_Change()
        'clear Date Box Values
        For i = DateBox.ListCount - 1 To 0 Step -1
            DateBox.RemoveItem i
        Next i
        'clear Time Box Values
        i = 0
        For i = TimeBox.ListCount - 1 To 0 Step -1
            TimeBox.RemoveItem i
        Next i
        'reset i to 0
        i = 0
        'populate dates
        Me.DateBox.List = Worksheets(BranchBox.Value).Range("A2:A31").Value
    End Sub
    Public Sub DateBox_Change()
        branch = BranchBox.Value
        Set sht = ActiveWorkbook.Worksheets(branch)
        dateSel = DateBox.Value

        'Get Row to scan
        For i = 2 To sht.Rows.Count
            Set cel = sht.Cells(i, 1)
            If cel.Value = dateSel Then
                rowOff = i
                Exit For
            End If
        Next i

        'Scan selected row for blank cells
        For i = 2 To sht.Columns.Count
            Set cel = sht.Cells(rowOff, i)
            If CStr(cel.Value) = "" Then
                Set matchingHeader = sht.Cells(1, i)
                TimeBox.AddItem matchingHeader.Text
            End If
        Next i
        Me.TimeBox.AddItem ("No Appointments Available")
    End Sub
</code>```

This is the line which errors:

```<code>sht.Hyperlinks.Add Anchor:=sht.Cells(row, column).Address, _
                   Address:="", _
                   SubAddress:=ActiveWorkbook.Worksheets("ApplicantInfo") _
                                  .Cells(InfoRow, 1).Address, _
                   TextToDisplay:=linkDisplay
</code>```

Help is much appreciated! Thanks in advance!

答:
```<code>sht.Hyperlinks.Add Anchor:=sht.Cells(row, column), _
              Address:="", _
              SubAddress:="'ApplicantInfo'!" & Cells(InfoRow, 1).Address(False, False), _
              TextToDisplay:=linkDisplay
</code>```

I'd typically use a utility method for this type of thing though.

E.g. something like:

```<code>Sub CreateHyperlink(FromCell As Range, ToCell As Range, Optional LinkText As String = "")
    Dim subAddr, txt

    subAddr = ToCell.Address(False, False)
    If FromCell.Worksheet.Name <> ToCell.Worksheet.Name Then
        subAddr = "'" & ToCell.Worksheet.Name & "'!" & subAddr
    End If

    txt = IIf(LinkText <> "", LinkText, FromCell.Value)
    If Len(txt) = 0 Then txt = "Go"

    With FromCell.Worksheet
        .Hyperlinks.Add Anchor:=FromCell, Address:="", _
                        SubAddress:=subAddr, TextToDisplay:=txt
    End With

End Sub
</code>```

Body:
So I have had a couple of questions I've asked regarding excel VBA, and I appreciate you all bearing with me as I stumble through learning about all this. Your answers have been a tremendous help and learning experience.

So far, I have a subroutine whose main responsibility is to write all of the values collected through a user form with various validations and dynamic comboboxes. My final task is to get this Subroutine to assign a hyperlink to the location selected by an earlier loop. But with my current syntax, I'm getting a "run-time error '1004' method '_default' of object 'range' failed". Some research proved that the cell coordinates require a .address property after them in order to avert this error, but it did not resolve the issue. The code is below:

    Option Explicit
    Dim cnt As Integer
    Dim i As Long, rowOff As Long
    Dim dateSel As String
    Dim timeSel As String
    Dim branch As String
    Dim sht As Worksheet
    Dim cel As Range
    Dim matchingHeader As Range

    Public Sub UserForm_Initialize()
        'clear form
        BranchBox.Value = ""
        DateBox.Value = ""
        TimeBox.Value = ""

        'populate sheet names from each branch
        For Each sht In ActiveWorkbook.Sheets
          If sht.Name = "ApplicantInfo" Then
            'Do Nothing
          Else
            Me.BranchBox.AddItem sht.Name
          End If
        Next sht
    End Sub

    Public Sub HoldButton_Click() 'revisit... throwing Time message box regardless what's selected
        If TimeBox.Value <> "" Then
            If DateBox.Value <> "" Then
                If BranchBox.Value <> "" Then
                    sht.Cells(rowOff, i).Value = "-"
                    'Save workbook
                Else
                    MsgBox "You must select a branch for your appointment"
                End If
            Else
                MsgBox "You must select a date for your appointment"
            End If
        Else
            MsgBox "You must select a time for your appointment"
        End If
    End Sub

    Private Sub ResetButton_Click()
        FirstName.Value = ""
        LastName.Value = ""
        EMail.Value = ""
        Phone.Value = ""
        Skills.Value = ""
        'BranchBox.Value = "" throws error
        DateBox.Value = ""
        TimeBox.Value = ""
    End Sub

    Private Sub ScheduleButton_Click()
        Dim row As Long, column As Long
        Dim linkDisplay As String
        'test for RowOff and i <> 0
        If IsNull(BranchBox) = True Then
            MsgBox "Select a branch for you interview before you click schedule"
        Else
            If IsNull(DateBox) = True Then
                MsgBox "Select a date for you interview before you click schedule"
            Else
                If IsNull(TimeBox) = True Then
                    MsgBox "Select a time for you interview before you click schedule"
                Else
                    'find first empty row in applicant profile tab.
                    'Insert applicant information in free row
                    'parse applicant name as a link to found free row above
                    'replace "-" placeholder for held appointment with applicant name as a link

                    Call GetFirstEmptyRow
                    'write selected values into row
                    Dim InfoRow As Integer
                    InfoRow = ActiveCell.row
                    ActiveCell.Value = ActiveCell.Offset(-5, 0).Value + 5
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = LastName.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = FirstName.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = EMail.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = Phone.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = Skills.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = BranchBox.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = DateBox.Value
                    ActiveCell.Offset(0, 1).Select
                    ActiveCell.Value = TimeBox.Value

                    branch = BranchBox.Value
                    Set sht = ActiveWorkbook.Worksheets(branch)
                    dateSel = DateBox.Value
                    timeSel = TimeBox.Value

                    'scan for selected date
                    For i = 2 To sht.Rows.Count
                        Set cel = sht.Cells(i, 1)
                        If cel.Value = dateSel Then
                            column = i
                            Exit For
                        End If
                    Next i

                    'Scan for selected time
                    For i = 2 To sht.Columns.Count
                        Set cel = sht.Cells(1, i)
                        If CStr(cel.Value) = timeSel Then
                            row = i
                            Exit For
                        End If
                    Next i

                    linkDisplay = LastName.Value & ", " & FirstName.Value
'This is the error
                    sht.Hyperlinks.Add Anchor:=sht.Cells(row, column).Address, Address:="", SubAddress:=ActiveWorkbook.Worksheets("ApplicantInfo").Cells(InfoRow, 1).Address, TextToDisplay:=linkDisplay

                    'end of validations
                End If
            End If
        End If
    End Sub
    Public Sub GetFirstEmptyRow()
        Set sht = ActiveWorkbook.Worksheets("ApplicantInfo")
        sht.Activate
        Range("A1").Select
        Do
            If IsEmpty(ActiveCell) = False Then
                ActiveCell.Offset(1, 0).Select
            End If
        Loop Until IsEmpty(ActiveCell) = True

    End Sub
    Public Sub Save()

    End Sub
    Public Sub TimeBox_Change()

    End Sub

    Public Sub BranchBox_Change()
        'clear Date Box Values
        For i = DateBox.ListCount - 1 To 0 Step -1
            DateBox.RemoveItem i
        Next i
        'clear Time Box Values
        i = 0
        For i = TimeBox.ListCount - 1 To 0 Step -1
            TimeBox.RemoveItem i
        Next i
        'reset i to 0
        i = 0
        'populate dates
        Me.DateBox.List = Worksheets(BranchBox.Value).Range("A2:A31").Value
    End Sub
    Public Sub DateBox_Change()
        branch = BranchBox.Value
        Set sht = ActiveWorkbook.Worksheets(branch)
        dateSel = DateBox.Value

        'Get Row to scan
        For i = 2 To sht.Rows.Count
            Set cel = sht.Cells(i, 1)
            If cel.Value = dateSel Then
                rowOff = i
                Exit For
            End If
        Next i

        'Scan selected row for blank cells
        For i = 2 To sht.Columns.Count
            Set cel = sht.Cells(rowOff, i)
            If CStr(cel.Value) = "" Then
                Set matchingHeader = sht.Cells(1, i)
                TimeBox.AddItem matchingHeader.Text
            End If
        Next i
        Me.TimeBox.AddItem ("No Appointments Available")
    End Sub

This is the line which errors:

sht.Hyperlinks.Add Anchor:=sht.Cells(row, column).Address, _
                   Address:="", _
                   SubAddress:=ActiveWorkbook.Worksheets("ApplicantInfo") _
                                  .Cells(InfoRow, 1).Address, _
                   TextToDisplay:=linkDisplay

Help is much appreciated! Thanks in advance!

Body:
sht.Hyperlinks.Add Anchor:=sht.Cells(row, column), _
              Address:="", _
              SubAddress:="'ApplicantInfo'!" & Cells(InfoRow, 1).Address(False, False), _
              TextToDisplay:=linkDisplay

I'd typically use a utility method for this type of thing though.

E.g. something like:

Sub CreateHyperlink(FromCell As Range, ToCell As Range, Optional LinkText As String = "")
    Dim subAddr, txt

    subAddr = ToCell.Address(False, False)
    If FromCell.Worksheet.Name <> ToCell.Worksheet.Name Then
        subAddr = "'" & ToCell.Worksheet.Name & "'!" & subAddr
    End If

    txt = IIf(LinkText <> "", LinkText, FromCell.Value)
    If Len(txt) = 0 Then txt = "Go"

    With FromCell.Worksheet
        .Hyperlinks.Add Anchor:=FromCell, Address:="", _
                        SubAddress:=subAddr, TextToDisplay:=txt
    End With

End Sub


问:
Changing css background image property by jquery setTimeout
I want to change my header image (which I gave it's source in the css, not in HTML) every 10 seconds Using jQuery.
I may have up to 15 16 images so the code I wrote may be too long for my js file.
I wrote the code below , but I'm looking for much compact code , hopefully using arrays.</p>

```<code>$(function() {
  setTimeout(function() {
    changeHeaderImg3()
  }, 10000);

  setTimeout(function() {
    changeHeaderImg2()
  }, 20000);

  setTimeout(function() {
    changeHeaderImg1()
  }, 30000);

  setTimeout(function() {
    changeHeaderImg4()
  }, 40000);
  setTimeout(function() {
    changeHeaderImg3()
  }, 50000);
});

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg2() {

  $('header').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg1() {

  $('header').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg4() {

  $('header').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};
</code>```

答:
If you have an array of image urls, you can use setInterval to periodically update your header/footer images. Something like this:</p>

```<code>var imgUrls = [
    'assets/img/bg1.jpg',
    'assets/img/bg2.jpg',
    'assets/img/bg3.jpg',
    'assets/img/bg4.jpg',
    // ... etc.
];

var currentImageIndex = 0;

// Create a callback that will be invoked every 10 seconds
setInterval(function() {
    var imgUrl = imgUrls[currentImageIndex++];
    $('header').css('background', 'url(" + imgUrl + ") center center').css('background-size', 'cover');
    $('footer').css('background', 'url(" + imgUrl + ") center center').css('background-size', 'cover');

    // Make sure the currentImageIndex doesn't get too big
    if (currentImageIndex >= imgUrls.length) {
        currentImageIndex = 0;
    }
}, 10000);
</code>```

Body:
I want to change my header image (which I gave it's source in the css, not in HTML) every 10 seconds Using jQuery.
I may have up to 15 16 images so the code I wrote may be too long for my js file.
I wrote the code below , but I'm looking for much compact code , hopefully using arrays.

$(function() {
  setTimeout(function() {
    changeHeaderImg3()
  }, 10000);

  setTimeout(function() {
    changeHeaderImg2()
  }, 20000);

  setTimeout(function() {
    changeHeaderImg1()
  }, 30000);

  setTimeout(function() {
    changeHeaderImg4()
  }, 40000);
  setTimeout(function() {
    changeHeaderImg3()
  }, 50000);
});

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg2() {

  $('header').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg1() {

  $('header').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg4() {

  $('header').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};

Body:
If you have an array of image urls, you can use setInterval to periodically update your header/footer images. Something like this:

var imgUrls = [
    'assets/img/bg1.jpg',
    'assets/img/bg2.jpg',
    'assets/img/bg3.jpg',
    'assets/img/bg4.jpg',
    // ... etc.
];

var currentImageIndex = 0;

// Create a callback that will be invoked every 10 seconds
setInterval(function() {
    var imgUrl = imgUrls[currentImageIndex++];
    $('header').css('background', 'url(" + imgUrl + ") center center').css('background-size', 'cover');
    $('footer').css('background', 'url(" + imgUrl + ") center center').css('background-size', 'cover');

    // Make sure the currentImageIndex doesn't get too big
    if (currentImageIndex >= imgUrls.length) {
        currentImageIndex = 0;
    }
}, 10000);


问:
How to get html tags from url?
How would you get all the HTML tags from a URL and print them?

答: Fetch it (using mechanize, urllib or whatever else you want), parse what you get (using elementtree, BeautifulSoup, lxml or whatever else you want) and you have what you want.

Title: How to get html tags from url?


问:
Passing property to components inside ng-content (properties which aren't available in the component where the markup lies)
I am trying to develop a carousel.

The desired end result should be that the developer would simply write the entire markup in one place (let's say in app.component.html) with only an options property and then, the carousel would take over.

Problem is that from carousel.component I need to set some properties on carousel-item.component (properties that app.component should have nothing to do with... but all the markup is in app.component.html).

How can I achieve this?

app.component.html:

```<code><carousel [options]="myOptions">
    <carousel-item *ngFor="let item of items">
        <img [src]="item.image" alt="" />
    </carousel-item>
</carousel>

<hr />

<carousel [options]="myOptions2">
    <carousel-item *ngFor="let item of items">
        <img [src]="item.image" alt="" />
    </carousel-item>
</carousel>
</code>```

carousel.component.html:

```<code><div class="carousel-stage">
    <ng-content></ng-content>
</div>
</code>```

carousel-item.component.html:

```<code><ng-content></ng-content>
</code>```

答:
I think the only solution is to go with @ContentChildren()

In my carousel.component.ts:

```<code>import { ContentChildren, ... } from '@angular/core';

// ...

export class CarouselComponent implements AfterContentInit {
  @ContentChildren(ItemComponent) carouselItems;

  ngAfterContentInit() {
    this.carouselItems.forEach((item: ItemComponent, currentIndex) => {
      // Do stuff with each item
      // Even call item's methods:
      item.setWidth(someComputedWidth);
      item.setClass(someClass);
    }
  }
}
</code>```

Then, in carousel-item.component.ts:

```<code>export class ItemComponent implements OnInit, OnDestroy {
  @HostBinding('style.width') itemWidth;
  @HostBinding('class') itemClass;
  @HostBinding('@fade') fadeAnimationState;

  setWidth(width) {
    this.itemWidth = width + 'px';
  }
  setClass(class) {
    this.itemClass = class;
  }
  setAnimationState(state) {
    this.fadeAnimationState = state;
  }
}
</code>```

Apparently, I can even bind animation triggers with @HostBinding. I assumed @HostBingind() was designed to only work with the standard html attributes (style, class etc.), but it seems that I can actually bind anything (literally anything).

Does anybody have a better solution? Before I accept my own answer...

Body:
I am trying to develop a carousel.

The desired end result should be that the developer would simply write the entire markup in one place (let's say in app.component.html) with only an options property and then, the carousel would take over.

Problem is that from carousel.component I need to set some properties on carousel-item.component (properties that app.component should have nothing to do with... but all the markup is in app.component.html).

How can I achieve this?

app.component.html:

<carousel [options]="myOptions">
    <carousel-item *ngFor="let item of items">

    </carousel-item>
</carousel>

<carousel [options]="myOptions2">
    <carousel-item *ngFor="let item of items">

    </carousel-item>
</carousel>

carousel.component.html:

    <ng-content></ng-content>

carousel-item.component.html:

<ng-content></ng-content>

Body:
I think the only solution is to go with @ContentChildren()

In my carousel.component.ts:

import { ContentChildren, ... } from '@angular/core';

// ...

export class CarouselComponent implements AfterContentInit {
  @ContentChildren(ItemComponent) carouselItems;

  ngAfterContentInit() {
    this.carouselItems.forEach((item: ItemComponent, currentIndex) => {
      // Do stuff with each item
      // Even call item's methods:
      item.setWidth(someComputedWidth);
      item.setClass(someClass);
    }
  }
}

Then, in carousel-item.component.ts:

export class ItemComponent implements OnInit, OnDestroy {
  @HostBinding('style.width') itemWidth;
  @HostBinding('class') itemClass;
  @HostBinding('@fade') fadeAnimationState;

  setWidth(width) {
    this.itemWidth = width + 'px';
  }
  setClass(class) {
    this.itemClass = class;
  }
  setAnimationState(state) {
    this.fadeAnimationState = state;
  }
}

Apparently, I can even bind animation triggers with @HostBinding. I assumed @HostBingind() was designed to only work with the standard html attributes (style, class etc.), but it seems that I can actually bind anything (literally anything).

Does anybody have a better solution? Before I accept my own answer...


问:
Gridview table not being displayed in asp.net webform
I just want to display the gridview with some specific queries.
I've tried doing it below.
This code shows "No data matches" when wrong parameter is passed in query ,but displays nothing even when parameters are correct.
I am new to asp.net .Please tell me,what important line ,I'm missing</p>

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["Filter"] = "ALL";
            BindGrid();
        }
    }

private void BindGrid()
    {
        DataTable dt = new DataTable();
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString1"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        string query = "SELECT ContactName, City, Country, PostalCode FROM Customers";
        SqlCommand cmd = new SqlCommand("SELECT ContactName, City, Country, PostalCode FROM Customers WHERE Country='UK'" );
        cmd.Connection = con;
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
</code>```

答:
The code is working and returning 7 rows from northwind database into the gridview.

Your connection string should be like this in web.config file:

```<code><connectionStrings>
      <add name="NorthwindConnectionString1" connectionString="server=.; database=northwnd; integrated security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
</code>```

Body:
I just want to display the gridview with some specific queries.
I've tried doing it below.
This code shows "No data matches" when wrong parameter is passed in query ,but displays nothing even when parameters are correct.
I am new to asp.net .Please tell me,what important line ,I'm missing

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["Filter"] = "ALL";
            BindGrid();
        }
    }

private void BindGrid()
    {
        DataTable dt = new DataTable();
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString1"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        string query = "SELECT ContactName, City, Country, PostalCode FROM Customers";
        SqlCommand cmd = new SqlCommand("SELECT ContactName, City, Country, PostalCode FROM Customers WHERE Country='UK'" );
        cmd.Connection = con;
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

Body:
The code is working and returning 7 rows from northwind database into the gridview.

Your connection string should be like this in web.config file:

<connectionStrings>
      <add name="NorthwindConnectionString1" connectionString="server=.; database=northwnd; integrated security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>