问:
When I display elements from list ,they are there,but when I want to use the list in method ,nothing is showing
I have a connection with ORACLE database and I have class (model). I put my database information in the list when I run a.Output()-I can see data.
But when I want to use my list in a method it's showing nothing!

It's my model Class: From the database, I wanna get an only first name, last name and section name

```<code>public class Customer implements Comparable<Object> {

public String ime;
public String fam;
public String oime;

Customer(){}

Customer(String n, String f, String o) {
    ime = n;
    fam=f;
    oime=o;
}

public String getIme() {
    return ime;
}

public void setIme(String ime) {
    this.ime = ime;
}
public String getFam() {
    return fam;
}

public void setFam(String fam) {
    this.fam = fam;
}

public String getOime() {
    return oime;
}

public void setOime(String o) {
    oime = o;
}
 public int compareTo(Object a) {
     if(getOime().equals(((Customer)a).getOime()))
         return -1;
     if(this.getOime().equals(((Customer)a).getOime()))
         return 1;
     return 0;
    }

    public boolean equals(Object o) {
    return (this.getOime()==((Customer)o).getOime());
    }
    public String toString() {
    return  "Ime="+ ime+" "+fam + ", Otdel = " + oime;
    }

    }
</code>```

And here I have my main class: Here I have a connection with my DB and pushing in the list all information

```<code>   public class ConnectionDatabase {

   protected  List<Customer> warehouses = new ArrayList<Customer>();

   public static Connection connectDB() {
    Connection connect = null;
    try {
        String driver = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driver);
         connect =

     DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
        "asd","pass");
    }
    catch(Exception e) {
        System.out.println(e);
    }
    return connect;
}

 ConnectionDatabase() {
    Connection connect1 = connectDB();
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
    String query = "SELECT firstname,lastname,sectionname FROM
            staff,section";
        ps = connect1.prepareStatement(query);
        rs = ps.executeQuery();
        while(rs.next()) {
        warehouses.add(new
   Customer(rs.getString("firstname"),
   rs.getString("lastname"),rs.getString("sectionname")));
        }
    rs.close();
    connect1.close();

    } catch(Exception e) {e.printStackTrace();}
    }

public void Output() {
    for(int i=0; i < warehouses.size(); i++){
        System.out.println(warehouses.get(i));
    }
}

public List<Customer> typeReference(String type) {
    Customer w1 = new Customer();
    List<Customer> w2 = new ArrayList<Customer>();
    for(int i=0; i < warehouses.size(); i++) {
        w1 =  warehouses.get(i);
        if(w1.getOime().equals(otdel))
        w2.add(w1);
    }
    return w2;
}

public static void main(String args[]) {
ConnectionDatabase a=new ConnectionDatabase();
a.typeReference("Pool");
}
    }
</code>```

答:
You need to override the Customer toString() method.

The default is the object memory location inherited from Object.

Body:
I have a connection with ORACLE database and I have class (model). I put my database information in the list when I run a.Output()-I can see data.
But when I want to use my list in a method it's showing nothing!

It's my model Class: From the database, I wanna get an only first name, last name and section name

public class Customer implements Comparable<Object> {

public String ime;
public String fam;
public String oime;

Customer(){}

Customer(String n, String f, String o) {
    ime = n;
    fam=f;
    oime=o;
}

public String getIme() {
    return ime;
}

public void setIme(String ime) {
    this.ime = ime;
}
public String getFam() {
    return fam;
}

public void setFam(String fam) {
    this.fam = fam;
}

public String getOime() {
    return oime;
}

public void setOime(String o) {
    oime = o;
}
 public int compareTo(Object a) {
     if(getOime().equals(((Customer)a).getOime()))
         return -1;
     if(this.getOime().equals(((Customer)a).getOime()))
         return 1;
     return 0;
    }

    public boolean equals(Object o) {
    return (this.getOime()==((Customer)o).getOime());
    }
    public String toString() {
    return  "Ime="+ ime+" "+fam + ", Otdel = " + oime;
    }

    }

And here I have my main class: Here I have a connection with my DB and pushing in the list all information

   public class ConnectionDatabase {

   protected  List<Customer> warehouses = new ArrayList<Customer>();

   public static Connection connectDB() {
    Connection connect = null;
    try {
        String driver = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driver);
         connect =

     DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
        "asd","pass");
    }
    catch(Exception e) {
        System.out.println(e);
    }
    return connect;
}

 ConnectionDatabase() {
    Connection connect1 = connectDB();
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
    String query = "SELECT firstname,lastname,sectionname FROM
            staff,section";
        ps = connect1.prepareStatement(query);
        rs = ps.executeQuery();
        while(rs.next()) {
        warehouses.add(new
   Customer(rs.getString("firstname"),
   rs.getString("lastname"),rs.getString("sectionname")));
        }
    rs.close();
    connect1.close();

    } catch(Exception e) {e.printStackTrace();}
    }

public void Output() {
    for(int i=0; i < warehouses.size(); i++){
        System.out.println(warehouses.get(i));
    }
}

public List<Customer> typeReference(String type) {
    Customer w1 = new Customer();
    List<Customer> w2 = new ArrayList<Customer>();
    for(int i=0; i < warehouses.size(); i++) {
        w1 =  warehouses.get(i);
        if(w1.getOime().equals(otdel))
        w2.add(w1);
    }
    return w2;
}

public static void main(String args[]) {
ConnectionDatabase a=new ConnectionDatabase();
a.typeReference("Pool");
}
    }


来源: stackexchange

问:
Compare two html files
Hi
I want to compare code of two HTML files. How do I achieve this?</p>

答: If you are on a Unix platform, you can compare the two files using a program such as diff.</p>

ContentLicense: CC BY-SA 3.0

Title: Compare two html files


问:
Can upload / download files at Karate Driver?
When using KarateDriver, I want to upload and download files on the browser.

Upload : Using <input type="file" />

Download : Browser download. The response header is Content-Disposition: attachment; filename=sample.txt

But I don't know how to do it.
Is that possible?

答: Sorry we haven't implemented it yet. If you have some sample Selenium code we can take a look at that. Maybe we should open a feature request.</p>

ContentLicense: CC BY-SA 4.0


问:
How to get parent Widget width
I have a card view Widget and inside that a Text Widget but it is showing overflowed by 1.00pixels

Is there any way to set Text fit to parent width

```<code>Container(
            child: Card(
              margin: EdgeInsets.only(left: 10, right: 10),
              child: Column(
                children: getDetailsItems(),
              ),
            ),
          ),
</code>```

Here getDetailsItems return a list of Widget it include Text Widget

```<code>List<Widget> getDetailsItems() {
    List<Widget> l = [];

    if (mItem.mServiceDetail != null) {
      for (int i = 0; i < mItem.mServiceDetail.length; i++) {
        Row r1 = Row(
          children: <Widget>[],
        );
        Align a1 = Align(
          child: Padding(
            padding: EdgeInsets.all(10),
            child: Container(
                child: SizedBox(
              width: 24,
              height: 24,
              child: Image.network(mItem.mServiceDetail[i].img),
            )),
          ),
          alignment: Alignment.centerLeft,
        );
        Align a2 = Align(
          child: Padding(
            padding: EdgeInsets.all(10),
            child: Container(

                child: Align(
              child:  Text(
                (mItem.mServiceDetail[i].title == null
                    ? ""
                    : mItem.mServiceDetail[i].title),
                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
              ),
            )),
          ),
          alignment: Alignment.topRight,
        );

        r1.children.add((a1));
        r1.children.add((a2));

        l.add(r1);
      }
    }

    return l;
  }
</code>```

It looks like your post is mostly code; please add some more details.

It looks like your post is mostly code; please add some more details.

答:
As a direct child of your Row you can wrap your Align widget with a Flexible widget. This will prevent its child from overflowing. Note that this can only be used for direct children of RenderFlex widget as Column or Row. So in your case:

```<code>Flexible a2 = Flexible(
  child: Align(
    child: Padding(
      padding: EdgeInsets.all(10),
      child: Container(
        child: Align(
          child: Text(
            mItem.mServiceDetail[i].title == null
                ? ""
                : mItem.mServiceDetail[i].title,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
          ),
        ),
      ),
    ),
    alignment: Alignment.topRight,
  ),
);
</code>```

I have added the overflow: TextOverflow.ellipsis property to make it visible.

As a general tip I would recommend you to add children of something like Row directly and skip using those local variables as most stuff in Flutter is added instantly as part of its declarative form. So your method should look like this:

```<code>List<Widget> getDetailsItems() {
  List<Widget> l = [];

  if (mItem.mServiceDetail != null) {
    for (int i = 0; i < mItem.mServiceDetail.length; i++) {
      l.add(
        Row(
          children: <Widget>[
            Align(
              child: Padding(
                padding: EdgeInsets.all(10),
                child: Container(
                  child: SizedBox(
                    width: 24,
                    height: 24,
                    child: Image.network(mItem.mServiceDetail[i].img),
                  ),
                ),
              ),
              alignment: Alignment.centerLeft,
            ),
            Flexible(
              child: Align(
                alignment: Alignment.topRight,
                child: Padding(
                  padding: EdgeInsets.all(10),
                  child: Container(
                    child: Align(
                      child: Text(
                        mItem.mServiceDetail[i].title == null
                            ? ""
                            : mItem.mServiceDetail[i].title,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontWeight: FontWeight.w500, fontSize: 16),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }
  }
  return l;
}
</code>```

Seeing you use this function to create those entries in a specific way is also a good indicator that it should be a Widget itself so you could even create a new StatefulWidget for that.

Title: How to get parent Widget width

Body:
I have a card view Widget and inside that a Text Widget but it is showing overflowed by 1.00pixels

Is there any way to set Text fit to parent width

Container(
            child: Card(
              margin: EdgeInsets.only(left: 10, right: 10),
              child: Column(
                children: getDetailsItems(),
              ),
            ),
          ),

Here getDetailsItems return a list of Widget it include Text Widget

List<Widget> getDetailsItems() {
    List<Widget> l = [];

    if (mItem.mServiceDetail != null) {
      for (int i = 0; i < mItem.mServiceDetail.length; i++) {
        Row r1 = Row(
          children: <Widget>[],
        );
        Align a1 = Align(
          child: Padding(
            padding: EdgeInsets.all(10),
            child: Container(
                child: SizedBox(
              width: 24,
              height: 24,
              child: Image.network(mItem.mServiceDetail[i].img),
            )),
          ),
          alignment: Alignment.centerLeft,
        );
        Align a2 = Align(
          child: Padding(
            padding: EdgeInsets.all(10),
            child: Container(

                child: Align(
              child:  Text(
                (mItem.mServiceDetail[i].title == null
                    ? ""
                    : mItem.mServiceDetail[i].title),
                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
              ),
            )),
          ),
          alignment: Alignment.topRight,
        );

        r1.children.add((a1));
        r1.children.add((a2));

        l.add(r1);
      }
    }

    return l;
  }

It looks like your post is mostly code; please add some more details.

It looks like your post is mostly code; please add some more details.

Body:
As a direct child of your Row you can wrap your Align widget with a Flexible widget. This will prevent its child from overflowing. Note that this can only be used for direct children of RenderFlex widget as Column or Row. So in your case:

Flexible a2 = Flexible(
  child: Align(
    child: Padding(
      padding: EdgeInsets.all(10),
      child: Container(
        child: Align(
          child: Text(
            mItem.mServiceDetail[i].title == null
                ? ""
                : mItem.mServiceDetail[i].title,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
          ),
        ),
      ),
    ),
    alignment: Alignment.topRight,
  ),
);

I have added the overflow: TextOverflow.ellipsis property to make it visible.

As a general tip I would recommend you to add children of something like Row directly and skip using those local variables as most stuff in Flutter is added instantly as part of its declarative form. So your method should look like this:

List<Widget> getDetailsItems() {
  List<Widget> l = [];

  if (mItem.mServiceDetail != null) {
    for (int i = 0; i < mItem.mServiceDetail.length; i++) {
      l.add(
        Row(
          children: <Widget>[
            Align(
              child: Padding(
                padding: EdgeInsets.all(10),
                child: Container(
                  child: SizedBox(
                    width: 24,
                    height: 24,
                    child: Image.network(mItem.mServiceDetail[i].img),
                  ),
                ),
              ),
              alignment: Alignment.centerLeft,
            ),
            Flexible(
              child: Align(
                alignment: Alignment.topRight,
                child: Padding(
                  padding: EdgeInsets.all(10),
                  child: Container(
                    child: Align(
                      child: Text(
                        mItem.mServiceDetail[i].title == null
                            ? ""
                            : mItem.mServiceDetail[i].title,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontWeight: FontWeight.w500, fontSize: 16),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }
  }
  return l;
}

Seeing you use this function to create those entries in a specific way is also a good indicator that it should be a Widget itself so you could even create a new StatefulWidget for that.


问:
How to display image using AWS S3 and Vapor 3 and Leaf
I have set up AWS S3 bucket and I'm able to upload files there using Vapor 3 and Postman. I can also get files using Vapor 3 and Postman but I have a hard time to get and actually display files(png -images) on my browser (I'm using leaf).

So how can I display image files on the view? I'm new with HTML, AWS S3 and Vapor.

I'm using:

Vapor 3

AWS S3

Leaf package

S3 package

VaporExt package

I followed this tutorial to set up everything (except the get request and the bucket policies): https://fivedottwelve.com/blog/using-amazon-s3-with-vapor/

Here are my Vapor code:

/// GET reguest
func preparePresignedImageUrl(request: Request) throws -> String {

    let baseUrl = awsConfig.url
    let imagePath = awsConfig.imagePath
    let fileName = "x.png"

    guard var url = URL(string: baseUrl) else {
        throw Abort(.internalServerError)
    }
    url.appendPathComponent(imagePath)
    url.appendPathComponent(fileName)

    print("url is \(url)")
    let headers = ["x-amz-acl" : "public-read"]

    let s3 = try request.makeS3Signer()
    let result = try s3.presignedURL(for: .GET, url: url, expiration: Expiration.hour, headers: headers)
    /// Retrieve file data from S3

    guard let presignedUrl = result?.absoluteString else {
        throw Abort(.internalServerError)
    }

    return presignedUrl

}
```

<p>The route:</p>

<pre class="lang-swift prettyprint-override"><code>// GET request
 group.get("aws", "image", use: preparePresignedImageUrl)
</code>```

And in the Postman when I make a GET request to that presignedURL it gives me a status code 200OK.

My showImage.leaf file:

#set("content") {

#(title)

// Here some html to get the image path and display the image?

}

#embed("base")
```

答:
So I am going to assume that you have a perfectly good URL to the image.

Let's start by creating a route at GET /image:

routes.get("image", use: image)

func image(_ request: Request) -> EventLoopFuture<View> {

}
```

<p>To properly render the Leaf view, we will need a context that contains the data for the Leaf variables. It will look something like this:</p>

<pre class="lang-swift prettyprint-override"><code>struct ImageContext: Encodable {
    let title: String
    let imageURL: String
}
</code>```

We also need to edit your leaf file so it will use the properties in the context:

```<code>#set("content") {
<h1>#(title)</h1>
<img src="#(imageURL)">
}

#embed("base")
</code>```

Now we can render the leaf file with out new context and return the resulting view from the route handler. Here is what the implementation of the image route handler will look like:

func image(_ request: Request) -> EventLoopFuture<View> {
    let context = ImageContext(title: "Image", imageURL: preparePresignedImageUrl(request: request)
    return try request.view().make("showImage", context)
}
```

Now you should be able to access localhost:8080/image from your browser and the image will be there!

Body:
I have set up AWS S3 bucket and I'm able to upload files there using Vapor 3 and Postman. I can also get files using Vapor 3 and Postman but I have a hard time to get and actually display files(png -images) on my browser (I'm using leaf).

So how can I display image files on the view? I'm new with HTML, AWS S3 and Vapor.

I'm using:

Vapor 3

AWS S3

Leaf package

S3 package

VaporExt package

I followed this tutorial to set up everything (except the get request and the bucket policies): https://fivedottwelve.com/blog/using-amazon-s3-with-vapor/

Here are my Vapor code:

/// GET reguest
func preparePresignedImageUrl(request: Request) throws -> String {

    let baseUrl = awsConfig.url
    let imagePath = awsConfig.imagePath
    let fileName = "x.png"

    guard var url = URL(string: baseUrl) else {
        throw Abort(.internalServerError)
    }
    url.appendPathComponent(imagePath)
    url.appendPathComponent(fileName)

    print("url is \(url)")
    let headers = ["x-amz-acl" : "public-read"]

    let s3 = try request.makeS3Signer()
    let result = try s3.presignedURL(for: .GET, url: url, expiration: Expiration.hour, headers: headers)
    /// Retrieve file data from S3

    guard let presignedUrl = result?.absoluteString else {
        throw Abort(.internalServerError)
    }

    return presignedUrl

}

The route:

// GET request
 group.get("aws", "image", use: preparePresignedImageUrl)

And in the Postman when I make a GET request to that presignedURL it gives me a status code 200OK.

My showImage.leaf file:

#set("content") {

#(title)

// Here some html to get the image path and display the image?

}

#embed("base")

Body:
So I am going to assume that you have a perfectly good URL to the image.

Let's start by creating a route at GET /image:

routes.get("image", use: image)

func image(_ request: Request) -> EventLoopFuture<View> {

}

To properly render the Leaf view, we will need a context that contains the data for the Leaf variables. It will look something like this:

struct ImageContext: Encodable {
    let title: String
    let imageURL: String
}

We also need to edit your leaf file so it will use the properties in the context:

#set("content") {
<h1>#(title)</h1>
<img src="#(imageURL)">
}

#embed("base")

Now we can render the leaf file with out new context and return the resulting view from the route handler. Here is what the implementation of the image route handler will look like:

func image(_ request: Request) -> EventLoopFuture<View> {
    let context = ImageContext(title: "Image", imageURL: preparePresignedImageUrl(request: request)
    return try request.view().make("showImage", context)
}

Now you should be able to access localhost:8080/image from your browser and the image will be there!


问:
Welcome message with Ibot interface
I am using the Ibot interface, but the welcome message is sent twice.
I use the OnTurnAsync method, and it seems that doesn't do anything when I call the MembersAdded property.

To send the Welcome message i have this piece of code:

```<code>if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate && turnContext.Activity.MembersAdded.Count == 1)
        {

            userProfile.Welcome = true;

            var reply = turnContext.Activity.CreateReply();
            reply.Attachments = new List<Attachment>();
            reply.Attachments.Add(getCard("Welcome"));

            await turnContext.SendActivityAsync(reply);
        }
</code>```

答:
There's a few things that could be going on with this.

MembersAdded is called for adding both the bot and the user. I'm guessing this is why it's being sent twice.

If you're using the newer ActivityHandler, you can use:

protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
    foreach (var member in membersAdded)
    {
        if (member.Id != turnContext.Activity.Recipient.Id)
        {
            userProfile.Welcome = true;

            var reply = turnContext.Activity.CreateReply();
            reply.Attachments = new List<Attachment>();
            reply.Attachments.Add(getCard("Welcome"));

            await turnContext.SendActivityAsync(reply);
        }
    }
}
```

<p>Or, if you're using the old activity handler:</p>

<pre class="lang-cs prettyprint-override"><code>public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
    if (activity.Type == ActivityTypes.ConversationUpdate)
    {
        if (activity.MembersAdded != null)
        {
            foreach (var member in activity.MembersAdded)
            {
                if (member.Name != "Bot" && member.Name != null)
                {
                    userProfile.Welcome = true;

                    var reply = turnContext.Activity.CreateReply();
                    reply.Attachments = new List<Attachment>();
                    reply.Attachments.Add(getCard("Welcome"));

                    await turnContext.SendActivityAsync(reply);
                }
            }
        }
    }

    [...]
</code>```

WebChat doesn't automatically send a ConversationUpdate like Emulator does. See this WebChat sample for how to send a welcome event.

You could always ensure it doesn't double-send by checking to see if userProfile.Welcome != true. This sample may help.

Title: Welcome message with Ibot interface

Body:
I am using the Ibot interface, but the welcome message is sent twice.
I use the OnTurnAsync method, and it seems that doesn't do anything when I call the MembersAdded property.

To send the Welcome message i have this piece of code:

if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate && turnContext.Activity.MembersAdded.Count == 1)
        {

            userProfile.Welcome = true;

            var reply = turnContext.Activity.CreateReply();
            reply.Attachments = new List<Attachment>();
            reply.Attachments.Add(getCard("Welcome"));

            await turnContext.SendActivityAsync(reply);
        }

Body:
There's a few things that could be going on with this.

MembersAdded is called for adding both the bot and the user. I'm guessing this is why it's being sent twice.

If you're using the newer ActivityHandler, you can use:

protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
    foreach (var member in membersAdded)
    {
        if (member.Id != turnContext.Activity.Recipient.Id)
        {
            userProfile.Welcome = true;

            var reply = turnContext.Activity.CreateReply();
            reply.Attachments = new List<Attachment>();
            reply.Attachments.Add(getCard("Welcome"));

            await turnContext.SendActivityAsync(reply);
        }
    }
}

Or, if you're using the old activity handler:

public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
    if (activity.Type == ActivityTypes.ConversationUpdate)
    {
        if (activity.MembersAdded != null)
        {
            foreach (var member in activity.MembersAdded)
            {
                if (member.Name != "Bot" && member.Name != null)
                {
                    userProfile.Welcome = true;

                    var reply = turnContext.Activity.CreateReply();
                    reply.Attachments = new List<Attachment>();
                    reply.Attachments.Add(getCard("Welcome"));

                    await turnContext.SendActivityAsync(reply);
                }
            }
        }
    }

    [...]

WebChat doesn't automatically send a ConversationUpdate like Emulator does. See this WebChat sample for how to send a welcome event.

You could always ensure it doesn't double-send by checking to see if userProfile.Welcome != true. This sample may help.


问:
How do the core modules in node.js work? (https://github.com/nodejs/node/blob/master/lib)
Does the node interpreter look for core modules (let's say "fs") within the node binary? If yes, are these modules packaged as js files. Are the core modules that are referenced within our code converted to c/c++ code first and then executed? For example, I see a method in the _tls_common.js (https://github.com/nodejs/node/blob/master/lib/_tls_common.js) file called "loadPKCS12" and the only place that I see this method being referenced/defined is within the "node_crypto.cc" file (https://github.com/nodejs/node/blob/master/src/node_crypto.cc). So how does node link a method in javascript with the one defined in the c/c++ file?

here is the extract from the _tls_common.js file that makes use of the "loadPKCS12" method:

```<code> if (passphrase) {
      c.context.loadPKCS12(buf, toBuf(passphrase));
    } else {
      c.context.loadPKCS12(buf);
    }
  }
} else {
  const buf = toBuf(options.pfx);
  const passphrase = options.passphrase;
  if (passphrase) {
    c.context.loadPKCS12(buf, toBuf(passphrase));
  } else {
    c.context.loadPKCS12(buf);
</code>```

答:
There are two different (but seemingly related) questions asked here. The first one is: "How the core modules work?". Second one being "How does NodeJS let c++ code get referenced and executed in JavaScript?". Let's take them one by one.

How the core modules work?

The core modules are packaged with NodeJS binary. And, while they are packaged with the binary, they are not converted to c++ code before packaging. The internal modules are loaded into memory during bootstrap of the node process. When a program executes, lets say require('fs'), the require function simply returns the already loaded module from cache. The actual loading of the internal module obviously happens in c++ code.

How does NodeJS let c++ code get referenced in JS?

This ability comes partly from V8 engine which exposes the ability to create and manage JS constructs in C++, and partly from NodeJS / LibUV which create a wrapper on top of V8 to provide the execution environment. The documentation about such node modules can be accessed here. As the documentation states, these c++ modules can be used in JS file by requiring them, like any other ordinary JS module.

Your example for use of c++ function in JS (loadPKCS12), however, is more special case of internal c++ functionality of NodeJS. loadPKCS12 is called on a object of SecureContext imported from crypto c++ module. If you follow the link to SecureContext import in _tls_common.js above, you will see that the crypto is not loaded using require(), instead a special (global) method internalBinding is used to obtain the reference. At the last line in node_crypto.cc file, initializer for internal module crypto is registered. Following the chain of initialization, node::crypto::Initialize calls node::crypto::SecureContext::Initialize which creates a function template, assigns the appropriate prototype methods and exports it on target. Eventually these exported functionalities from C++ world are imported and used in JS-World using internalBinding.

Body:
Does the node interpreter look for core modules (let's say "fs") within the node binary? If yes, are these modules packaged as js files. Are the core modules that are referenced within our code converted to c/c++ code first and then executed? For example, I see a method in the _tls_common.js (https://github.com/nodejs/node/blob/master/lib/_tls_common.js) file called "loadPKCS12" and the only place that I see this method being referenced/defined is within the "node_crypto.cc" file (https://github.com/nodejs/node/blob/master/src/node_crypto.cc). So how does node link a method in javascript with the one defined in the c/c++ file?

here is the extract from the _tls_common.js file that makes use of the "loadPKCS12" method:

 if (passphrase) {
      c.context.loadPKCS12(buf, toBuf(passphrase));
    } else {
      c.context.loadPKCS12(buf);
    }
  }
} else {
  const buf = toBuf(options.pfx);
  const passphrase = options.passphrase;
  if (passphrase) {
    c.context.loadPKCS12(buf, toBuf(passphrase));
  } else {
    c.context.loadPKCS12(buf);


问:
How to automate createsuperuser on django?
I want to auto run manage.py createsuperuser on django but it seams that there is no way of setting a default password.

How can I get this? It has to be independent on the django database.

答:
Go to command prompt and type:

```<code>C:\WINDOWS\system32>pip install django-createsuperuser
Collecting django-createsuperuser
  Downloading https://files.pythonhosted.org/packages/93/8c/344c6367afa62b709adebee039d09229675f1ee34d424180fcee9ed857a5/django-createsuperuser-2019.4.13.tar.gz
Requirement already satisfied: Django>1.0 in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (2.2.1)
Requirement already satisfied: setuptools in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (41.0.1)
Requirement already satisfied: sqlparse in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (0.3.0)
Requirement already satisfied: pytz in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (2018.7)
Building wheels for collected packages: django-createsuperuser
  Running setup.py bdist_wheel for django-createsuperuser ... done
  Stored in directory: C:\Users\Arif Khan\AppData\Local\pip\Cache\wheels\0c\96\2a\e73e95bd420e844d3da1c9d3e496c92642a4f2181535440db2
Successfully built django-createsuperuser
Installing collected packages: django-createsuperuser
</code>```

if not executed the migration then go to django application folder and execute following

python manage.py migrate

python manage.py createsuperuser

then bingo.

Body:
Go to command prompt and type:

C:\WINDOWS\system32>pip install django-createsuperuser
Collecting django-createsuperuser
  Downloading https://files.pythonhosted.org/packages/93/8c/344c6367afa62b709adebee039d09229675f1ee34d424180fcee9ed857a5/django-createsuperuser-2019.4.13.tar.gz
Requirement already satisfied: Django>1.0 in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (2.2.1)
Requirement already satisfied: setuptools in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (41.0.1)
Requirement already satisfied: sqlparse in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (0.3.0)
Requirement already satisfied: pytz in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (2018.7)
Building wheels for collected packages: django-createsuperuser
  Running setup.py bdist_wheel for django-createsuperuser ... done
  Stored in directory: C:\Users\Arif Khan\AppData\Local\pip\Cache\wheels\0c\96\2a\e73e95bd420e844d3da1c9d3e496c92642a4f2181535440db2
Successfully built django-createsuperuser
Installing collected packages: django-createsuperuser

if not executed the migration then go to django application folder and execute following

python manage.py migrate

python manage.py createsuperuser

then bingo.


问:
How to convert an array?
I need to reformat an array from one type to another using library "Lodash".

I initially have such an array:

```<code>[{
    "language": {
      "displayName": {
        "en": "English"
      },
      "id": 1
    },
    "level": {
      "id": 1,
      "displayName": {
        "en": "Intermediate"
      }
    }
  }, {
    "language": {
      "displayName": {
        "en": "Russian"
      },
      "id": 2
    },
    "level": {
      "id": 1
      "displayName": {
        "en": "Fluent"
      }
    }
  }]
</code>```

How to convert an array in this format:

```<code>[{
    "language": 1, // it is language.id
    "level": 1 // it is level.id
  }, {
    "language": 2, // it is language.id
    "level": 2 // it is level.id
}]
</code>```

答:
You can use Array.map() as already shown. However, a Lodash solution as required will be using _.map() in combination with _.mapValues()

const input = [{"language":{"displayName":{"en":"English"},"id":1},"level":{"id":1,"displayName":{"en":"Intermediate"}}},{"language":{"displayName":{"en":"Russian"},"id":2},"level":{"id":2,"displayName":{"en":"Fluent"}}}];

let res = _.map(input, o => _.mapValues(o, "id"));

console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

```

Title: How to convert an array?

Body:
I need to reformat an array from one type to another using library "Lodash".

I initially have such an array:

[{
    "language": {
      "displayName": {
        "en": "English"
      },
      "id": 1
    },
    "level": {
      "id": 1,
      "displayName": {
        "en": "Intermediate"
      }
    }
  }, {
    "language": {
      "displayName": {
        "en": "Russian"
      },
      "id": 2
    },
    "level": {
      "id": 1
      "displayName": {
        "en": "Fluent"
      }
    }
  }]

How to convert an array in this format:

[{
    "language": 1, // it is language.id
    "level": 1 // it is level.id
  }, {
    "language": 2, // it is language.id
    "level": 2 // it is level.id
}]

Body:
You can use Array.map() as already shown. However, a Lodash solution as required will be using _.map() in combination with _.mapValues()

const input = [{"language":{"displayName":{"en":"English"},"id":1},"level":{"id":1,"displayName":{"en":"Intermediate"}}},{"language":{"displayName":{"en":"Russian"},"id":2},"level":{"id":2,"displayName":{"en":"Fluent"}}}];

let res = _.map(input, o => _.mapValues(o, "id"));

console.log(res);

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


问:
Laravel Error - Call to undefined method Illuminate\Database\Query\Builder::gets()
I am running a query in Laravel but got this error:

Call to undefined method Illuminate\Database\Query\Builder::gets()

I have written the query

Controller

```<code>            $currentMonth = date('m');
            $currentmonthbilling = DB::table("billings")
                   ->select(DB::raw("SUM(amount) as total"))
                   ->whereRaw('MONTH(created_at) = ?',$currentMonth)
                   ->gets();
</code>```

View

```<code><span class="info-box-number">{{ $currentmonthbilling[0]->total }}</span>
</code>```

I expect it to display total amount for the current month

答:
As was mentioned, you should use get() instead of gets().

But you don't need get() at all, and can write it more clearly.

```<code>$total = DB::table('billings')
    ->whereMonth('created_at', date('m'))
    ->sum('amount');
</code>```

Body:
I am running a query in Laravel but got this error:

Call to undefined method Illuminate\Database\Query\Builder::gets()

I have written the query

Controller

            $currentMonth = date('m');
            $currentmonthbilling = DB::table("billings")
                   ->select(DB::raw("SUM(amount) as total"))
                   ->whereRaw('MONTH(created_at) = ?',$currentMonth)
                   ->gets();

View

{{ $currentmonthbilling[0]->total }}

I expect it to display total amount for the current month

Body:
As was mentioned, you should use get() instead of gets().

But you don't need get() at all, and can write it more clearly.

$total = DB::table('billings')
    ->whereMonth('created_at', date('m'))
    ->sum('amount');


问:
Qt set background color for selected QTableWidgetItems
I've been trying to choose the background colors of the selected cells in my QTableWidget. I use a custom QTableWidgetItem that has the following data method:

QVariant MyItem::data(int role) const
{
    if (role == Qt::BackgroundRole)
    {
        if (isSelected())
            return QBrush(Qt::green);
        else
            return QBrush(Qt::blue);
    }
}
```

However, it does not work as expected:

I don't really know what to do at this point... Please suggest!

Note: For simple cases, I could edit my QSS to add the items' background color, but I want to add a condition to the flow in data and using QSS won't be as easy.

答:
You need to reimplement item delegate too.</p>

```<code>class ColoredItemDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit ColoredItemDelegate(QObject *parent = 0);

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    void setEditorData(QWidget *editor, const QModelIndex &index) const;
    void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;

};

void ColoredItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                                const QModelIndex &index) const
{
    if (option.state.testFlag(QStyle::State_Selected))
    {
        QStyleOptionViewItem newOption(option);
        newOption.palette.setBrush(QPalette::Normal, QPalette::Highlight,
                                   index.data(Qt::BackgroundRole).value<QBrush>());
        QStyledItemDelegate::paint(painter, newOption, index);
        return;
    }

    QStyledItemDelegate::paint(painter, option, index);
}
</code>```

Body:
I've been trying to choose the background colors of the selected cells in my QTableWidget. I use a custom QTableWidgetItem that has the following data method:

QVariant MyItem::data(int role) const
{
    if (role == Qt::BackgroundRole)
    {
        if (isSelected())
            return QBrush(Qt::green);
        else
            return QBrush(Qt::blue);
    }
}

However, it does not work as expected:

I don't really know what to do at this point... Please suggest!

Note: For simple cases, I could edit my QSS to add the items' background color, but I want to add a condition to the flow in data and using QSS won't be as easy.

Body:
You need to reimplement item delegate too.

class ColoredItemDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit ColoredItemDelegate(QObject *parent = 0);

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    void setEditorData(QWidget *editor, const QModelIndex &index) const;
    void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;

};

void ColoredItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                                const QModelIndex &index) const
{
    if (option.state.testFlag(QStyle::State_Selected))
    {
        QStyleOptionViewItem newOption(option);
        newOption.palette.setBrush(QPalette::Normal, QPalette::Highlight,
                                   index.data(Qt::BackgroundRole).value<QBrush>());
        QStyledItemDelegate::paint(painter, newOption, index);
        return;
    }

    QStyledItemDelegate::paint(painter, option, index);
}


问:
Jslint "Line breaking error"
JSLint validation of this snippet

```<code>1: function foo() {}
2:
3: foo(1
4: );
5:
6: foo(
7: );
</code>```

gives this error:

```
Error:

Problem at line 3 character 5: Line breaking error ')'.

foo(1
```

Is this a JSLint bug?

答:
It's not a bug. JSLint does more than syntax checking: It enforces certain coding conventions. If you revalidate with the "Tolerate sloppy line breaking" option turned on, you won't get an error.

From the JSLint Documentation:

Line Breaking

As a further defense against the semicolon insertion mechanism, JSLint  expects long statements to be broken only after one of these punctuation characters or operators:

, . ; : { } ( [ = < > ? ! + - * / % ~ ^ | &
  == != <= >= += -= *= /= %= ^= |= &= << >> || &&
  === !== <<= >>= >>> >>>=

JSLint does not expect to see a long statement broken after an identifier, a string, a number, closer, or a suffix operator:

) ] ++ --

JSLint allows you to turn on the Tolerate sloppy line breaking (laxbreak) option.

Semicolon insertion can mask copy/paste errors. If you always break lines after operators, then JSLint can do better at finding them.

ContentLicense: CC BY-SA 2.5

Title: Jslint "Line breaking error"

Body:
JSLint validation of this snippet

1: function foo() {}
2:
3: foo(1
4: );
5:
6: foo(
7: );

gives this error:

Error:

Problem at line 3 character 5: Line breaking error ')'.

foo(1

Is this a JSLint bug?

LastEditorDisplayName: Rob Kennedy

OwnerDisplayName: Ferdinand

LastEditorDisplayName: Ferdinand


问:
multiple parameters url pattern django 2.0
I want to pass two parameters in my url pattern but i am getting error no-reverse match i.e 'projects'.While it works fine with only one parameter.

here is main urls file-

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^materials/(?P<name>(\s+)/',include('materials.urls')),
    path(r'^projects/',include('projects.urls')),
]
</code>```

projects.urls-

```<code>urlpatterns = [
path('',views.view_projects,name='view_projects'),
path('(?<projectid>\d+)/',views.project_steps,name='project_steps'),
path('(P<projectid>\d+)/(P<stepid>\d+)/',views.project_steps,
name='project_steps'),
]
</code>```

views.py-

```<code> def view_projects(request):
   projects = project.objects.all
   return render(request,'projects/project_view.html',
   {'projects':projects})

def project_steps(request,projectid,stepno=1):
  projects = project.objects.all
  stepss = steps.objects.all
  return render(request,'projects/project_steps.html',
  {'projectid':projectid,'steps':stepss,'projects':projects,
  'stepno':stepno})
</code>```

template-

```<code> "{% url 'projects' projectid=project.id stepno=step.step_no %}"
</code>```

答:
No regex matching or additional model fields required to make it work.

urls.py

```<code>path('custom_page/<str:id1>/<str:id2>/', views.custom_page, name='custom_page'),
</code>```

views.py

```<code>def custom_page(request, id1, id2):
    #use in view func or pass to template via context
    context = {}
    context['id1'] = id1
    context['id2'] = id2
    return render(request, 'custom_page.html', context=context)
</code>```

custom_page.html

```<code><div>{{id1}} {{id2}}</div>
</code>```

Body:
I want to pass two parameters in my url pattern but i am getting error no-reverse match i.e 'projects'.While it works fine with only one parameter.

here is main urls file-

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^materials/(?P<name>(\s+)/',include('materials.urls')),
    path(r'^projects/',include('projects.urls')),
]

projects.urls-

urlpatterns = [
path('',views.view_projects,name='view_projects'),
path('(?<projectid>\d+)/',views.project_steps,name='project_steps'),
path('(P<projectid>\d+)/(P<stepid>\d+)/',views.project_steps,
name='project_steps'),
]

views.py-

 def view_projects(request):
   projects = project.objects.all
   return render(request,'projects/project_view.html',
   {'projects':projects})

def project_steps(request,projectid,stepno=1):
  projects = project.objects.all
  stepss = steps.objects.all
  return render(request,'projects/project_steps.html',
  {'projectid':projectid,'steps':stepss,'projects':projects,
  'stepno':stepno})

template-

 "{% url 'projects' projectid=project.id stepno=step.step_no %}"

Body:
No regex matching or additional model fields required to make it work.

urls.py

path('custom_page/<str:id1>/<str:id2>/', views.custom_page, name='custom_page'),

views.py

def custom_page(request, id1, id2):
    #use in view func or pass to template via context
    context = {}
    context['id1'] = id1
    context['id2'] = id2
    return render(request, 'custom_page.html', context=context)

custom_page.html

<div>{{id1}} {{id2}}</div>


问:
Oracle UTL_FILE read CSV file lines
i'm using UTL_FILE package to read a csv file , then insert values in table, but my issue is how to read values separated by Commas.. , this is my code :

```<code>     declare
         file1 UTL_FILE.FILE_TYPE;
         str varchar2(200 CHAR);
        begin
         file1 := UTL_FILE.FOPEN('DRCT1','test_file.csv','R');

         loop
          UTL_FILE.GET_LINE(file1,str);
-- here i want to read each value before the Commas then insert them in my table
-- insert statement..
          dbms_output.put_line(str);
         end loop;

        exception
        when no_data_found then
        UTL_FILE.FCLOSE(file1);

        end;
        /
</code>```

this is my csv file :

```<code>100,Steven,King
101,Neena,Kochha
102,Lex,De Haan
103,Alexander
104,Bruce,Ernst
</code>```

please do you have any suggestion to my issue ?

Regards .

答:
Here's an example which shows how to do that. My code slightly differs from yours because of different directory and file names.

Sample table, which will contain data stored in the file:

```<code>SQL> create table test2 (id number, fname varchar2(20), lname varchar2(20));

Table created.
</code>```

Code; interesting part is line 14 and the way to split the whole row into separate values:

```<code>SQL> declare
  2    l_file         utl_file.file_type;
  3    l_text         varchar2(32767);
  4    l_cnt          number;
  5  begin
  6    -- Open file.
  7    l_file := utl_file.fopen('EXT_DIR', 'test2.txt', 'R', 32767);
  8
  9    loop
 10      utl_file.get_line(l_file, l_text, 32767);
 11
 12      -- L_TEXT contains the whole row; split it (by commas) into 3 values
 13      -- and insert them into the TEST2 table
 14      insert into test2 (id, fname, lname)
 15        values (regexp_substr(l_text, '[^,]+', 1, 1),
 16                regexp_substr(l_text, '[^,]+', 1, 2),
 17                regexp_substr(l_text, '[^,]+', 1, 3)
 18               );
 19    end loop;
 20
 21    utl_file.fclose(l_file);
 22  exception
 23    when no_data_found then
 24      null;
 25  end;
 26  /

PL/SQL procedure successfully completed.
</code>```

The result:

```<code>SQL> select * from test2;

        ID FNAME                LNAME
---------- -------------------- --------------------
       100 Steven               King
       101 Neena                Kochha
       102 Lex                  De Haan
       103 Alexander
       104 Bruce                Ernst

SQL>
</code>```

Title: Oracle UTL_FILE read CSV file lines

Body:
i'm using UTL_FILE package to read a csv file , then insert values in table, but my issue is how to read values separated by Commas.. , this is my code :

     declare
         file1 UTL_FILE.FILE_TYPE;
         str varchar2(200 CHAR);
        begin
         file1 := UTL_FILE.FOPEN('DRCT1','test_file.csv','R');

         loop
          UTL_FILE.GET_LINE(file1,str);
-- here i want to read each value before the Commas then insert them in my table
-- insert statement..
          dbms_output.put_line(str);
         end loop;

        exception
        when no_data_found then
        UTL_FILE.FCLOSE(file1);

        end;
        /

this is my csv file :

100,Steven,King
101,Neena,Kochha
102,Lex,De Haan
103,Alexander
104,Bruce,Ernst

please do you have any suggestion to my issue ?

Regards .

Body:
Here's an example which shows how to do that. My code slightly differs from yours because of different directory and file names.

Sample table, which will contain data stored in the file:

SQL> create table test2 (id number, fname varchar2(20), lname varchar2(20));

Table created.

Code; interesting part is line 14 and the way to split the whole row into separate values:

SQL> declare
  2    l_file         utl_file.file_type;
  3    l_text         varchar2(32767);
  4    l_cnt          number;
  5  begin
  6    -- Open file.
  7    l_file := utl_file.fopen('EXT_DIR', 'test2.txt', 'R', 32767);
  8
  9    loop
 10      utl_file.get_line(l_file, l_text, 32767);
 11
 12      -- L_TEXT contains the whole row; split it (by commas) into 3 values
 13      -- and insert them into the TEST2 table
 14      insert into test2 (id, fname, lname)
 15        values (regexp_substr(l_text, '[^,]+', 1, 1),
 16                regexp_substr(l_text, '[^,]+', 1, 2),
 17                regexp_substr(l_text, '[^,]+', 1, 3)
 18               );
 19    end loop;
 20
 21    utl_file.fclose(l_file);
 22  exception
 23    when no_data_found then
 24      null;
 25  end;
 26  /

PL/SQL procedure successfully completed.

The result:

SQL> select * from test2;

        ID FNAME                LNAME
---------- -------------------- --------------------
       100 Steven               King
       101 Neena                Kochha
       102 Lex                  De Haan
       103 Alexander
       104 Bruce                Ernst

SQL>


问:
Java Synth: Problem with JTabbedPane and SynthGraphicsUtils
in my Java application, I have a JTabbedPane and a synth look&feel. The l&f is defined by a xml file. This works very fine for me.

Now the challenge: I want the text in the tabs of the JTabbedPane to be written vertically, not horizontally. For this, I subclassed the SynthGraphicsUtils and overwrote the method paintText(SynthContext ss, Graphics g, String text, int x, int y, int mnemonicIndex). This works also.

Now the problem: the text in the different tabs is shown vertically, but the size of every tab seems to be misscalculated. The tabs are not separated correctly. Unfortunatly I'm not allowed to post images... The tabs overlay each other.

I don't know how to fix this problem :-( Here's my code:

SwingTest.java

```<code>public SwingTest(JFrame owner) {

    super(null);

    setOpaque(true);
    setSize(WIDTH, HEIGHT);
    owner.setSize(WIDTH, HEIGHT);

    JTabbedPane pane = new JTabbedPane(JTabbedPane.LEFT);
    pane.setName("MyPane");
    pane.setSize(WIDTH, HEIGHT);

    // Add a tab
    JPanel p1 = new JPanel();
    p1.setSize(300, 300);

    JPanel p2 = new JPanel();
    p2.setSize(500, 500);

    JPanel p3 = new JPanel();
    p3.setSize(300, 300);

    p3.add(new JLabel("HALLO"));

    JPanel p4 = new JPanel();
    p4.setSize(300, 300);

    JButton roundedButton = new JButton("Halloi Button");
    roundedButton.setName("roundedButton");

    p2.add(roundedButton);

    pane.addTab(EFFORT_CARD, p1);
    pane.addTab(EMOTION_CARD, p2);
    pane.addTab(COMFORT_CARD, p3);
    pane.addTab(DRIVING_CARD, p4);

    add(pane);

    pane.updateUI();
</code>```

laf.xml

```<code><!--
TABNAVIGATION
 -->
<style id="tabNavigationStyle">
    <!-- Angabe ist wichtig, da die Hintergrundfarben sonst nicht angezeigt
    werden. -->
    <!-- <object id="verticalTextWriterClass" class="VerticalTextWriter" />
    <painter method="text" idref="verticalTextWriterClass"/> -->
    <opaque value="TRUE" />
    <state>
        <font name="Verdana" size="12" />
        <color value="WHITE" type="BACKGROUND" />
        <color value="BLACK" type="FOREGROUND" />
        <color value="BLUE" type="TEXT_FOREGROUND" />
        <object id="myGraphicsUtils" class="MySynthGraphicsUtils" />
        <graphicsUtils idref="myGraphicsUtils" />
    </state>
    <!-- Fuer den Zustand "SELECTED" einen anderen Style definieren. -->
    <state value="SELECTED">
        <!-- Auf weiter oben definierte Farbe beziehen. -->
        <color value="WHITE" type="BACKGROUND" />
        <color idref="magentaForegroundColor" type="TEXT_FOREGROUND" />
    </state>
    <state value="FOCUSED">
        <!-- Auf weiter oben definierte Farbe beziehen. -->
        <color value="WHITE" type="BACKGROUND" />
        <color idref="magentaForegroundColor" type="TEXT_FOREGROUND" />
    </state>
    <state value="PRESSED">
        <!-- Auf weiter oben definierte Farbe beziehen. -->
        <color value="WHITE" type="BACKGROUND" />
        <color idref="magentaForegroundColor" type="TEXT_FOREGROUND" />
    </state>
</style>
<!-- Den Style fuer die Tabnavigation an die Tabnavigation mit dem Namen (type="name")
"MyPane" binden. Der Name wird in Java ueber component.setName() festgelegt. -->
<bind style="tabNavigationStyle" type="region" key="TabbedPaneTab" />
</code>```

MySynthGraphicsUtils.java

```<code>public class MySynthGraphicsUtils extends SynthGraphicsUtils {
public void paintText(SynthContext ss, Graphics g, String text, int x, int y, int mnemonicIndex) {

    Graphics2D g2 = (Graphics2D) g;

    System.out.println(ss.getComponent().getClass().getName());

    Object oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);

    g2.setFont(ss.getStyle().getFont(ss));
    AffineTransform tx = new AffineTransform();
    tx.rotate(90 * Math.PI / 180, x, y);
    g2.setTransform(tx);

    g2.drawString(text, x, y);

    // get metrics from the graphics
    FontMetrics metrics = g2.getFontMetrics(ss.getStyle().getFont(ss));
    // get the height of a line of text in this font and render context
    int hgt = metrics.getHeight();
    // get the advance of my text in this font and render context
    int adv = metrics.stringWidth(text);
    // calculate the size of a box to hold the text with some padding.
    Dimension size = new Dimension(adv + 2, hgt + 2);

    //g2.setClip(0, 0, size.width, size.height);

    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue);
}
</code>```

}

Thank you very much!!

答:
As a workaround, I use an image border with an sourceInset on the Left side to seperate Tabs. I make the image the same colour as the background of the app:</p>

```<code>        <state>
                <opaque value="true"/>
                <color value="black" type="BACKGROUND" />
                <color value="white" type="TEXT_FOREGROUND" />
                <imagePainter method="tabbedPaneTabBorder" path="relative/path/to/white_border.png"
             sourceInsets="0 1 0 0" paintCenter="false"/>
                <insets top="3" bottom="3" right="3" left="3"/>
        </state>
</code>```

Body:
in my Java application, I have a JTabbedPane and a synth look&feel. The l&f is defined by a xml file. This works very fine for me.

Now the challenge: I want the text in the tabs of the JTabbedPane to be written vertically, not horizontally. For this, I subclassed the SynthGraphicsUtils and overwrote the method paintText(SynthContext ss, Graphics g, String text, int x, int y, int mnemonicIndex). This works also.

Now the problem: the text in the different tabs is shown vertically, but the size of every tab seems to be misscalculated. The tabs are not separated correctly. Unfortunatly I'm not allowed to post images... The tabs overlay each other.

I don't know how to fix this problem :-( Here's my code:

SwingTest.java

public SwingTest(JFrame owner) {

    super(null);

    setOpaque(true);
    setSize(WIDTH, HEIGHT);
    owner.setSize(WIDTH, HEIGHT);

    JTabbedPane pane = new JTabbedPane(JTabbedPane.LEFT);
    pane.setName("MyPane");
    pane.setSize(WIDTH, HEIGHT);

    // Add a tab
    JPanel p1 = new JPanel();
    p1.setSize(300, 300);

    JPanel p2 = new JPanel();
    p2.setSize(500, 500);

    JPanel p3 = new JPanel();
    p3.setSize(300, 300);

    p3.add(new JLabel("HALLO"));

    JPanel p4 = new JPanel();
    p4.setSize(300, 300);

    JButton roundedButton = new JButton("Halloi Button");
    roundedButton.setName("roundedButton");

    p2.add(roundedButton);

    pane.addTab(EFFORT_CARD, p1);
    pane.addTab(EMOTION_CARD, p2);
    pane.addTab(COMFORT_CARD, p3);
    pane.addTab(DRIVING_CARD, p4);

    add(pane);

    pane.updateUI();

laf.xml

<bind style="tabNavigationStyle" type="region" key="TabbedPaneTab" />

MySynthGraphicsUtils.java

public class MySynthGraphicsUtils extends SynthGraphicsUtils {
public void paintText(SynthContext ss, Graphics g, String text, int x, int y, int mnemonicIndex) {

    Graphics2D g2 = (Graphics2D) g;

    System.out.println(ss.getComponent().getClass().getName());

    Object oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);

    g2.setFont(ss.getStyle().getFont(ss));
    AffineTransform tx = new AffineTransform();
    tx.rotate(90 * Math.PI / 180, x, y);
    g2.setTransform(tx);

    g2.drawString(text, x, y);

    // get metrics from the graphics
    FontMetrics metrics = g2.getFontMetrics(ss.getStyle().getFont(ss));
    // get the height of a line of text in this font and render context
    int hgt = metrics.getHeight();
    // get the advance of my text in this font and render context
    int adv = metrics.stringWidth(text);
    // calculate the size of a box to hold the text with some padding.
    Dimension size = new Dimension(adv + 2, hgt + 2);

    //g2.setClip(0, 0, size.width, size.height);

    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue);
}

}

Thank you very much!!

Body:
As a workaround, I use an image border with an sourceInset on the Left side to seperate Tabs. I make the image the same colour as the background of the app:

        <state>
                <opaque value="true"/>
                <color value="black" type="BACKGROUND" />
                <color value="white" type="TEXT_FOREGROUND" />
                <imagePainter method="tabbedPaneTabBorder" path="relative/path/to/white_border.png"
             sourceInsets="0 1 0 0" paintCenter="false"/>
                <insets top="3" bottom="3" right="3" left="3"/>
        </state>


问:
Hibernate Multi tenancy issue with H2: wrong schema
I am building an application that uses PostgreSQL in production and H2 for local development and tests using latest versions of Hibernate and Java 8.

The implementation works fine for PostgreSQL, but causes issues when using H2. If I call the same endpoint to create an entity for 2 different tenants, all entities are created in the same (first) schema that was called.

getConnection() in my MultiTenantConnectionProviderImpl:

```<code>@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
    final Connection connection = getAnyConnection();
    connection.setSchema(tenantIdentifier);
    return connection;
}
</code>```

application.properties:

```<code>spring.datasource.url=jdbc:h2:mem:mydb;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE
spring.datasource.username=sa
spring.datasource.password=
</code>```

Note that even though the correct tenantIdentifier is passed into getConnection, the query is still run against the wrong schema.

Could this be an issue with the Hikari Connection Pool caching the connections and not propagating the setSchema() call?

答:
It looks like this is a bug with H2 and it's query cache not picking up a change in schema.

Disabling the query cache completely works around the issue:

jdbc:h2:mem:mydb;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;QUERY_CACHE_SIZE=0

Created a bug report: https://github.com/h2database/h2database/issues/1952

Body:
I am building an application that uses PostgreSQL in production and H2 for local development and tests using latest versions of Hibernate and Java 8.

The implementation works fine for PostgreSQL, but causes issues when using H2. If I call the same endpoint to create an entity for 2 different tenants, all entities are created in the same (first) schema that was called.

getConnection() in my MultiTenantConnectionProviderImpl:

@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
    final Connection connection = getAnyConnection();
    connection.setSchema(tenantIdentifier);
    return connection;
}

application.properties:

spring.datasource.url=jdbc:h2:mem:mydb;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE
spring.datasource.username=sa
spring.datasource.password=

Note that even though the correct tenantIdentifier is passed into getConnection, the query is still run against the wrong schema.

Could this be an issue with the Hikari Connection Pool caching the connections and not propagating the setSchema() call?


问:
C# Writeline that responds with name
I haven't used variables on C# yet so I don't know how I would go about having the next Console.Writeline respond saying, "Hello X, welcome!". Adding the users input to the X.</p>

```<code>Console.WriteLine("What is your name?");
String answer = Console.ReadLine();

if (answer == string)
    Console.WriteLine("Okay , welcome!");
}
</code>```

答:
```<code>    Console.WriteLine("Please type your name?");
    var cName = Console.ReadLine();
    Console.WriteLine($"Hay there { cName }, how are you?");
</code>```

Screenshot, working example

Title: C# Writeline that responds with name

Body:
I haven't used variables on C# yet so I don't know how I would go about having the next Console.Writeline respond saying, "Hello X, welcome!". Adding the users input to the X.

Console.WriteLine("What is your name?");
String answer = Console.ReadLine();

if (answer == string)
    Console.WriteLine("Okay , welcome!");
}

Body:
    Console.WriteLine("Please type your name?");
    var cName = Console.ReadLine();
    Console.WriteLine($"Hay there { cName }, how are you?");

Screenshot, working example


问:
Does parallel requests with RXJS will do better to performance?
Problem: I need to download huge file (5-10gb) with simple XHR requests, to simplify a question I need to do at-least: 100 requests (could be more).
I would like to improve the performance to it using RXJS (parallel http-requests).

The questions:

Is it at all possible to improve the performance with Parallel?

Does parallelizing the requests won't be the same as using 1 request for each iteration of the request-loop? The bandwidth is the same - NO?

Is there other ways to improve my perf?

Stack:

Angular 7.2.x

Typescript 3.2.4

Rxjs 6.4.0

What I actually reached for:
What I actually need is to apply sync on mergeMap to trigger it on/off for example I have 100urls but I do not wish em to run until the last one of them.

For example I want it to run up until the 17th but will pause making requests and wait for certain logic and request to finish.

Code Example:

```<code>from(observableQueries)
           .pipe(
               mergeMap(partialQuery => this.messageService.getResults(partialQuery, true), 4),
               takeWhile(o => {
                   if (!o.isMoreResults && o.auditMessageList.length === 0) {
                       this.logger.log(`First page that returns false ${ o.number }`);
                       this.logger.log(`Count of responses that exists in array: ${ allResults.length }`);
                       if (!firstPageThatShouldBeStopped) {
                           firstPageThatShouldBeStopped = o.number;
                       }

                       if (allResults.length === firstPageThatShouldBeStopped) {
                           return false;
                       }
                   }
                   return true;
               }),
               retryWhen(genericRetryStrategy()),
               catchError((err, caught) => {
                   this._alertService.error(this._translate.instant('EXPORT_TO_CSV_DOWNLOAD_ERROR'));
                   return throwError(err);
               })
           )
           .subscribe(
               (res: MessagesResult) => {
                   if (reThrowError) {
                       this.logger.info('Error will be thrown for e2e purposes');
                       throw new Error('Error will throw for e2e purposes');
                   }
                   if (res.isMoreResults && res.auditMessageList.length > 0) {
                       allResults[res.number] = res;
                       this.subject.next(true);
                   } else if (!res.isMoreResults && res.auditMessageList.length > 0) {
                       allResults[res.number] = res;
                       this.subject.next(true);
                   } else {
                       this.subject.next(false);
                   }
               },
               err => {
                   // clear subject after emitting value...
                   this.subject.next(true);
                   return this.handleError(err);
               },
               () => {
                   this.logger.info('Download file finished...');
                   this.logger.info('Time consumed: ', performance.now() - start);
                   try {
                       this.logger.info(`Count Responses: ${ allResults.length } `);
                       const allResultSorted = this._sortResults(allResults);
                       let counter = 0;
                       for (let i = 0; i < allResultSorted.length; i++) {
                           this.logger.info('Index: ' + i, allResultSorted[i]);
                           counter += allResultSorted[i].auditMessageList.length;
                           this.logger.info('Length OF Messages: ' + i, counter);
                           this.fileSaver.save(!allResultSorted[i].isMoreResults, allResultSorted[i].auditMessageList,
                               `audit-events_${ LOCAL_QUERY_COPY.application }_${ timestamp }_${ moment()
                                   .tz(this._timezoneService.timezone).zoneName() }.csv`, null, headers);
                       }
                       this.subject.next(false);
                   } catch (e) {
                       this._alertService.error(this._translate.instant('EXPORT_TO_CSV_DOWNLOAD_ERROR'));
                       return this.handleError(e);
                   } finally {
                       // clear subject after emitting value...
                       this.subject.next(true);
                   }
               }
           );
</code>```

The code works! But the issue is with redundant calls. How it would be possible to make em stop up until the last requests are finished running.

答:
You can use RXJS 'merge' operator:
Assuming that getData(url) is the methode making the request and that this methode return an Observable, you can do:

```<code>const urls: string[] = {url1, url2, url3,...};
let mergeHttpCallObservalbe: Observable<any>;
urls.forEach((url: string) => {
  const newHttpCallObservalbe : Observable<any> = myService.getData(url);
  if (mergeHttpCallObservalbe){
    mergeHttpCallObservalbe = merge(mergeHttpCallObservalbe, newHttpCallObservalbe);
  } else {
    mergeHttpCallObservalbe = newHttpCallObservalbe;
  }
});

// Now you have merged all your Observable, you can subscribe:
mergeHttpCallObservalbe.subscribe(result => {
  // Do your stuff...
});
</code>```

Here is a good article regarding Rxjs Operators: https://blog.angularindepth.com/learn-to-combine-rxjs-sequences-with-super-intuitive-interactive-diagrams-20fce8e6511

Hope it will helps

Body:
Problem: I need to download huge file (5-10gb) with simple XHR requests, to simplify a question I need to do at-least: 100 requests (could be more).
I would like to improve the performance to it using RXJS (parallel http-requests).

The questions:

Is it at all possible to improve the performance with Parallel?

Does parallelizing the requests won't be the same as using 1 request for each iteration of the request-loop? The bandwidth is the same - NO?

Is there other ways to improve my perf?

Stack:

Angular 7.2.x

Typescript 3.2.4

Rxjs 6.4.0

What I actually reached for:
What I actually need is to apply sync on mergeMap to trigger it on/off for example I have 100urls but I do not wish em to run until the last one of them.

For example I want it to run up until the 17th but will pause making requests and wait for certain logic and request to finish.

Code Example:

from(observableQueries)
           .pipe(
               mergeMap(partialQuery => this.messageService.getResults(partialQuery, true), 4),
               takeWhile(o => {
                   if (!o.isMoreResults && o.auditMessageList.length === 0) {
                       this.logger.log(`First page that returns false ${ o.number }`);
                       this.logger.log(`Count of responses that exists in array: ${ allResults.length }`);
                       if (!firstPageThatShouldBeStopped) {
                           firstPageThatShouldBeStopped = o.number;
                       }

                       if (allResults.length === firstPageThatShouldBeStopped) {
                           return false;
                       }
                   }
                   return true;
               }),
               retryWhen(genericRetryStrategy()),
               catchError((err, caught) => {
                   this._alertService.error(this._translate.instant('EXPORT_TO_CSV_DOWNLOAD_ERROR'));
                   return throwError(err);
               })
           )
           .subscribe(
               (res: MessagesResult) => {
                   if (reThrowError) {
                       this.logger.info('Error will be thrown for e2e purposes');
                       throw new Error('Error will throw for e2e purposes');
                   }
                   if (res.isMoreResults && res.auditMessageList.length > 0) {
                       allResults[res.number] = res;
                       this.subject.next(true);
                   } else if (!res.isMoreResults && res.auditMessageList.length > 0) {
                       allResults[res.number] = res;
                       this.subject.next(true);
                   } else {
                       this.subject.next(false);
                   }
               },
               err => {
                   // clear subject after emitting value...
                   this.subject.next(true);
                   return this.handleError(err);
               },
               () => {
                   this.logger.info('Download file finished...');
                   this.logger.info('Time consumed: ', performance.now() - start);
                   try {
                       this.logger.info(`Count Responses: ${ allResults.length } `);
                       const allResultSorted = this._sortResults(allResults);
                       let counter = 0;
                       for (let i = 0; i < allResultSorted.length; i++) {
                           this.logger.info('Index: ' + i, allResultSorted[i]);
                           counter += allResultSorted[i].auditMessageList.length;
                           this.logger.info('Length OF Messages: ' + i, counter);
                           this.fileSaver.save(!allResultSorted[i].isMoreResults, allResultSorted[i].auditMessageList,
                               `audit-events_${ LOCAL_QUERY_COPY.application }_${ timestamp }_${ moment()
                                   .tz(this._timezoneService.timezone).zoneName() }.csv`, null, headers);
                       }
                       this.subject.next(false);
                   } catch (e) {
                       this._alertService.error(this._translate.instant('EXPORT_TO_CSV_DOWNLOAD_ERROR'));
                       return this.handleError(e);
                   } finally {
                       // clear subject after emitting value...
                       this.subject.next(true);
                   }
               }
           );

The code works! But the issue is with redundant calls. How it would be possible to make em stop up until the last requests are finished running.

Body:
You can use RXJS 'merge' operator:
Assuming that getData(url) is the methode making the request and that this methode return an Observable, you can do:

const urls: string[] = {url1, url2, url3,...};
let mergeHttpCallObservalbe: Observable<any>;
urls.forEach((url: string) => {
  const newHttpCallObservalbe : Observable<any> = myService.getData(url);
  if (mergeHttpCallObservalbe){
    mergeHttpCallObservalbe = merge(mergeHttpCallObservalbe, newHttpCallObservalbe);
  } else {
    mergeHttpCallObservalbe = newHttpCallObservalbe;
  }
});

// Now you have merged all your Observable, you can subscribe:
mergeHttpCallObservalbe.subscribe(result => {
  // Do your stuff...
});

Here is a good article regarding Rxjs Operators: https://blog.angularindepth.com/learn-to-combine-rxjs-sequences-with-super-intuitive-interactive-diagrams-20fce8e6511

Hope it will helps


问:
Is there a way of hiding sections of a form with JavaScript?
I am trying to build a Form that is dynamic. I have the form sections built.
In the Header of the form, there is a dropdown option, with five option's that are relevant to five sections of the form. I want to hide all sections until a dropdown option is selected, revealing the relevant section.

I'm trying to do this without Jquery, as I'm trying to grow my javascript skills

```<code>    <label for="issueDescInput">Date of Requests</label>
        <br>
     <input type="date" class="form-control" id="issueSeverityInput">
        <br>

        <label for="TOR">Tasks</label>
         <select class="form-control" id="issueSeverityInput">
          <option value="CO">Task 1</option>
          <option value="ASM">task 2</option>
          <option value="SM">task 3</option>
          <option value="AM">Task 4</option>
          <option value="RC">Task 5</option>
        </select>

       <div class="Tasks-section">
        <div class="Task 1">

      <p>test</p>

       </div>
       </div>

     var select = document.getElementById('TOR'),
     onChange = function(event) {
    var shown = this.options[this.selectedIndex].value == "SM";

    document.getElementById('hidden_div').style.display = shown ? 'block'
  : 'none';
};
</code>```

答:
I think you can have a look at this sample using pure javascript, I already made a Codepen:

A slightly change has been made to the HTML to make things easier.

https://codepen.io/DieByMacro/pen/arKaRX

(function() {
  const selectOption = document.querySelector('#issueSeverityInput');
  const tasks = document.querySelectorAll('.task-section');
  const cssVisible = 'is-visible';

  // Add select onChange event handler
  selectOption.addEventListener('change', onChangeHandler );

  // Calling trigger to check current selected value and update at first time
  triggerSelect();

  function triggerSelect() {
    // Get the current selected at first load
    const currentSelect = selectOption[selectOption.selectedIndex].value

    // Update the task
    updateCurrentTask(currentSelect)
  }

  function updateCurrentTask(value) {
    // Find the correct task to update by adding/removing CSS `is-visible` class
    for(const task of tasks) {
      if (task.getAttribute('data-value') === value ) {
        task.classList.add(cssVisible)
      } else task.classList.remove(cssVisible)
    }
  }

  function onChangeHandler(event) {
    console.log('Selected: ', event.currentTarget.value);
    updateCurrentTask(event.currentTarget.value);
  }
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*
We init the task-section by hiding it. Then later we will use js to toggle class `is-visible`
*/
.task-section {
  display: none;
}
.task-section.is-visible {
  display: block;
}</code>```

Tasks
<select class="form-control" id="issueSeverityInput">
  <option value="1">Task 1</option>
  <option value="2">task 2</option>
  <option value="3">task 3</option>
  <option value="4">Task 4</option>
  <option value="5">Task 5</option>
</select>

This is task 1

This is task 2

This is task 3

This is task 4

This is task 5

```

Body:
I am trying to build a Form that is dynamic. I have the form sections built.
In the Header of the form, there is a dropdown option, with five option's that are relevant to five sections of the form. I want to hide all sections until a dropdown option is selected, revealing the relevant section.

I'm trying to do this without Jquery, as I'm trying to grow my javascript skills

    Date of Requests

     <input type="date" class="form-control" id="issueSeverityInput">

        Tasks
         <select class="form-control" id="issueSeverityInput">
          <option value="CO">Task 1</option>
          <option value="ASM">task 2</option>
          <option value="SM">task 3</option>
          <option value="AM">Task 4</option>
          <option value="RC">Task 5</option>
        </select>

test

     var select = document.getElementById('TOR'),
     onChange = function(event) {
    var shown = this.options[this.selectedIndex].value == "SM";

    document.getElementById('hidden_div').style.display = shown ? 'block'
  : 'none';
};

Body:
I think you can have a look at this sample using pure javascript, I already made a Codepen:

A slightly change has been made to the HTML to make things easier.

https://codepen.io/DieByMacro/pen/arKaRX

(function() {
  const selectOption = document.querySelector('#issueSeverityInput');
  const tasks = document.querySelectorAll('.task-section');
  const cssVisible = 'is-visible';

  // Add select onChange event handler
  selectOption.addEventListener('change', onChangeHandler );

  // Calling trigger to check current selected value and update at first time
  triggerSelect();

  function triggerSelect() {
    // Get the current selected at first load
    const currentSelect = selectOption[selectOption.selectedIndex].value

    // Update the task
    updateCurrentTask(currentSelect)
  }

  function updateCurrentTask(value) {
    // Find the correct task to update by adding/removing CSS `is-visible` class
    for(const task of tasks) {
      if (task.getAttribute('data-value') === value ) {
        task.classList.add(cssVisible)
      } else task.classList.remove(cssVisible)
    }
  }

  function onChangeHandler(event) {
    console.log('Selected: ', event.currentTarget.value);
    updateCurrentTask(event.currentTarget.value);
  }
})();

/*
We init the task-section by hiding it. Then later we will use js to toggle class `is-visible`
*/
.task-section {
  display: none;
}
.task-section.is-visible {
  display: block;
}

<label for="TOR">Tasks</label>
<select class="form-control" id="issueSeverityInput">
  <option value="1">Task 1</option>
  <option value="2">task 2</option>
  <option value="3">task 3</option>
  <option value="4">Task 4</option>
  <option value="5">Task 5</option>
</select>

<div class="tasks-wrapper">
  <div class="task-section" data-value="1">
    <p>This is task 1</p>
  </div>
  <div class="task-section" data-value="2">
    <p>This is task 2</p>
  </div>
  <div class="task-section" data-value="3">
    <p>This is task 3</p>
  </div>
  <div class="task-section" data-value="4">
    <p>This is task 4</p>
  </div>
  <div class="task-section" data-value="5">
    <p>This is task 5</p>
  </div>
</div>


问:
Is there a way to determine the line endings in a existing git repo?
Is there a way to determine the line endings in a existing git repository?

If I clone a existing repository how do I determine what core.autocrlf was used by the creator?

I'm still uncertain whats the best setting for core.autocrlf e.g on a windows box
(since there are multiple opinions:   Distributing git configuration with the code or https://help.github.com/articles/dealing-with-line-endings)

Bonus question: Can you determine on windows (with standard tools) if a repo has mixed line endings (by wrong core.autocrlf setting) through all commits?

答:
Is there a way to determine the line endings in a existing git repository?

```<code>git ls-files --eol

# for a given file:
git -c color.diff.whitespace="red reverse" diff -R -- afile
</code>```

In Windows, just run the below command from the command prompt:

```<code>git config --list
</code>```

This will list all the git configuration variables.

If you want to get the individual config setting (e.g. for core.autocrlf), run the following command on the windows command prompt:

```<code>git config --get core.autocrlf
</code>```

This will either give you a "true" OR "false" value.

If you wish to change this, edit C:\ProgramData\Git\config file, and change the value from false to true

Note: This only applies for Windows operating systems.

Body:
Is there a way to determine the line endings in a existing git repository?

git ls-files --eol

# for a given file:
git -c color.diff.whitespace="red reverse" diff -R -- afile

In Windows, just run the below command from the command prompt:

git config --list

This will list all the git configuration variables.

If you want to get the individual config setting (e.g. for core.autocrlf), run the following command on the windows command prompt:

git config --get core.autocrlf

This will either give you a "true" OR "false" value.

If you wish to change this, edit C:\ProgramData\Git\config file, and change the value from false to true

Note: This only applies for Windows operating systems.


问:
Image loading icon for flash/flex?
You often see those little 'petal' animations while an image or .swf file is loading in a Flash / Flex application.

Do I have to steal this from someone or is there a standard one available from somewhere. i would think there is somethin standard because everyones looks the same!

Ideally I want a flex Image control that displays such an icon when it is loading for more than 1/4 second.

答: Here are a few "loading" SWF files you can use.</p>

OwnerDisplayName: Simon

Title: Image loading icon for flash/flex?


问:
How to show multiple existing markers from google maps sorting by sports category?
I have an android application where I need to show all existing sport courts from a specific zone, these courts need to be marked with a pin and in the moment when I click the pin, some information about the court will be displayed.

How to get those existing markers from Google Maps automatically, without manually inserting for every place the exact location (longitude and latitude).

答:
I think you are looking for GOOGLE PLACES SDK , it allows you to get all places by category referred here . and also with nearby option

and once you get your Place information through Place ID , then you can show it on marker infowindow

Note that using GOOGLE PLACES SDK is not for free