问:
ImportError: tensorflow/python/_pywrap_tensorflow.so: wrong ELF class: ELFCLASS64
I want to integrate TenserFlow on robot nao .
I have copied the library Tensorflow in a path : /home/nao , and i do :

```<code>export PYTHONPATH="${PYTHONPATH}:/home/nao/tensorflow"
</code>```

but if i import a lib tensorflow ... and run , he print :

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tensorflow/__init__.py", line 23, in <module>
    from tensorflow.python import *
  File "tensorflow/python/__init__.py", line 48, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: tensorflow/python/_pywrap_tensorflow.so: wrong ELF class: ELFCLASS64
</code>```

what is the problem ?

答:
In general you cannot install TensorFlow by copying an existing installation to a different computer. The error message wrong ELF class: ELFCLASS64 means that you are trying to load 64-bit code (for the native TensorFlow library) into a 32-bit process. There are two solutions:

If you have a x86_64 processor, install a 64-bit version of Python and install one of the standard Linux releases of TensorFlow using pip.

If you have a 32-bit processor, you will need to build TensorFlow from source with the appropriate compilation options for the target platform. (Note that TensorFlow on 32-bit platforms is not officially supported, so there is no guarantee that this will work, but at least one person has got TensorFlow to build on a 32-bit ARM platform.)

Body:
I want to integrate TenserFlow on robot nao .
I have copied the library Tensorflow in a path : /home/nao , and i do :

export PYTHONPATH="${PYTHONPATH}:/home/nao/tensorflow"

but if i import a lib tensorflow ... and run , he print :

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tensorflow/__init__.py", line 23, in <module>
    from tensorflow.python import *
  File "tensorflow/python/__init__.py", line 48, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: tensorflow/python/_pywrap_tensorflow.so: wrong ELF class: ELFCLASS64

what is the problem ?


来源: stackexchange

问:
How to get a sorted subvector out of a sorted vector, fast
I have a data structure like this:

```<code>struct X {
  float value;
  int id;
};
</code>```

a vector of those (size N (think 100000), sorted by value (stays constant during the execution of the program):

```<code>std::vector<X> values;
</code>```

Now, I want to write a function

```<code>void subvector(std::vector<X> const& values,
               std::vector<int> const& ids,
               std::vector<X>& out /*,
               helper data here */);
</code>```

that fills the out parameter with a sorted subset of values, given by the passed ids (size M < N (about 0.8 times N)), fast (memory is not an issue, and this will be done repeatedly, so building lookuptables (the helper data from the function parameters) or something else that is done only once is entirely ok).

My solution so far:

Build lookuptable lut containing id -> offset in values (preparation, so constant runtime)

create std::vector<X> tmp, size N, filled with invalid ids (linear in N)

for each id, copy values[lut[id]] to tmp[lut[id]] (linear in M)

loop over tmp, copying items to out (linear in N)

this is linear in N (as it's bigger than M), but the temporary variable and repeated copying bugs me. Is there a way to do it quicker than this? Note that M will be close to N, so things that are O(M log N) are unfavourable.

Edit: http://ideone.com/xR8Vp is a sample implementation of mentioned algorithm, to make the desired output clear and prove that it's doable in linear time - the question is about the possibility of avoiding the temporary variable or speeding it up in some other way, something that is not linear is not faster :).

答:
An alternative approach you could try is to use a hash table instead of a vector to look up ids in:

```<code>void subvector(std::vector<X> const& values,
               std::unordered_set<int> const& ids,
               std::vector<X>& out) {

    out.clear();
    out.reserve(ids.size());
    for(std::vector<X>::const_iterator i = values.begin(); i != values.end(); ++i) {
        if(ids.find(i->id) != ids.end()) {
            out.push_back(*i);
        }
    }
}
</code>```

This runs in linear time since unordered_set::find is constant expected time (assuming that we have no problems hashing ints). However I suspect it might not be as fast in practice as the approach you described initially using vectors.

ContentLicense: CC BY-SA 2.5

Body:
I have a data structure like this:

struct X {
  float value;
  int id;
};

a vector of those (size N (think 100000), sorted by value (stays constant during the execution of the program):

std::vector<X> values;

Now, I want to write a function

void subvector(std::vector<X> const& values,
               std::vector<int> const& ids,
               std::vector<X>& out /*,
               helper data here */);

that fills the out parameter with a sorted subset of values, given by the passed ids (size M < N (about 0.8 times N)), fast (memory is not an issue, and this will be done repeatedly, so building lookuptables (the helper data from the function parameters) or something else that is done only once is entirely ok).

My solution so far:

Build lookuptable lut containing id -> offset in values (preparation, so constant runtime)

create std::vector<X> tmp, size N, filled with invalid ids (linear in N)

for each id, copy values[lut[id]] to tmp[lut[id]] (linear in M)

loop over tmp, copying items to out (linear in N)

this is linear in N (as it's bigger than M), but the temporary variable and repeated copying bugs me. Is there a way to do it quicker than this? Note that M will be close to N, so things that are O(M log N) are unfavourable.

Edit: http://ideone.com/xR8Vp is a sample implementation of mentioned algorithm, to make the desired output clear and prove that it's doable in linear time - the question is about the possibility of avoiding the temporary variable or speeding it up in some other way, something that is not linear is not faster :).

Body:
An alternative approach you could try is to use a hash table instead of a vector to look up ids in:

void subvector(std::vector<X> const& values,
               std::unordered_set<int> const& ids,
               std::vector<X>& out) {

    out.clear();
    out.reserve(ids.size());
    for(std::vector<X>::const_iterator i = values.begin(); i != values.end(); ++i) {
        if(ids.find(i->id) != ids.end()) {
            out.push_back(*i);
        }
    }
}

This runs in linear time since unordered_set::find is constant expected time (assuming that we have no problems hashing ints). However I suspect it might not be as fast in practice as the approach you described initially using vectors.


问:
circe type field not showing
When encoding to Json with circe we really want the type field to show e.g.

```<code>scala> val fooJson = foo.asJson
fooJson: io.circe.Json =
{
  "this_is_a_string" : "abc",
  "another_field" : 123,
  "type" : "Foo"
}
</code>```

This is taken from the release notes which previously mentions that you can configure the encoding like this:

```<code>implicit val customConfig: Configuration =
Configuration.default.withSnakeCaseKeys.withDefaults.withDiscriminator("type")
</code>```

Also other information about circe here suggests that without any configuration you should get some class type information in the encoding json.

Am I missing something? How do you get the class type to show?

答:
UPDATE 30/03/2017: Follow up to OP's comment

I was able to make this work, as shown in the linked release notes.

Preparation step 1: add additional dependency to build.sbt

```<code>libraryDependencies += "io.circe" %% "circe-generic-extras" % "0.7.0"
</code>```

Preparation step 2: setup dummy sealed trait hierarchy

```<code>import io.circe.{ Decoder, Encoder }
import io.circe.parser._, io.circe.syntax._
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.auto._
import io.circe.generic.{ semiauto => boring } // <- This is the default generic derivation behaviour
import io.circe.generic.extras.{ semiauto => fancy } // <- This is the new generic derivation behaviour

implicit val customConfig: Configuration = Configuration.default.withDefaults.withDiscriminator("type")

sealed trait Stuff
case class Foo(thisIsAString: String, anotherField: Int = 13) extends Stuff
case class Bar(thisIsAString: String, anotherField: Int = 13) extends Stuff

object Foo {
  implicit val decodeBar: Decoder[Bar] = fancy.deriveDecoder
  implicit val encodeBar: Encoder[Bar] = fancy.deriveEncoder
}

object Bar {
  implicit val decodeBar: Decoder[Bar] = boring.deriveDecoder
  implicit val encodeBar: Encoder[Bar] = boring.deriveEncoder
}
</code>```

Actual code using this:

```<code>val foo: Stuff = Foo("abc", 123)
val bar: Stuff = Bar("xyz", 987)

val fooString = foo.asJson.noSpaces
// fooString: String = {"thisIsAString":"abc","anotherField":123,"type":"Foo"}

val barString = bar.asJson.noSpaces
// barString: String = {"thisIsAString":"xyz","anotherField":987,"type":"Bar"}

val bar2 = for{
  json <- parse(barString)
  bar2 <- json.as[Stuff]
} yield bar2
// bar2: scala.util.Either[io.circe.Error,Stuff] = Right(Bar(xyz,987))

val foo2 = for{
  json <- parse(fooString)
  foo2 <- json.as[Stuff]
} yield foo2
// foo2: scala.util.Either[io.circe.Error,Stuff] = Right(Foo(abc,123))
</code>```

So, provided you import the extra dependency (which is where Configuration comes from), it looks like it works.

Finally, as a sidenote, it does seem that there is some disconnection between Circe's DESIGN.md and practice, for which I am actually happy.

Original answer:
I am not sure this is supposed to be supported, by design.

Taken from Circe's DESIGN.md:

Implicit scope should not be used for configuration. Lots of people have asked for a way to configure generic codec derivation to use e.g. a type field as the discriminator for sealed trait hierarchies, or to use snake case for member names. argonaut-shapeless supports this quite straightforwardly with a JsonCoproductCodec type that the user can provide implicitly.

I don't want to criticize this approach—it's entirely idiomatic Scala, and it often works well in practice—but I personally don't like using implicit values for configuration, and I'd like to avoid it in circe until I am 100% convinced that there's no alternative way to provide this functionality.

What this means concretely: You'll probably never see an implicit argument that isn't a type class instance—i.e. that isn't a type constructor applied to a type in your model—in circe, and configuration of generic codec derivation is going to be relatively limited (compared to e.g. argonaut-shapeless) until we find a nice way to do this kind of thing with type tags or something similar.

In particular, customConfig: Configuration seems to be  exactly the type of argument that the last paragraph refers to (e.g. an implicit argument that isn't a type class instance)

I am sure that @travis-brown or any other Circe's main contributors could shed some more light on this, in case there was in fact a way of doing this - and I would be very happy to know it! :)

ContentLicense: CC BY-SA 3.0

Title: circe type field not showing

Body:
When encoding to Json with circe we really want the type field to show e.g.

scala> val fooJson = foo.asJson
fooJson: io.circe.Json =
{
  "this_is_a_string" : "abc",
  "another_field" : 123,
  "type" : "Foo"
}

This is taken from the release notes which previously mentions that you can configure the encoding like this:

implicit val customConfig: Configuration =
Configuration.default.withSnakeCaseKeys.withDefaults.withDiscriminator("type")

Also other information about circe here suggests that without any configuration you should get some class type information in the encoding json.

Am I missing something? How do you get the class type to show?

Body:
UPDATE 30/03/2017: Follow up to OP's comment

I was able to make this work, as shown in the linked release notes.

Preparation step 1: add additional dependency to build.sbt

libraryDependencies += "io.circe" %% "circe-generic-extras" % "0.7.0"

Preparation step 2: setup dummy sealed trait hierarchy

import io.circe.{ Decoder, Encoder }
import io.circe.parser._, io.circe.syntax._
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.auto._
import io.circe.generic.{ semiauto => boring } // <- This is the default generic derivation behaviour
import io.circe.generic.extras.{ semiauto => fancy } // <- This is the new generic derivation behaviour

implicit val customConfig: Configuration = Configuration.default.withDefaults.withDiscriminator("type")

sealed trait Stuff
case class Foo(thisIsAString: String, anotherField: Int = 13) extends Stuff
case class Bar(thisIsAString: String, anotherField: Int = 13) extends Stuff

object Foo {
  implicit val decodeBar: Decoder[Bar] = fancy.deriveDecoder
  implicit val encodeBar: Encoder[Bar] = fancy.deriveEncoder
}

object Bar {
  implicit val decodeBar: Decoder[Bar] = boring.deriveDecoder
  implicit val encodeBar: Encoder[Bar] = boring.deriveEncoder
}

Actual code using this:

val foo: Stuff = Foo("abc", 123)
val bar: Stuff = Bar("xyz", 987)

val fooString = foo.asJson.noSpaces
// fooString: String = {"thisIsAString":"abc","anotherField":123,"type":"Foo"}

val barString = bar.asJson.noSpaces
// barString: String = {"thisIsAString":"xyz","anotherField":987,"type":"Bar"}

val bar2 = for{
  json <- parse(barString)
  bar2 <- json.as[Stuff]
} yield bar2
// bar2: scala.util.Either[io.circe.Error,Stuff] = Right(Bar(xyz,987))

val foo2 = for{
  json <- parse(fooString)
  foo2 <- json.as[Stuff]
} yield foo2
// foo2: scala.util.Either[io.circe.Error,Stuff] = Right(Foo(abc,123))

So, provided you import the extra dependency (which is where Configuration comes from), it looks like it works.

Finally, as a sidenote, it does seem that there is some disconnection between Circe's DESIGN.md and practice, for which I am actually happy.

Original answer:
I am not sure this is supposed to be supported, by design.

Taken from Circe's DESIGN.md:

Implicit scope should not be used for configuration. Lots of people have asked for a way to configure generic codec derivation to use e.g. a type field as the discriminator for sealed trait hierarchies, or to use snake case for member names. argonaut-shapeless supports this quite straightforwardly with a JsonCoproductCodec type that the user can provide implicitly.

I don't want to criticize this approach—it's entirely idiomatic Scala, and it often works well in practice—but I personally don't like using implicit values for configuration, and I'd like to avoid it in circe until I am 100% convinced that there's no alternative way to provide this functionality.

What this means concretely: You'll probably never see an implicit argument that isn't a type class instance—i.e. that isn't a type constructor applied to a type in your model—in circe, and configuration of generic codec derivation is going to be relatively limited (compared to e.g. argonaut-shapeless) until we find a nice way to do this kind of thing with type tags or something similar.

In particular, customConfig: Configuration seems to be  exactly the type of argument that the last paragraph refers to (e.g. an implicit argument that isn't a type class instance)

I am sure that @travis-brown or any other Circe's main contributors could shed some more light on this, in case there was in fact a way of doing this - and I would be very happy to know it! :)


问:
QML: Fetch mouse event of MouseArea in C++
I am trying to connect MouseArea mouse event with C++, But the QQuickMouseArea is private, so i could not fetch the signal.

Like this:

```<code>QObject::connect(mouseAreaObj, SIGNAL(released(QMouseEvent*)),
                 handlerObj, SLOT(handleEvent(QMouseEvent*)));
</code>```

Is there any way to solve this?

And if not able, i wonder why Qt not allow us to access QQuickMouseArea.

答:
I made the connection in qml mouseArea.clicked.connect(cppObject.onClicked) and then in C++ simply received a QObject* which has properties as expected:

```<code>void CppClass::onClicked(QObject *event) {
    qDebug() << "clicked" << event->property("x").toInt();
}
</code>```

Body:
I am trying to connect MouseArea mouse event with C++, But the QQuickMouseArea is private, so i could not fetch the signal.

Like this:

QObject::connect(mouseAreaObj, SIGNAL(released(QMouseEvent*)),
                 handlerObj, SLOT(handleEvent(QMouseEvent*)));

Is there any way to solve this?

And if not able, i wonder why Qt not allow us to access QQuickMouseArea.

Body:
I made the connection in qml mouseArea.clicked.connect(cppObject.onClicked) and then in C++ simply received a QObject* which has properties as expected:

void CppClass::onClicked(QObject *event) {
    qDebug() << "clicked" << event->property("x").toInt();
}


问:
didReceiveMemoryWarning: what type of memory?
I have a base cordova app, with some objective-c code around cordova's framework. Sometimes I've didReceiveMemoryWarning notification, but I don't understand if the problem is the javascript inside the UIWebView or other.
The documentation says:

Your app never calls this method directly. Instead, this method is called when the system determines that the amount of available memory is low.

But my question is: what type of memory?
RAM? Heap allocations? Something else?

答: RAM, it is for RAM, if your app consuming more memory without realising it, and no memory to remain to process any more thread then, this didreceivememorywarning get called by system.</p>


问:
Blink the time like a real digital clock
I am displaying the current time like this way :

```<code>$('#mydiv').html(
   new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' }));
</code>```

and it is displayed for example like this :

16:13

How is it possible to make the two dots blink every one second like a real digital clock?

答:
Yeah, still a bit of fun, here's a slightly more verbose es6 example

function blinkingTime() {
  const timeString = new Date().toLocaleTimeString('en-US', {
    hour12: false,
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
  });
  const [hours, mins, seconds] = timeString.split(':');
  const centreChar = seconds % 2 === 0 ? ':' : ' ';
  return `${hours}${centreChar}${mins}`;
}

function updateTime() {
  console.log(blinkingTime());
  setTimeout(updateTime, 1000);
}

updateTime();```

Body:
I am displaying the current time like this way :

$('#mydiv').html(
   new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' }));

and it is displayed for example like this :

16:13

How is it possible to make the two dots blink every one second like a real digital clock?


问:
How do I return a List to JSON along with hard coded roots
I'm not entirely sure how to define this question but basically I'm developing an ASP.Net application where I am generating a JsonResult called IndexJson.

My code is as follows:

```<code>public JsonResult IndexJson()
{
    var contacts = (from x in db.ContactSet
                   select new
                   {
                       x.AccountId,
                       x.FirstName,
                       x.LastName,
                       x.FullName,
                       x.JobTitle,
                       x.ParentCustomerId,
                       x.EMailAddress1,
                       x.Telephone1,
                       x.MobilePhone,
                       x.Fax,
                       x.GenderCode,
                       x.BirthDate
                   }).ToList();

    return Json(contacts, JsonRequestBehavior.AllowGet);
}
</code>```

This works well at returning the following JSON:

```<code>[{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...]
</code>```

But now I want to return the following JSON (hard-coded for now, I will change the values later):

```<code>{
  "current": 1,
  "rowCount": 10,
  "rows": [{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...],
  "total": 1123
}
</code>```

How can I adapt my code to do that?

答:
You might like to define a (generic) type to store your extra fields and the list of items

```<code>public class ItemsWithTotal<T> // for pete sake find a better name!
{
    public int Current {get; set; }
    public int RowCount {get; set; }
    public int Total {get; set; }
    public List<T> Rows {get; set; }
}
</code>```

Usage would be

```<code>var contacts = (from x in db.ContactSet
               select new
               {
                   x.AccountId,
                   x.FirstName,
                   x.LastName,
                   x.FullName,
                   x.JobTitle,
                   x.ParentCustomerId,
                   x.EMailAddress1,
                   x.Telephone1,
                   x.MobilePhone,
                   x.Fax,
                   x.GenderCode,
                   x.BirthDate
               }).ToList();
var result = new ItemsWithTotal<ContactSet>(){
     Current = 1,
     RowCount = 10,
     Total = 1123,
     Rows = contacts
}
return Json(result);
</code>```

Body:
I'm not entirely sure how to define this question but basically I'm developing an ASP.Net application where I am generating a JsonResult called IndexJson.

My code is as follows:

public JsonResult IndexJson()
{
    var contacts = (from x in db.ContactSet
                   select new
                   {
                       x.AccountId,
                       x.FirstName,
                       x.LastName,
                       x.FullName,
                       x.JobTitle,
                       x.ParentCustomerId,
                       x.EMailAddress1,
                       x.Telephone1,
                       x.MobilePhone,
                       x.Fax,
                       x.GenderCode,
                       x.BirthDate
                   }).ToList();

    return Json(contacts, JsonRequestBehavior.AllowGet);
}

This works well at returning the following JSON:

[{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...]

But now I want to return the following JSON (hard-coded for now, I will change the values later):

{
  "current": 1,
  "rowCount": 10,
  "rows": [{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...],
  "total": 1123
}

How can I adapt my code to do that?

Body:
You might like to define a (generic) type to store your extra fields and the list of items

public class ItemsWithTotal<T> // for pete sake find a better name!
{
    public int Current {get; set; }
    public int RowCount {get; set; }
    public int Total {get; set; }
    public List<T> Rows {get; set; }
}

Usage would be

var contacts = (from x in db.ContactSet
               select new
               {
                   x.AccountId,
                   x.FirstName,
                   x.LastName,
                   x.FullName,
                   x.JobTitle,
                   x.ParentCustomerId,
                   x.EMailAddress1,
                   x.Telephone1,
                   x.MobilePhone,
                   x.Fax,
                   x.GenderCode,
                   x.BirthDate
               }).ToList();
var result = new ItemsWithTotal<ContactSet>(){
     Current = 1,
     RowCount = 10,
     Total = 1123,
     Rows = contacts
}
return Json(result);


问:
Pagination with the stored procedure
I am trying to add sorting feature of my pagination stored procedure.

How can I do this, so far I created this one. It works fine but when pass the @sort parameter, it didn't work.

```<code>ALTER PROCEDURE [dbo].[sp_Mk]
 @page INT,
 @size INT,
 @sort nvarchar(50) ,
 @totalrow INT  OUTPUT
AS
BEGIN
    DECLARE @offset INT
    DECLARE @newsize INT

    IF(@page=0)
    begin
       SET @offset = @page;
       SET @newsize = @size
    end
    ELSE
    begin
        SET @offset = @page+1;
        SET @newsize = @size-1
    end
    -- SET NOCOUNT ON added to prevent extra result sets from
    SET NOCOUNT ON;
    WITH OrderedSet AS
    (
      SELECT *,
          ROW_NUMBER() OVER (ORDER BY @sort DESC) AS 'Index'
      FROM [dbo].[Mk]
    )
   SELECT *
   FROM OrderedSet
   WHERE [Index] BETWEEN @offset AND (@offset + @newsize)

   SET @totalrow = (SELECT COUNT(*) FROM [dbo].[Mk])
END
</code>```

答:
I'm adding an answer since so many of the other answers suggest dynamic SQL, which is not a best practice. You can add pagination using an OFFSET-FETCH clause, which provides you with an option to fetch only a window or page of results from a result set.

Note: OFFSET-FETCH can be used only with the ORDER BY clause.

Example:

```<code>SELECT First Name + ' ' + Last Name FROM Employees
ORDER BY First Name
OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;
</code>```

Title: Pagination with the stored procedure

Body:
I am trying to add sorting feature of my pagination stored procedure.

How can I do this, so far I created this one. It works fine but when pass the @sort parameter, it didn't work.

ALTER PROCEDURE [dbo].[sp_Mk]
 @page INT,
 @size INT,
 @sort nvarchar(50) ,
 @totalrow INT  OUTPUT
AS
BEGIN
    DECLARE @offset INT
    DECLARE @newsize INT

    IF(@page=0)
    begin
       SET @offset = @page;
       SET @newsize = @size
    end
    ELSE
    begin
        SET @offset = @page+1;
        SET @newsize = @size-1
    end
    -- SET NOCOUNT ON added to prevent extra result sets from
    SET NOCOUNT ON;
    WITH OrderedSet AS
    (
      SELECT *,
          ROW_NUMBER() OVER (ORDER BY @sort DESC) AS 'Index'
      FROM [dbo].[Mk]
    )
   SELECT *
   FROM OrderedSet
   WHERE [Index] BETWEEN @offset AND (@offset + @newsize)

   SET @totalrow = (SELECT COUNT(*) FROM [dbo].[Mk])
END

Body:
I'm adding an answer since so many of the other answers suggest dynamic SQL, which is not a best practice. You can add pagination using an OFFSET-FETCH clause, which provides you with an option to fetch only a window or page of results from a result set.

Note: OFFSET-FETCH can be used only with the ORDER BY clause.

Example:

SELECT First Name + ' ' + Last Name FROM Employees
ORDER BY First Name
OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;


问:
Mongo & Angular 2
I would like to know how to integrate a Mongo database (to store information, a form ...) in an angular 2 project
If you have a tutorial, documents that give me a step to follow, do not hesitate, I wait for your answers to unlock me</p>

答:
The process is actually fairly simple. Here is the run down of the basics you will need...

Create your api to handle your CRUD operations

Create your Database in MongoDB

Create your angular 2 service to handle CRUD functions to API

Create an angular 2 service to call out to your running API

I have a Github of how I did it as well as the sources of the tutorials that I followed: https://github.com/bcrawford11/Angular2-w-CRUD-Api-MongoDb

Title: Mongo & Angular 2


答:
You could create a viewmodel that looks the same. ie

```<code>    public MyReturnModel{
      public int Current {get; set;}
      public int rowCount {get; set;}
      public List<contacts> rows {get; set;}
      public int total {get; set;}
    }
</code>```

Then in your method, just assign each property appropriately and return the JSONify the new viewmodel and return it.

Title: How do I return a List to JSON along with hard coded roots

Body:
You could create a viewmodel that looks the same. ie

    public MyReturnModel{
      public int Current {get; set;}
      public int rowCount {get; set;}
      public List<contacts> rows {get; set;}
      public int total {get; set;}
    }

Then in your method, just assign each property appropriately and return the JSONify the new viewmodel and return it.


问:
PHP dynamic form with text field and checkboxes combined
I have a form with an image, the image file name with a checkbox, and a field text (with the quantity) (this is dynamically created when the admin uploads the image on a wordpress folder)
The user select the checkbox and write a quantity, I want that information sent to an email.
I made that possible, but it only works when I click on all the checkboxes, if one of them is not selected, it sends the email with empty information.

this is the part of the code where I think the problem is:

```<code>    // if the submit button is clicked, send the email
       if ( isset( $_POST['cf-submitted'] ) ) {
        $result ="";
        $myQuantity = $_POST["quantity"];
        $myFile = $_POST["fileName"];
        //Combine both filename and quantity arrays
        $values = array_combine($myFile, $myQuantity);

        if(!empty($_POST["fileName"])){
            foreach($values as $key => $value){
                $result .= "$key - Quantity: $value <br/>";
            }
        }
</code>```

...
Any help will be appreciated.

update:
this is the whole form just in case:

```<code>    echo '<div class="images-form"><form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
        foreach($images as $image) {
            echo '<div class="thumb"><img src="';
            echo $uploads['baseurl'].'/'.$a['folder_name'].'/'.$image;
            echo '" alt="" /><br/>';
            $fileName = basename($path.'/'.$image);
            echo $fileName;
            echo '  <input name="fileName[]" type ="checkbox" value="'.$fileName.'" /><br/>';
            echo 'Quantity: <input name="quantity[]" type="text" value="" size="5" /></div>';
        }

    echo  '<div class="send-form"><input type="submit" name="cf-submitted" value="Send email"/></div></form></div>';

  // if the submit button is clicked, send the email
    if ( isset( $_POST['cf-submitted'] ) ) {
        $result ="";
        $myQuantity = $_POST["quantity"];
        $myFile = $_POST["fileName"];
        //Combine both arrays
        $values = array_combine($myFile, $myQuantity);

        if(!empty($_POST["fileName"])){
            foreach($values as $key => $value){
                $result .= "$key - Quantity: $value <br/>";
            }
        }

        // to get wordpress user name and last name
        global $current_user;
        get_currentuserinfo();
        $userName = $current_user->user_firstname;
        $userLastName = $current_user->user_lastname ;

        $to = get_option( 'admin_email' );// get the blog administrator's email address
        $email = $current_user->user_email;
        $headers = "From: $email" . "\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        $subject = "Print request";
        $message = "<html><body>";
        $message .= $userName." ".$userLastName." wants to print the following file(s): <br/>".$result;
        $message .= "</body></html>";

        // If email has been process for sending, display a success message
        if ( wp_mail( $to, $subject, $message, $headers ) ) {
            echo '<div>';
            echo '<p>Thanks for contacting me, expect a response soon.</p>';
            echo '</div>';
        } else {
            echo 'An unexpected error occurred';
        }
    }
</code>```

答:
When the browser submits a form, only checkboxes that are checked are passed to the server.  Text boxes on the other hand, are always passed even if they are blank. PHP creates an array using just the checked boxes for $_POST['fileName'] and an array of all of the quantity boxes in $_POST['quantity'].

When less than all checkboxes are selected, $myQuantity will have a different number of elements than $myFile.

Which leads to the problem.
Array_combine returns false if the number of elements in each array isn't equal.

A simple solution to this is to index your input boxes and eliminate the array_combine.

```<code>$index=0;
foreach($images as $image) {
    $index++;
    echo '<div class="thumb"><img src="';
    echo $uploads['baseurl'].'/'.$a['folder_name'].'/'.$image;
    echo '" alt="" /><br/>';
    $fileName = basename($path.'/'.$image);
    echo $fileName;

    // use $index between the [] of the field name.  PHP will use it as the key value when it creates the array.
    echo '  <input name="fileName['. $index .']" type ="checkbox" value="'.$fileName.'" /><br/>';
    echo 'Quantity: <input name="quantity['. $index .']" type="text" value="" size="5" /></div>';
}
</code>```

Now you receive an indexed array for $_POST['filename'].

```<code>$result ="";
$myQuantity = $_POST["quantity"];
$myFile = $_POST["fileName"];
// eliminate the array_combine.

if(!empty($_POST["fileName"])){

    foreach( $myFile as $key => $value){
        // key will now be the $index value from the form generation.
        // $value will be the file name.
        // The index will match the $_POST['quantity'] array allowing
        // simple lookup by key value.
        $result .= "$value- Quantity: ". $myQuantity[$key] ."<br/>";
    }
}
</code>```

Body:
I have a form with an image, the image file name with a checkbox, and a field text (with the quantity) (this is dynamically created when the admin uploads the image on a wordpress folder)
The user select the checkbox and write a quantity, I want that information sent to an email.
I made that possible, but it only works when I click on all the checkboxes, if one of them is not selected, it sends the email with empty information.

this is the part of the code where I think the problem is:

    // if the submit button is clicked, send the email
       if ( isset( $_POST['cf-submitted'] ) ) {
        $result ="";
        $myQuantity = $_POST["quantity"];
        $myFile = $_POST["fileName"];
        //Combine both filename and quantity arrays
        $values = array_combine($myFile, $myQuantity);

        if(!empty($_POST["fileName"])){
            foreach($values as $key => $value){
                $result .= "$key - Quantity: $value
";
            }
        }

...
Any help will be appreciated.

update:
this is the whole form just in case:

    echo '
<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
        foreach($images as $image) {
            echo '

';
            $fileName = basename($path.'/'.$image);
            echo $fileName;
            echo '  <input name="fileName[]" type ="checkbox" value="'.$fileName.'" />
';
            echo 'Quantity: <input name="quantity[]" type="text" value="" size="5" />
';
        }

    echo  '
<input type="submit" name="cf-submitted" value="Send email"/>
</form>
';

  // if the submit button is clicked, send the email
    if ( isset( $_POST['cf-submitted'] ) ) {
        $result ="";
        $myQuantity = $_POST["quantity"];
        $myFile = $_POST["fileName"];
        //Combine both arrays
        $values = array_combine($myFile, $myQuantity);

        if(!empty($_POST["fileName"])){
            foreach($values as $key => $value){
                $result .= "$key - Quantity: $value
";
            }
        }

        // to get wordpress user name and last name
        global $current_user;
        get_currentuserinfo();
        $userName = $current_user->user_firstname;
        $userLastName = $current_user->user_lastname ;

        $to = get_option( 'admin_email' );// get the blog administrator's email address
        $email = $current_user->user_email;
        $headers = "From: $email" . "\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        $subject = "Print request";
        $message = "";
        $message .= $userName." ".$userLastName." wants to print the following file(s):
".$result;
        $message .= "";

        // If email has been process for sending, display a success message
        if ( wp_mail( $to, $subject, $message, $headers ) ) {
            echo '
';
            echo '
Thanks for contacting me, expect a response soon.
';
            echo '
';
        } else {
            echo 'An unexpected error occurred';
        }
    }

Body:
When the browser submits a form, only checkboxes that are checked are passed to the server.  Text boxes on the other hand, are always passed even if they are blank. PHP creates an array using just the checked boxes for $_POST['fileName'] and an array of all of the quantity boxes in $_POST['quantity'].

When less than all checkboxes are selected, $myQuantity will have a different number of elements than $myFile.

Which leads to the problem.
Array_combine returns false if the number of elements in each array isn't equal.

A simple solution to this is to index your input boxes and eliminate the array_combine.

$index=0;
foreach($images as $image) {
    $index++;
    echo '<div class="thumb"><img src="';
    echo $uploads['baseurl'].'/'.$a['folder_name'].'/'.$image;
    echo '" alt="" /><br/>';
    $fileName = basename($path.'/'.$image);
    echo $fileName;

    // use $index between the [] of the field name.  PHP will use it as the key value when it creates the array.
    echo '&nbsp;&nbsp;<input name="fileName['. $index .']" type ="checkbox" value="'.$fileName.'" /><br/>';
    echo 'Quantity: <input name="quantity['. $index .']" type="text" value="" size="5" /></div>';
}

Now you receive an indexed array for $_POST['filename'].

$result ="";
$myQuantity = $_POST["quantity"];
$myFile = $_POST["fileName"];
// eliminate the array_combine.

if(!empty($_POST["fileName"])){

    foreach( $myFile as $key => $value){
        // key will now be the $index value from the form generation.
        // $value will be the file name.
        // The index will match the $_POST['quantity'] array allowing
        // simple lookup by key value.
        $result .= "$value- Quantity: ". $myQuantity[$key] ."<br/>";
    }
}


问:
Weblogic Console not showing applications
I use a Weblogic 10.3.6 Server on which I have numerous Enterprise Applications, Web Applications and Libraries deployed.
A few days ago, after a deployment glitch, the Console's deployment view does not show applications anymore. Only libraries are listed.

Does anyone know where I can start looking to fix the problem? How are enterprise and web applications found by the server to be displayed?

Edit 1:
Applications are in fact running, accessible and listed under the /Environment/Server//Deployments tab. From there I cannot update/start/stop them, however. They are missing only in the /Deployments view.

config/config.xml seems to be correct. All applications are listed there.

答:
Okay, that fixed it.

The Admin Server had an application called wls-cat.war installed, which failed upon server start. Apparently, it is Oracle's Classloader Analysis Tool which may come in useful in debugging. Not in this case, though. It failed on Admin Server startup. You cannot start, stop, deploy, undeploy or redeploy it with the standard means (it is an internal application).

In the end, I shut down the server and manually removed it from the /config/config.xml file.

```<code><app-deployment>
    <name>wls-cat</name>
    <target>SBV00PG9_PERM01_ADMIN_SPU_PORTAL</target>
    <module-type>war</module-type>
    <source-path>${WL_HOME}/server/lib/wls-cat.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
    <cache-in-app-directory>false</cache-in-app-directory>
</app-deployment>
</code>```

After that, the server shows applications again. I may need to reinstall the app at a later time, but for now the server seems to run well without it.

Very special thanks to Emmanuel Collin for setting me on the right path.

Body:
Okay, that fixed it.

The Admin Server had an application called wls-cat.war installed, which failed upon server start. Apparently, it is Oracle's Classloader Analysis Tool which may come in useful in debugging. Not in this case, though. It failed on Admin Server startup. You cannot start, stop, deploy, undeploy or redeploy it with the standard means (it is an internal application).

In the end, I shut down the server and manually removed it from the /config/config.xml file.

<app-deployment>
    <name>wls-cat</name>
    <target>SBV00PG9_PERM01_ADMIN_SPU_PORTAL</target>
    <module-type>war</module-type>
    <source-path>${WL_HOME}/server/lib/wls-cat.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
    <cache-in-app-directory>false</cache-in-app-directory>
</app-deployment>

After that, the server shows applications again. I may need to reinstall the app at a later time, but for now the server seems to run well without it.

Very special thanks to Emmanuel Collin for setting me on the right path.


问:
Why I see the contour of a logo in the navbar on Google Chrome?
I'm creating my website and I want to add a log on the navbar.

index.html:

```<code><header>
  <div class="header_logo">
    <img class="logo" value="logo"/>
  </div>
  <div>

  </div>
</header>
</code>```

style.css:

```<code>  .logo
  {
   background-image: url("../icons/car.png");
   border-style: none;
   position: absolute;
   left: 38px;
   top: 19px;
   width: 137px;
   height: 49px;
  }
  .header_logo
  {
   background-color: #000000;
   position: absolute;
   left: 0px;
   top: 0px;
   width: 100%;
   height: 75px;
  }
</code>```

the logo is:
car.png

But when I test the website it works well on Explorer and Firefox but on Chrome I got a white contour surrounded the logo and the background of the navbar is black.
How can I fix that?

答:
Looking at the PNG file. it looks like it has a white border around it. replace the image with one without a white border and you will be good.

use this file instead
Car.png

EDIT: After looking at it, it looks to be an issue with how Chrome works with the img tag. just use a div tag for it. for example the HTML:

```<code><header>
    <div class="header_logo">
        <div class="logo" value="logo"></div>
    </div>
    <div>

    </div>
</header>
</code>```

And for the CSS:

```<code>.logo {
    background-image: url("../icons/car.png");
    border-style: none;
    position: absolute;
    left: 38px;
    top: 19px;
    width: 137px;
    height: 49px;
}
.header_logo {
    background-color: #000000;
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 75px;
}
</code>```

https://codepen.io/anon/pen/QpJbwy

If you need to use an img tag, you must have a src attribute.

Body:
I'm creating my website and I want to add a log on the navbar.

index.html:

style.css:

  .logo
  {
   background-image: url("../icons/car.png");
   border-style: none;
   position: absolute;
   left: 38px;
   top: 19px;
   width: 137px;
   height: 49px;
  }
  .header_logo
  {
   background-color: #000000;
   position: absolute;
   left: 0px;
   top: 0px;
   width: 100%;
   height: 75px;
  }

the logo is:
car.png

But when I test the website it works well on Explorer and Firefox but on Chrome I got a white contour surrounded the logo and the background of the navbar is black.
How can I fix that?

Body:
Looking at the PNG file. it looks like it has a white border around it. replace the image with one without a white border and you will be good.

use this file instead
Car.png

EDIT: After looking at it, it looks to be an issue with how Chrome works with the img tag. just use a div tag for it. for example the HTML:

<header>
    <div class="header_logo">
        <div class="logo" value="logo"></div>
    </div>
    <div>

    </div>
</header>

And for the CSS:

.logo {
    background-image: url("../icons/car.png");
    border-style: none;
    position: absolute;
    left: 38px;
    top: 19px;
    width: 137px;
    height: 49px;
}
.header_logo {
    background-color: #000000;
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 75px;
}

https://codepen.io/anon/pen/QpJbwy

If you need to use an img tag, you must have a src attribute.


问:
Turning a list of lists or array into a nxn binary matrix
Ok so I need to take the following format of input file

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

and then turn it into a matrice where the left hand column represents the customer ID and the right hand column is the Item ID.

I can get Python to import the data however I'm struggling to manipulate it to the way I need.

and example of how I need the data would be:

```<code>          Item 1   Item 2  Item 3
Customer1:  1        2       0
Customer2:  1        0       2
</code>```

Here are the methods I've used to import the data:

```<code>def DataImport(filename):

    Data = []
    with open(filename) as f:
        for line in f:
            Data.append([int(v) for v in line.split()])
    return Data
</code>```

(incomplete)

```<code>def ImportData(filename):
    if filename == "history.txt":
        Option1 = np.loadtxt(filename, skiprows=1)
        CustomerID = np.loadtxt(filename, skiprows=1, usecols=(0,))
        ItemID = np.loadtxt(filename, skiprows=1, usecols=(1,))
        print(CustomerID)
        print(ItemID)
        print(Option1)
        Option11 = []
        for i in Option1:
            if i[i][0] == i[0]:
                Option11.append(i[0][1])
        print(Option11)
    else:
        Data = np.loadtxt(filename)

def ImportData(filename):
    rawdata = {}
    File = open(filename, "r")

    for line in File:
        rawdata[len(rawdata)+1] = line.rstrip("\n")
    File.close()
    print(rawdata)

def ImportData2(filename):
    with open(filename, newline='') as file:
        reader = csv.reader(file, delimiter=' ')
        next(reader)
        TRvalues = dict(reader)
    print(TRvalues)
</code>```

I think the numpy method presents in a way that would be easiest to work with but I'm not sure how to get Python to itterate using the customerID as a key and then adding the values in the way previously mentioned.

I'm not sure if I've explained that well but I can answer questions if you need more clarification.

答:
In principle I highly recommend using something like PANDAS (http://pandas.pydata.org/pandas-docs/stable/io.html), especially

```<code>pandas.read_tabel
</code>```

will generate a pandas data-frame that you can manipulate as you like.
However if you don't like that you can also just iterate by column rather than row by simply using

```<code>for row in matrix.T:
  instructions for rows...
</code>```

rather then

```<code>for col in matrix:
  instructions for columns...
</code>```

hope it helps.

Body:
Ok so I need to take the following format of input file

5 5 12
1 1
1 2
2 1
2 3
3 1
3 2
3 4
4 2
4 4
1 2
2 3
5 5

and then turn it into a matrice where the left hand column represents the customer ID and the right hand column is the Item ID.

I can get Python to import the data however I'm struggling to manipulate it to the way I need.

and example of how I need the data would be:

          Item 1   Item 2  Item 3
Customer1:  1        2       0
Customer2:  1        0       2

Here are the methods I've used to import the data:

def DataImport(filename):

    Data = []
    with open(filename) as f:
        for line in f:
            Data.append([int(v) for v in line.split()])
    return Data

(incomplete)

def ImportData(filename):
    if filename == "history.txt":
        Option1 = np.loadtxt(filename, skiprows=1)
        CustomerID = np.loadtxt(filename, skiprows=1, usecols=(0,))
        ItemID = np.loadtxt(filename, skiprows=1, usecols=(1,))
        print(CustomerID)
        print(ItemID)
        print(Option1)
        Option11 = []
        for i in Option1:
            if i[i][0] == i[0]:
                Option11.append(i[0][1])
        print(Option11)
    else:
        Data = np.loadtxt(filename)

def ImportData(filename):
    rawdata = {}
    File = open(filename, "r")

    for line in File:
        rawdata[len(rawdata)+1] = line.rstrip("\n")
    File.close()
    print(rawdata)

def ImportData2(filename):
    with open(filename, newline='') as file:
        reader = csv.reader(file, delimiter=' ')
        next(reader)
        TRvalues = dict(reader)
    print(TRvalues)

I think the numpy method presents in a way that would be easiest to work with but I'm not sure how to get Python to itterate using the customerID as a key and then adding the values in the way previously mentioned.

I'm not sure if I've explained that well but I can answer questions if you need more clarification.

Body:
In principle I highly recommend using something like PANDAS (http://pandas.pydata.org/pandas-docs/stable/io.html), especially

pandas.read_tabel

will generate a pandas data-frame that you can manipulate as you like.
However if you don't like that you can also just iterate by column rather than row by simply using

for row in matrix.T:
  instructions for rows...

rather then

for col in matrix:
  instructions for columns...

hope it helps.


答:
You can use dplyr group_by and summarise
Combine first to "tot.data". Then

library(dplyr)

group_by(tot.data, quality_score) %>% summarise(Mean1 = mean(outcome))

Title: Compute Multiple Means in Dataframe in R

Body:
I have a dataframe with 2 columns. A quality score, and an outcomes. Outcomes are either 1 or 0. Quality Scores are different integers from 1 - 135. This is a snapshot of the dataframe:

For each quality score, I would like to compute the mean. I can do it for one Quality Score at a time as such:

test <- subset(deletion_qs, qs == 10)

sum(test$outcomes)/length(test$outcomes)

[1] 0.4

But this is too slow. I was wondering if there is a way using one of the apply functions?

Here is the data:

quality_score <- c(2, 1  ,18  , 1  , 2  , 1  , 1 ,  1  , 2 ,  1,   1  , 1  , 1 ,  1  ,10 , 10  ,10,  10 , 10 , 10 , 10 , 10,  10 , 10 ,  1  ,29 ,1 , 29  ,63  , 1  ,25 ,  1  , 1  ,52  ,28  , 1 ,  1  ,10 ,  3,  28  , 1 , 20,   1, 10, 1 , 10 ,  3  , 1  , 3 , 10  ,10 , 56 , 1,   1,   2 ,  3 ,  2 ,  1 ,  1,  44 ,  1 ,  1,  10 , 33 , 67  ,67,  19  , 8 , 39,  10 ,  2  , 1 , 42 , 22,   7 , 93 ,  1  , 12 , 10 ,135 ,  1 , 31 ,  6 , 16,  15 ,  1 , 35 ,  1,  10 , 10)

outcome <- c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0,
0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1)


问:
What do curly braces in the Windows registry mean?
I've been wondering this for a while and can't seem to get answer.

In Windows (maybe other places too), what do the curly braces mean? I'm guessing it has to do with hex but not sure.

Any help would be appreciated.

*UPDATE

I'm sorry I wasn't as specific as I should have been. I was talking about in the registry, but I've also seen it in folder paths.

答:
In programming, curly braces are used for a lot of different things.  Different languages use them in completely different contexts.

If you're talking about program flow in C++, I like to think of them as tiers that progressively get more specific.  Example:

```<code>string myName = "Max";

if (myName[0] == 'M') // If the first letter of myName is M...
{
    cout << "The first letter is M." << endl;

    if (myName.length() == 3) // If myName is three characters long...
    {
        cout << "myName is three chars long." << endl;

        if(myName[2] == 'x') // If the third letter is x...
        {
             cout << "The third letter is x." << endl;
        }
    }
}
</code>```

They're also used in array assignment in C++, like so:

int myArray[5] = {1, 2, 3, 4, 5};

There are other uses, but these two are probably the most common.

Body:
In programming, curly braces are used for a lot of different things.  Different languages use them in completely different contexts.

If you're talking about program flow in C++, I like to think of them as tiers that progressively get more specific.  Example:

string myName = "Max";

if (myName[0] == 'M') // If the first letter of myName is M...
{
    cout << "The first letter is M." << endl;

    if (myName.length() == 3) // If myName is three characters long...
    {
        cout << "myName is three chars long." << endl;

        if(myName[2] == 'x') // If the third letter is x...
        {
             cout << "The third letter is x." << endl;
        }
    }
}

They're also used in array assignment in C++, like so:

int myArray[5] = {1, 2, 3, 4, 5};

There are other uses, but these two are probably the most common.


问:
Is it possible to insert a "sub" label into a BasicBlock in LLVM?
Suppose I've a BasicBlock with label, e.g., entry.

Now, I would like to insert a "sub" label into this BasicBlock without breaking up the block into two parts.

In assembly, it would look like:

```<code>entry:
...
.mylabel1:
...
.mylabel2:
...
</code>```

Is it possible to insert labels into a BasicBlock to divide it into "parts", but without splitting the block?

答:
No.

By definition, a basic block only has one entry point, and that's how it's implemented in LLVM. A label is an entry point, so what you're asking for is not possible.

Body:
Suppose I've a BasicBlock with label, e.g., entry.

Now, I would like to insert a "sub" label into this BasicBlock without breaking up the block into two parts.

In assembly, it would look like:

entry:
...
.mylabel1:
...
.mylabel2:
...

Is it possible to insert labels into a BasicBlock to divide it into "parts", but without splitting the block?


问:
Error with overload operator>>
Trying to use operator>> for my class plane, and I have an error in my main(). It says that

```<code>"no operator ">>" matches these operands    Air.
operand types are: std::istream >> Aircraft *"
</code>```

my main():

```<code>int main()
{
    Aircraft* air[2];
    int choice;
    std::cout << "Plane '1' and Helicopter '2'" << std::endl;
    std::cin >> choice;
    if (choice == 1)
    {
        Plane p;
        air[0] = new Plane;
        std::cin >> air[0]; //HERE IS AN ERROR
        air[0]->ShowTabl();
        std::cout << air[0];
    }
    /*if (choice == 2)
    {
        //air[1] = new Helicopter;
        //TODO: << and >>
    }*/
    system("pause");
    return 0;
}
</code>```

My read():

```<code>std::istream& Aircraft::read(std::istream& frFile)
{
    std::cout << "Name: ";
    frFile >> Name;
    std::cout << "Weight: ";
    frFile >> weight;
    return frFile;
}
</code>```

Operator >>:

it is in (.h):

friend std::istream& operator>> (std::istream& is, Aircraft& A);

it is in (.cpp):

```<code>std::istream& operator >> (std::istream& is,  Aircraft& A)
{
    return A.read(is);
}
</code>```

As for using in a way , like this ,so it is perfect:

```<code>Plane p;
    air[0] = new Plane;
    std::cin >> p; // it's okay
</code>```

What do I do wrong with this?

答:
Throughout this answer I assume that both Helicopter and Plane publicly inherit from Aircraft. If they don’t, the explanation is still correct but the rest of the advice is probably wrong.

The line

```<code>Aircraft* air[2];
</code>```

declares air as an array of two pointers to Aircraft.¹ You probably do want the pointers, despite some of the other comments, because you seem to be working with inheritance so you can’t just use Aircraft directly. So far you only ever have one of them, so I’m less sure that you need an array, but that may be useful later.

Because air contains pointers to Aircraft instead of directly containing Aircraft, you need to deal with the pointed-to objects at the extra level of indirection. Your stream extraction operator (operator>>) is for an Aircraft, not for an Aircraft*, so if you want to use it with the Plane you allocated on line 10 of your main function, you need to extracted it to the pointed-to Aircraft, *air[0], instead of the pointer, air[0].

I am not sure how well the Aircraft::read method could work when it isn’t virtual (I would expect you’d also want to read in a Plane-specific property like wingspan), but perhaps you plan to implement that later once you have this part working, which is sensible.

¹ You can see this by reading the type from the variable name outward, going to the right before the left. Thus, you see air, go to the right to see [2] meaning “array of two”, followed by * meaning “pointer to”, followed by Aircraft. Knowing this rule helps a lot when you have more complicated types, like functions that accept arrays.

Title: Error with overload operator>>

Body:
Trying to use operator>> for my class plane, and I have an error in my main(). It says that

"no operator ">>" matches these operands    Air.
operand types are: std::istream >> Aircraft *"

my main():

int main()
{
    Aircraft* air[2];
    int choice;
    std::cout << "Plane '1' and Helicopter '2'" << std::endl;
    std::cin >> choice;
    if (choice == 1)
    {
        Plane p;
        air[0] = new Plane;
        std::cin >> air[0]; //HERE IS AN ERROR
        air[0]->ShowTabl();
        std::cout << air[0];
    }
    /*if (choice == 2)
    {
        //air[1] = new Helicopter;
        //TODO: << and >>
    }*/
    system("pause");
    return 0;
}

My read():

std::istream& Aircraft::read(std::istream& frFile)
{
    std::cout << "Name: ";
    frFile >> Name;
    std::cout << "Weight: ";
    frFile >> weight;
    return frFile;
}

Operator >>:

it is in (.h):

friend std::istream& operator>> (std::istream& is, Aircraft& A);

it is in (.cpp):

std::istream& operator >> (std::istream& is,  Aircraft& A)
{
    return A.read(is);
}

As for using in a way , like this ,so it is perfect:

Plane p;
    air[0] = new Plane;
    std::cin >> p; // it's okay

What do I do wrong with this?

Body:
Throughout this answer I assume that both Helicopter and Plane publicly inherit from Aircraft. If they don’t, the explanation is still correct but the rest of the advice is probably wrong.

The line

Aircraft* air[2];

declares air as an array of two pointers to Aircraft.¹ You probably do want the pointers, despite some of the other comments, because you seem to be working with inheritance so you can’t just use Aircraft directly. So far you only ever have one of them, so I’m less sure that you need an array, but that may be useful later.

Because air contains pointers to Aircraft instead of directly containing Aircraft, you need to deal with the pointed-to objects at the extra level of indirection. Your stream extraction operator (operator>>) is for an Aircraft, not for an Aircraft*, so if you want to use it with the Plane you allocated on line 10 of your main function, you need to extracted it to the pointed-to Aircraft, *air[0], instead of the pointer, air[0].

I am not sure how well the Aircraft::read method could work when it isn’t virtual (I would expect you’d also want to read in a Plane-specific property like wingspan), but perhaps you plan to implement that later once you have this part working, which is sensible.

¹ You can see this by reading the type from the variable name outward, going to the right before the left. Thus, you see air, go to the right to see [2] meaning “array of two”, followed by * meaning “pointer to”, followed by Aircraft. Knowing this rule helps a lot when you have more complicated types, like functions that accept arrays.


问:
I can't run a android project on my Zenphone 5
I have a problem with the marked area in the image below.

Can anyone please tell me how to fix this?

答:
You should see a popup dialog on your phone, where you should approve installing app. If there is not a dialog, go to Developer options, turn off USB debugging and then turn it on. The dialog should come.

Also, as John Joe has mentioned, ASUS devices need Enable ADB integration to be turned on (they somehow switch it off, happened on my Zenfone 2).


问:
Read 2D matrix from file to 2D int array in C#
I have problem in reading 2D text from file and import it to an int array. Specifically, my text file looks like below:

2,3,4,5,6

5,2,3,4,5

2,4,6,7,4

2,7,8,5,6

So each cell in matrix is separated by comma and each new row starts with new line.

I tried many ways to make it works but I can't! Simply, I want an int[][] or int[,] array at the end.

P.S: I can read 1-D matrix simply to int[] as below:

```<code>int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();
</code>```

答:
Just to illustrate the point, the problem, that you have is storing the references of each line into a jagged array int[][] or into a bi-dimensional array int[,]

I suggest you to take a look here before https://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx?f=255&MSPPError=-2147217396

If you want to create a jagged array is simple, the first dimension will be the amount of lines that you have on your file. Remember this jagged array has arrays in each positions

```<code>int[][] a = new int[amountOfLinesTxt][];
</code>```

because you can get the array per line, the only thing that you need to do is to assign the array to the specific position for example

```<code>int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();
a[0] = array
</code>```

Same thing for the other lines.

Now if you want to use a bi-dimensional array you need to specify in your case from the begging the dimensions, for example int[,] a = new int[amountOfRowsTxt, amountofColumnsTxt];

then while you are reading your lines you need to save the items inside of it.

```<code>int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();

for(int i = 0; array.Length; i ++)
{
   a[currentRow, i] = array[i];
}
</code>```

Got the idea? Of course there are better ways to get the result using Linq, just take a look on the previous answers. Hope this helps

Body:
I have problem in reading 2D text from file and import it to an int array. Specifically, my text file looks like below:

2,3,4,5,6

5,2,3,4,5

2,4,6,7,4

2,7,8,5,6

So each cell in matrix is separated by comma and each new row starts with new line.

I tried many ways to make it works but I can't! Simply, I want an int[][] or int[,] array at the end.

P.S: I can read 1-D matrix simply to int[] as below:

int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();

Body:
Just to illustrate the point, the problem, that you have is storing the references of each line into a jagged array int[][] or into a bi-dimensional array int[,]

I suggest you to take a look here before https://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx?f=255&MSPPError=-2147217396

If you want to create a jagged array is simple, the first dimension will be the amount of lines that you have on your file. Remember this jagged array has arrays in each positions

int[][] a = new int[amountOfLinesTxt][];

because you can get the array per line, the only thing that you need to do is to assign the array to the specific position for example

int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();
a[0] = array

Same thing for the other lines.

Now if you want to use a bi-dimensional array you need to specify in your case from the begging the dimensions, for example int[,] a = new int[amountOfRowsTxt, amountofColumnsTxt];

then while you are reading your lines you need to save the items inside of it.

int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();

for(int i = 0; array.Length; i ++)
{
   a[currentRow, i] = array[i];
}

Got the idea? Of course there are better ways to get the result using Linq, just take a look on the previous answers. Hope this helps


问:
Alternate Icon in iOS 10.3
I have the info on how to set up alternate icons in iOS 10.3 adding the key in the Info.plist.  However, what I am not sure of is which sizes are needed for each alternate.  I use assets folders right now, and have to put in about 12 different sized icons for spotlight, different iphone and ipad sizes, etc.  What's the rule on the alternate ones?</p>

答:
To change the icon you need to use setAlternateIconName(_:completionHandler:)

You need to put the CFBundleAlternateIcons in Info.plist. The Alternate icon sizes are same as of primary icon sizes listed here.

You can read full docs in Contents of the CFBundleAlternateIcons Dictionary Entry

Edit: This excerpt is from the above docs icon sizes listed here

Provide visually consistent alternate icons in all necessary sizes. Like your primary app icon, each alternate app icon is delivered as a collection of related images that vary in size. When the user chooses an alternate icon, the appropriate sizes of that icon replace your primary app icon on the Home screen, in Spotlight, and elsewhere in the system. To ensure that alternate icons appear consistently throughout the system—the user shouldn't see one version of your icon on the Home screen and a completely different version in Settings, for example—provide them in the same sizes you provide for your primary app icon (with the exception of the large App Store icon). See App Icon Sizes

ContentLicense: CC BY-SA 4.0

Title: Alternate Icon in iOS 10.3


问:
is it considered bad practice to write c code in objective-c / cocoa framework?
I am writing some Objective-C code which will be publicly available. The code mainly consists of well known algorithms which would benefit from optimization. I am planning on writing most of the code in C to reduce the overhead on creating objects and garbage collection. Is this considered bad practice?</p>

答:
No it's not. This is done quite frequently actually.

Generally one does this when one needs time critical code to run quicker (everything else equal, calling a C function is quicker than an Objective-C method).

However, it may also be nicer in some other cases to write C functions instead.

Remember though that Objective-C is a superset of C. Everything C can do, Objective-C can do, and it should not be considered bad to do anything C can do. There may be cases where doing some things is discouraged, but anyway.


问:
IE 11 Downloads Page instead of opening it, works in Chrome and Firefox
I have a Django application running on a Ubuntu, Apache server that works perfectly under Chrome and Firefox, however when I access it via Internet Explorer 11, it will not load.  Instead of rendering the HTML in the browser window, I receive the

Do you want to open or save XXXXXX from XXXXXX message.

Tried debugging the site in IE, and the console shows a warming:

HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype:
  ""

however this is the first line of the HTML.

In Chrome, this error does not appear but I get a warning about the page including a password field (have not flipped to https yet as I am still in development).

The only other thing I can find (in debug) is that the "Content Type" shows up blank, but other sites I review have entries (text/html, etc.) but I don't see how to populate this information.

Please advise how I can troubleshoot this further to find the cause of the page not loading.

Here is the code:

```<code><!DOCTYPE html>
<html>
<head>

<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ops</title>

<link rel="stylesheet" type="text/css" href="/static/content/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/static/content/site.css" />
<script src="/static/scripts/modernizr-2.6.2.js"></script>
</head>

<body>
<div class="navbar navbar-inverse navbar-fixed-top opsBlack">
    <div class="container">

        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <img src="/static/images/test-N.png" width ="40" align="left"/>
            <a href="/" class="navbar-brand">ops</a>
        </div>
        <div class="navbar-collapse collapse opsBlack">
            <ul class="nav navbar-nav">
                <li><a href=#>Test</a></li>
                <li><a href=#>Test</a></li>
                <li><a href=#>Test</a></li>
                <li><a href="#" class="bluetext">Mar 28, 2017</a></li>
            </ul>

<ul class="nav navbar-nav navbar-right">
<li><a href="../registration/login.html">Log in</a></li>
</ul>
        </div>
    </div>
</div>
<h2></h2>
<div class="row">
<div class="col-md-8">
    <section id="loginForm">
        <form action="/accounts/login/" method="post" class="form-horizontal">
            <input type='hidden' name='csrfmiddlewaretoken' value='deleted' />
            <h4>Use your Account to log in.</h4>
            <hr />
            <div class="form-group">
                <label for="id_username" class="col-md-2 control-label">User name</label>
                <div class="col-md-10">
                    <input type="text" class="form-control" placeholder="Username" required=Yes name="username" />
                </div>
            </div>
            <div class="form-group">
                <label for="id_password" class="col-md-2 control-label">Password</label>
                <div class="col-md-10">
                    <input type="password" class="form-control" placeholder="Password" required=Yes name="password"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="hidden" name="next" value="/" />
                    <input type="submit" value="Log in" class="btn btn-default" />
                </div>
            </div>

        </form>
    </section>
</div>
</div>
    <hr/>
    <footer>
        <p>©  - ops</p>
    </footer>
<script src="/static/scripts/jquery-1.10.2.js"></script>
<script src="/static/scripts/bootstrap.js"></script>
<script src="/static/scripts/respond.js"></script>
</body>
</html>
</code>```

答:
Found the problem.

In my initial 'home' view, I redirected the user to the login page incorrectly.

Originally, I had:

```<code>return render(request, "registration/login.html", {}, RequestContext(request))
</code>```

Which was incorrect, and should have been:

```<code>return render(request, "registration/login.html")
</code>```

This was creating an issue with the HTTP Headers, and confusing IE 11.

Body:
I have a Django application running on a Ubuntu, Apache server that works perfectly under Chrome and Firefox, however when I access it via Internet Explorer 11, it will not load.  Instead of rendering the HTML in the browser window, I receive the

Do you want to open or save XXXXXX from XXXXXX message.

Tried debugging the site in IE, and the console shows a warming:

HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype:
  ""

however this is the first line of the HTML.

In Chrome, this error does not appear but I get a warning about the page including a password field (have not flipped to https yet as I am still in development).

The only other thing I can find (in debug) is that the "Content Type" shows up blank, but other sites I review have entries (text/html, etc.) but I don't see how to populate this information.

Please advise how I can troubleshoot this further to find the cause of the page not loading.

Here is the code:

<!DOCTYPE html>

<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ops</title>

<link rel="stylesheet" type="text/css" href="/static/content/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/static/content/site.css" />

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

            </button>

            ops

Test

Test

Test

Mar 28, 2017

Log in

        <form action="/accounts/login/" method="post" class="form-horizontal">
            <input type='hidden' name='csrfmiddlewaretoken' value='deleted' />

Use your Account to log in.

                User name

                    <input type="text" class="form-control" placeholder="Username" required=Yes name="username" />

                Password

                    <input type="password" class="form-control" placeholder="Password" required=Yes name="password"/>

                    <input type="hidden" name="next" value="/" />
                    <input type="submit" value="Log in" class="btn btn-default" />

        </form>

©  - ops

Body:
Found the problem.

In my initial 'home' view, I redirected the user to the login page incorrectly.

Originally, I had:

return render(request, "registration/login.html", {}, RequestContext(request))

Which was incorrect, and should have been:

return render(request, "registration/login.html")

This was creating an issue with the HTTP Headers, and confusing IE 11.


问:
Android: register new PhoneAccount for telecom
I'm trying to make a new PhoneAccount to use my implementation of ConnectionService. In the documentation it says I need to register a new PhoneAccount with TelecomManager and then select it in my phone-app's settings.

Here's my code:

```<code>TelecomManager telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);

ComponentName componentName = newComponentName("se.example.connectionservicestandalonetest", "se.example.connectionservicestandalonetest.MyConnectionService");
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(componentName, "Admin");
PhoneAccount phoneAccount = PhoneAccount.builder(phoneAccountHandle, "Admin").build();

telecomManager.registerPhoneAccount(phoneAccount);
</code>```

As you can see, it creates a new ComponentName that points towards my implementation of ConnectionService, then creates a new PhoneAccountHandle where I supply the ComponentName and a unique account-name. I then supply the PhoneAccountHandle in the PhoneAccount buildes, as well as label (a name?), to create a new PhoneAccount. Lastly I register the account in the telecomManager.

When I open up the phone app, nothing has changed. I see no where I could possibly change the PhoneAccount... Any ideas?

Thanks!

答:
As an addendum to j__m's answer: I found a way to check if the phone account is activated without setting up a call:

```<code>private boolean checkAccountConnection(Context context) {
    boolean isConnected = false;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            final List<PhoneAccountHandle> enabledAccounts = telecomManager.getCallCapablePhoneAccounts();
            for (PhoneAccountHandle account : enabledAccounts) {
                if (account.getComponentName().getClassName().equals(MyConnectionService.class.getCanonicalName())) {
                    isConnected = true;
                    break;
                }
            }
        }

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

As stated in the Javadoc to android.telecom.TelecomManager.getCallCapablePhoneAccounts()

Returns a list of {@link PhoneAccountHandle}s which can be used to make and receive phone calls. The returned list includes only those accounts which have been explicitly enabled by the user.

Body:
I'm trying to make a new PhoneAccount to use my implementation of ConnectionService. In the documentation it says I need to register a new PhoneAccount with TelecomManager and then select it in my phone-app's settings.

Here's my code:

TelecomManager telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);

ComponentName componentName = newComponentName("se.example.connectionservicestandalonetest", "se.example.connectionservicestandalonetest.MyConnectionService");
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(componentName, "Admin");
PhoneAccount phoneAccount = PhoneAccount.builder(phoneAccountHandle, "Admin").build();

telecomManager.registerPhoneAccount(phoneAccount);

As you can see, it creates a new ComponentName that points towards my implementation of ConnectionService, then creates a new PhoneAccountHandle where I supply the ComponentName and a unique account-name. I then supply the PhoneAccountHandle in the PhoneAccount buildes, as well as label (a name?), to create a new PhoneAccount. Lastly I register the account in the telecomManager.

When I open up the phone app, nothing has changed. I see no where I could possibly change the PhoneAccount... Any ideas?

Thanks!

Body:
As an addendum to j__m's answer: I found a way to check if the phone account is activated without setting up a call:

private boolean checkAccountConnection(Context context) {
    boolean isConnected = false;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            final List<PhoneAccountHandle> enabledAccounts = telecomManager.getCallCapablePhoneAccounts();
            for (PhoneAccountHandle account : enabledAccounts) {
                if (account.getComponentName().getClassName().equals(MyConnectionService.class.getCanonicalName())) {
                    isConnected = true;
                    break;
                }
            }
        }

    }
    return isConnected;
}

As stated in the Javadoc to android.telecom.TelecomManager.getCallCapablePhoneAccounts()

Returns a list of {@link PhoneAccountHandle}s which can be used to make and receive phone calls. The returned list includes only those accounts which have been explicitly enabled by the user.


问:
how to distribute make builds to separate dirs from single makefile?
I have C sources in 'modules' directory. They are just *.c and corresponding .h files. I have also 'tests' directory with test.c programs used for testing modules. Finally I have have also some independent programs in 'progs' directory, and they have names expressed by *.c mask.

I would like to have a single main Makefile where I have commands to compile targets called 'modules', 'progs' and 'tests'. However, I have no idea how to define all dependencies in order to compile everything properly. My trials are not working.

Here is the simplest makefile which obviously do not work at all:

```<code>COMPILER=gcc
SOURCES=modules progs tests
CFLAGS=-O2 -g -Og -Wall -std=c14
INCLUDES= -Imodules -I. -I../modules         # no idea which is needed!
LFLAGS=-lm -lSDL -lSDL_image

all: modules tests progs

modules: modules/*.c modules/*.h
  ${COMPILER} ${CFLAGS} ${INCLUDES} -c $< -o $@

progs: progs/*.c
  ${COMPILER} ${CFLAGS} ${INCLUDES} -c $< -o $@ ${LFLAGS}

tests: tests/*.c
  ${COMPILER} ${CFLAGS} ${INCLUDES} -c $< -o $@ ${LFLAGS}

#%.o: %.c   # no idea how to force compiling to modules OR progs, etc.
</code>```

I have heard about CPP and auto-creating dependencies for modules, but nothing I've tried is working, even after trying gnumakefile help examples or other manuals. My case is somehow different :(

答:
I think that this solution, which I found few days ago, will/could work:

Directories I have are 'src', 'tests', and 'utils'. The global Makefile, looks like the following:

```<code>DIRS = src tests utils

all:
        make -C src -f Makefile
        make -C tests -f Makefile
        make -C utils -f Makefile

clean:
        make -C src -f Makefile clean
        make -C tests -f Makefile clean
        make -C utils -f Makefile clean

.PHONY: all clean ${DIRS}
</code>```

This works, although I would rather prefer some automated solution for iterating over all dirs from ${DIRS}. For only three of them, it's OK for me to type commands three times.
Then, in each directory, its own Makefile exists:

In src:

```<code>SOURCES = ${wildcard *.c}
HEADERS = ${SOURCES:.c=.h}
OBJECTS = ${SOURCES:.c=.o}
DEPENDS = ${OBJECTS:.o=.d}
INCLUDE = -I/usr/include/SDL

LDFLAGS = -lm -lSDL -lSDL_image
CCFLAGS = -O2 -g -Wall -pedantic ${INCLUDE}

all: ${OBJECTS}

-include ${DEPENDS}

%.d: %.c
        ${CPP} ${CCFLAGS} $< -MM -MT ${@:.d=.o} >$@

%.o: %.c
        ${CC} ${CCFLAGS} -c $< -o $@

clean:
        rm -f ${OBJECTS} ${DEPENDS}

.PHONY: clean all
</code>```

Then, in tests and utils (they are very similar):

```<code>SOURCES = ${wildcard *.c}
OBJECTS = ${SOURCES:.c=.o}
DEPENDS = ${OBJECTS:.o=.d}
PROGRAM = ${patsubst %.c,%,${wildcard test*.c}}
INCLUDE = -I/usr/include/SDL -I../src

LDFLAGS = -lm -lSDL -lSDL_image
CCFLAGS = -O2 -g -Wall -pedantic ${INCLUDE}

all: ${PROGRAM}

test%: test%.o
        ${CC} ${CCFLAGS} $+ ../src/*.o -o $@ ${LDFLAGS}

#-include ${DEPENDS}

#%.d: %.c
#       ${CPP} ${CCFLAGS} $< -MM -MT ${@:.d=.o} >$@

%.o: %.c
        ${CC} ${CCFLAGS} -c $< -o $@

clean:
        rm -f ${PROGRAM} ${OBJECTS} ${DEPENDS}

.PHONY: clean all
</code>```

and in 'utils' I have:

```<code>SOURCES = ${wildcard *.c}
OBJECTS = ${SOURCES:.c=.o}
DEPENDS = ${OBJECTS:.o=.d}
PROGRAM = ${SOURCES:.c=}
INCLUDE = -I/usr/include/SDL -I../src

LDFLAGS = -lm -lSDL -lSDL_image
CCFLAGS = -O2 -g -Wall -pedantic ${INCLUDE}

all: calcVariance getScanLine

calcVariance: calcVariance.c
        ${CC} ${CCFLAGS} $< ../src/*.o -o $@ ${LDFLAGS}

getScanLine: getScanLine.c
        ${CC} ${CCFLAGS} $< ../src/*.o -o $@ ${LDFLAGS}

%.d: %.c
        ${CPP} ${CCFLAGS} $< -MM -MT ${@:.d=.o} >$@

%.o: %.c
        ${CC} ${CCFLAGS} -c $< -o $@

clean:
        rm -f ${PROGRAM} ${OBJECTS} ${DEPENDS}

-include ${DEPENDS}

.PHONY: clean all
</code>```

Again, I did not found anything nice to iterate over all programs from ${SOURCES}, because some dependencies were not calculated properly, and because of that I defined and put verbatim program names into rules. Maybe somebody will have some clue how to do that better. Also, I learned that using preprocessor to automatically determine all dependencies is a pretty nice trick, which in turn makes all makefiles lot better, automated and precise.

Drawbacks:
1. Some lack of automation, especially in 'utils' (my automated obvious version fooled make and it tried to build calcVariance with getScanLine.o object file, which failed miserably.

Make is not seeing new rebuilded objects from ../src/*.o files after rebuilding them from 'src' dir. Nothing changed is seen, when I try to build from 'tests' or 'utils', after I rebuilt 'src'. I have to force clean and then make all to rebuild those directories.

I have the feeling that this solution is not the best I could achieve due to my lack of understanding how make is working. So, I think lot's of things could be improved. Any comments are very welcome.

Body:
I have C sources in 'modules' directory. They are just *.c and corresponding .h files. I have also 'tests' directory with test.c programs used for testing modules. Finally I have have also some independent programs in 'progs' directory, and they have names expressed by *.c mask.

I would like to have a single main Makefile where I have commands to compile targets called 'modules', 'progs' and 'tests'. However, I have no idea how to define all dependencies in order to compile everything properly. My trials are not working.

Here is the simplest makefile which obviously do not work at all:

COMPILER=gcc
SOURCES=modules progs tests
CFLAGS=-O2 -g -Og -Wall -std=c14
INCLUDES= -Imodules -I. -I../modules         # no idea which is needed!
LFLAGS=-lm -lSDL -lSDL_image

all: modules tests progs

modules: modules/*.c modules/*.h
  ${COMPILER} ${CFLAGS} ${INCLUDES} -c $< -o $@

progs: progs/*.c
  ${COMPILER} ${CFLAGS} ${INCLUDES} -c $< -o $@ ${LFLAGS}

tests: tests/*.c
  ${COMPILER} ${CFLAGS} ${INCLUDES} -c $< -o $@ ${LFLAGS}

#%.o: %.c   # no idea how to force compiling to modules OR progs, etc.

I have heard about CPP and auto-creating dependencies for modules, but nothing I've tried is working, even after trying gnumakefile help examples or other manuals. My case is somehow different :(

Body:
I think that this solution, which I found few days ago, will/could work:

Directories I have are 'src', 'tests', and 'utils'. The global Makefile, looks like the following:

DIRS = src tests utils

all:
        make -C src -f Makefile
        make -C tests -f Makefile
        make -C utils -f Makefile

clean:
        make -C src -f Makefile clean
        make -C tests -f Makefile clean
        make -C utils -f Makefile clean

.PHONY: all clean ${DIRS}

This works, although I would rather prefer some automated solution for iterating over all dirs from ${DIRS}. For only three of them, it's OK for me to type commands three times.
Then, in each directory, its own Makefile exists:

In src:

SOURCES = ${wildcard *.c}
HEADERS = ${SOURCES:.c=.h}
OBJECTS = ${SOURCES:.c=.o}
DEPENDS = ${OBJECTS:.o=.d}
INCLUDE = -I/usr/include/SDL

LDFLAGS = -lm -lSDL -lSDL_image
CCFLAGS = -O2 -g -Wall -pedantic ${INCLUDE}

all: ${OBJECTS}

-include ${DEPENDS}

%.d: %.c
        ${CPP} ${CCFLAGS} $< -MM -MT ${@:.d=.o} >$@

%.o: %.c
        ${CC} ${CCFLAGS} -c $< -o $@

clean:
        rm -f ${OBJECTS} ${DEPENDS}

.PHONY: clean all

Then, in tests and utils (they are very similar):

SOURCES = ${wildcard *.c}
OBJECTS = ${SOURCES:.c=.o}
DEPENDS = ${OBJECTS:.o=.d}
PROGRAM = ${patsubst %.c,%,${wildcard test*.c}}
INCLUDE = -I/usr/include/SDL -I../src

LDFLAGS = -lm -lSDL -lSDL_image
CCFLAGS = -O2 -g -Wall -pedantic ${INCLUDE}

all: ${PROGRAM}

test%: test%.o
        ${CC} ${CCFLAGS} $+ ../src/*.o -o $@ ${LDFLAGS}

#-include ${DEPENDS}

#%.d: %.c
#       ${CPP} ${CCFLAGS} $< -MM -MT ${@:.d=.o} >$@

%.o: %.c
        ${CC} ${CCFLAGS} -c $< -o $@

clean:
        rm -f ${PROGRAM} ${OBJECTS} ${DEPENDS}

.PHONY: clean all

and in 'utils' I have:

SOURCES = ${wildcard *.c}
OBJECTS = ${SOURCES:.c=.o}
DEPENDS = ${OBJECTS:.o=.d}
PROGRAM = ${SOURCES:.c=}
INCLUDE = -I/usr/include/SDL -I../src

LDFLAGS = -lm -lSDL -lSDL_image
CCFLAGS = -O2 -g -Wall -pedantic ${INCLUDE}

all: calcVariance getScanLine

calcVariance: calcVariance.c
        ${CC} ${CCFLAGS} $< ../src/*.o -o $@ ${LDFLAGS}

getScanLine: getScanLine.c
        ${CC} ${CCFLAGS} $< ../src/*.o -o $@ ${LDFLAGS}

%.d: %.c
        ${CPP} ${CCFLAGS} $< -MM -MT ${@:.d=.o} >$@

%.o: %.c
        ${CC} ${CCFLAGS} -c $< -o $@

clean:
        rm -f ${PROGRAM} ${OBJECTS} ${DEPENDS}

-include ${DEPENDS}

.PHONY: clean all

Again, I did not found anything nice to iterate over all programs from ${SOURCES}, because some dependencies were not calculated properly, and because of that I defined and put verbatim program names into rules. Maybe somebody will have some clue how to do that better. Also, I learned that using preprocessor to automatically determine all dependencies is a pretty nice trick, which in turn makes all makefiles lot better, automated and precise.

Drawbacks:
1. Some lack of automation, especially in 'utils' (my automated obvious version fooled make and it tried to build calcVariance with getScanLine.o object file, which failed miserably.

Make is not seeing new rebuilded objects from ../src/*.o files after rebuilding them from 'src' dir. Nothing changed is seen, when I try to build from 'tests' or 'utils', after I rebuilt 'src'. I have to force clean and then make all to rebuild those directories.

I have the feeling that this solution is not the best I could achieve due to my lack of understanding how make is working. So, I think lot's of things could be improved. Any comments are very welcome.


问:
How to handle events on markup inserted through jQuery
I have the following markup:

```<code><div id="section">
    <input type="text" id="myInput">
</div>
</code>```

On click of a button, I'm cloning and inserting a copy of this markup with unique IDs using this script:

```<code>var newSection = $("#section").clone();
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
$(newSection).find("input").attr('id', "myInput" + ($("input[id^=myInput").length + 1));
$("div[id^=section").last().after(newSection);
</code>```

My resulting markup:

```<code><div id="section">
    <input type="text" id="myInput">
</div>
<div id="section2">
    <input type="text" id="myInput2">
</div>
</code>```

My question: is it possible to manipulate this new markup with jQuery? I assume since it has loaded dynamically after a click it's not part of the initial DOM and jQuery doesn't recognize it? I'm having trouble getting a click event to register on #myInput2. Thanks for any insight.

答:
if you wrap them in a container, you can delegate that container keep track of the buttons. For example, if you have:

```<code><div id="container">
    <div id="section">
        <input type="text" id="myInput">
    </div>
    <div id="section2">
        <input type="text" id="myInput2">
    </div>
</div>
</code>```

you can delegate the task to the container like this:

```<code>$("#container").on("click","input",function(){
    var newSection = $("#section").clone();
    $(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
    $(newSection).find("input").attr('id', "myInput" +
    ($("input[id^=myInput").length + 1));
    $("div[id^=section").last().after(newSection);
}
</code>```

This way you can manipulate them if not defined while binding

EDIT: Updated from .delegate() to .on()

Body:
I have the following markup:

    <input type="text" id="myInput">

On click of a button, I'm cloning and inserting a copy of this markup with unique IDs using this script:

var newSection = $("#section").clone();
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
$(newSection).find("input").attr('id', "myInput" + ($("input[id^=myInput").length + 1));
$("div[id^=section").last().after(newSection);

My resulting markup:

    <input type="text" id="myInput">

    <input type="text" id="myInput2">

My question: is it possible to manipulate this new markup with jQuery? I assume since it has loaded dynamically after a click it's not part of the initial DOM and jQuery doesn't recognize it? I'm having trouble getting a click event to register on #myInput2. Thanks for any insight.

Body:
if you wrap them in a container, you can delegate that container keep track of the buttons. For example, if you have:

<div id="container">
    <div id="section">
        <input type="text" id="myInput">
    </div>
    <div id="section2">
        <input type="text" id="myInput2">
    </div>
</div>

you can delegate the task to the container like this:

$("#container").on("click","input",function(){
    var newSection = $("#section").clone();
    $(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
    $(newSection).find("input").attr('id', "myInput" +
    ($("input[id^=myInput").length + 1));
    $("div[id^=section").last().after(newSection);
}

This way you can manipulate them if not defined while binding

EDIT: Updated from .delegate() to .on()


问:
HashSet - Is accessing/finding a object in HashSet O(1)?
Average complexity of accessing a particular object/data in an array is O(n) , here n is array length.
Is it O(1) for finding an element in HashSet for Java?

```<code>HashSet<String> set=new HashSet<String>();
......
System.out.print(set.contains(Some_string);
</code>```

Is contains(String) method performing at O(1)?

答:
Yes. The basic operations (add, remove, contains, and size) run in constant time.

http://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html

Body:
Average complexity of accessing a particular object/data in an array is O(n) , here n is array length.
Is it O(1) for finding an element in HashSet for Java?

HashSet<String> set=new HashSet<String>();
......
System.out.print(set.contains(Some_string);

Is contains(String) method performing at O(1)?


问:
Unable to download jersey-quickstart-webapp from maven
I am trying download a jersey-quickstart-webapp using maven. I am unable to figure out what is wrong with my command below.

```<code>mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes  -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.2
</code>```

The errors I get are below: what am I doing wrong here?

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] >>> maven-archetype-plugin:3.0.0:generate (default-cli) > generate-sources @ standalone-pom

[INFO] Generating project in Interactive mode
[WARNING] No archetype found in remote catalog. Defaulting to internal catalog
[WARNING] Archetype not found in any catalog. Falling back to central repository
(http://repo.maven.apache.org/maven2).
[WARNING] Use -DarchetypeRepository=<your repository> if archetype's repository is elsewhere.
Downloading: http://repo.maven.apache.org/maven2/org/glassfish/jersey/archetypes/jersey-quickstart-webapp/2.2/jersey-quickstart-webapp-2.2.pom
Downloading: https://repo.maven.apache.org/maven2/org/glassfish/jersey/archetypes/jersey-quickstart-webapp/2.2/jersey-quickstart-webapp-2.2.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.330 s
[INFO] Finished at: 2017-03-29T20:46:00+05:30
[INFO] Final Memory: 14M/139M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.0.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (org.glassfish.jersey.archetypes:jersey-quickstart-webapp:2.2) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
</code>```

答:
The version you have specified is wrong(NOT 2.2 its 2.25.1). Try to run this:</p>

```<code>mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes  -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.25.1
</code>```

Body:
I am trying download a jersey-quickstart-webapp using maven. I am unable to figure out what is wrong with my command below.

mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes  -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.2

The errors I get are below: what am I doing wrong here?

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] >>> maven-archetype-plugin:3.0.0:generate (default-cli) > generate-sources @ standalone-pom

[INFO] Generating project in Interactive mode
[WARNING] No archetype found in remote catalog. Defaulting to internal catalog
[WARNING] Archetype not found in any catalog. Falling back to central repository
(http://repo.maven.apache.org/maven2).
[WARNING] Use -DarchetypeRepository=<your repository> if archetype's repository is elsewhere.
Downloading: http://repo.maven.apache.org/maven2/org/glassfish/jersey/archetypes/jersey-quickstart-webapp/2.2/jersey-quickstart-webapp-2.2.pom
Downloading: https://repo.maven.apache.org/maven2/org/glassfish/jersey/archetypes/jersey-quickstart-webapp/2.2/jersey-quickstart-webapp-2.2.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.330 s
[INFO] Finished at: 2017-03-29T20:46:00+05:30
[INFO] Final Memory: 14M/139M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.0.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (org.glassfish.jersey.archetypes:jersey-quickstart-webapp:2.2) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.

Body:
The version you have specified is wrong(NOT 2.2 its 2.25.1). Try to run this:

mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes  -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.25.1