问:
unable to fetch data from ejs to controller and client side JS
I am a newbie in node and express. I am working on an app that has a login module. I am able to register a user but am facing some issues while trying to log in a user.

Please find my code below and suggest:

Logincontroller.js

```<code>app.post('/testAction',urlencodedParser,function(req,res){

    var usrnm = req.body.username;
    console.log(" usrnm ::: " + usrnm);
    var passwd = req.body.password;
    console.log(" passwd ::: " + passwd);
    Users.findOne({username:"tstusr1"},function(err,data){ // Users is my schema name
        if(err) throw err;
        console.log(" back from ajax with data in login controller :::; " + data);
        res.json(data);
    });
    console.log("inside index2 post");
});
</code>```

my Login-user.js is

```<code>$(document).ready(function(){

      var items = $('form');
      var user ={username: $('[name=username]', items).val()};
      console.log('user  ' + JSON.stringify(user));

  $('form').on('submit', function(){
      console.log("inside submit login");
      $.ajax({
          type: 'POST',
          url: '/testAction',
          data: user,
          success: function(data, textStatus, jqXHR){
            var resp = JSON.parse(JSON.stringify(jqXHR));
            if(resp["status"]==200){
                console.log("status == 200");
                window.location.href = '/';
            }
              return data;
          },
          error:function (jqXHR, textStatus, errorThrown) {

              console.log('error  ' + JSON.stringify(user));
              console.log("resp1 :::::: " + JSON.stringify(jqXHR));
              var resp = JSON.parse(JSON.stringify(jqXHR));
              console.log("resp :::::: " + resp);
          }
        });
         return false;
  });
});
</code>```

And my ejs file is

```<code><form action="/testAction">
    <label for="username"> Username </label>
    <input type="text" for="username" name="username" />
    <label for="password"> Password </label>
    <input type="password" for="password" name="password" />
    <button type="submit">Log In</button>
</form>
</code>```

My issue is I am not able to fetch the values of username and password to the client side js as well as backend server side js.

Please assist

答:
Found the solution:

Logincontroller.js

```<code>app.post('/testAction',urlencodedParser,function(req,res){

    var reqData = JSON.parse(JSON.stringify(req.body));
    console.log(" reqData username :::::::: " + reqData['username']);

    console.log(" reqData password :::::::: " + reqData['password']);

    Users.findOne({username:reqData['username']},function(err,data){
        if(err) throw err;
        console.log(" back from ajax with data in login controller :::; " + data);
        res.json(data);
});
</code>```

Login-user.js

```<code>$(document).ready(function(){

  $('form').on('submit', function(){
      console.log("inside submit login");

      var items = $('form');
      var user ={
              username: $('[name=username]', items).val(),
              password: $('[name=password]', items).val()
           };

      $.ajax({
          type: 'POST',
          url: '/testAction',
          data: user,
          success: function(data, textStatus, jqXHR){
            var resp = JSON.parse(JSON.stringify(jqXHR));
            console.log(" resp :::::: " + resp);
            if(resp["status"]==200){
                console.log("status == 200");
                var respData =JSON.parse(JSON.stringify(data));
                var enteredPassword = JSON.parse(JSON.stringify(user));
                console.log(" respData password :::::: " + respData.password);
                console.log(" enteredPassword password :::::: " + enteredPassword.password);

                if(enteredPassword.password==respData.password){
                    console.log("success Matched");
                }else {
                    console.log("unsuccessful not-Matched");
                }

            }
              return data;
          },
          error:function (jqXHR, textStatus, errorThrown) {

              console.log('error  ' + JSON.stringify(user));
              console.log("resp1 :::::: " + JSON.stringify(jqXHR));
              var resp = JSON.parse(JSON.stringify(jqXHR));
              console.log("resp :::::: " + resp);
          }
        });
         return false;
  });
});
</code>```

ejs File :

```<code><form action="/testAction">
    <label for="username"> Username </label>
    <input type="text" for="username" name="username"/>
    <label for="password"> Password </label>
    <input type="password" for="password" name="password" />

    <button type="submit">Log In</button>
</form>
</code>```

Body:
I am a newbie in node and express. I am working on an app that has a login module. I am able to register a user but am facing some issues while trying to log in a user.

Please find my code below and suggest:

Logincontroller.js

app.post('/testAction',urlencodedParser,function(req,res){

    var usrnm = req.body.username;
    console.log(" usrnm ::: " + usrnm);
    var passwd = req.body.password;
    console.log(" passwd ::: " + passwd);
    Users.findOne({username:"tstusr1"},function(err,data){ // Users is my schema name
        if(err) throw err;
        console.log(" back from ajax with data in login controller :::; " + data);
        res.json(data);
    });
    console.log("inside index2 post");
});

my Login-user.js is

$(document).ready(function(){

      var items = $('form');
      var user ={username: $('[name=username]', items).val()};
      console.log('user  ' + JSON.stringify(user));

  $('form').on('submit', function(){
      console.log("inside submit login");
      $.ajax({
          type: 'POST',
          url: '/testAction',
          data: user,
          success: function(data, textStatus, jqXHR){
            var resp = JSON.parse(JSON.stringify(jqXHR));
            if(resp["status"]==200){
                console.log("status == 200");
                window.location.href = '/';
            }
              return data;
          },
          error:function (jqXHR, textStatus, errorThrown) {

              console.log('error  ' + JSON.stringify(user));
              console.log("resp1 :::::: " + JSON.stringify(jqXHR));
              var resp = JSON.parse(JSON.stringify(jqXHR));
              console.log("resp :::::: " + resp);
          }
        });
         return false;
  });
});

And my ejs file is

<form action="/testAction">
     Username
    <input type="text" for="username" name="username" />
     Password
    <input type="password" for="password" name="password" />
    <button type="submit">Log In</button>
</form>

My issue is I am not able to fetch the values of username and password to the client side js as well as backend server side js.

Please assist

Body:
Found the solution:

Logincontroller.js

app.post('/testAction',urlencodedParser,function(req,res){

    var reqData = JSON.parse(JSON.stringify(req.body));
    console.log(" reqData username :::::::: " + reqData['username']);

    console.log(" reqData password :::::::: " + reqData['password']);

    Users.findOne({username:reqData['username']},function(err,data){
        if(err) throw err;
        console.log(" back from ajax with data in login controller :::; " + data);
        res.json(data);
});

Login-user.js

$(document).ready(function(){

  $('form').on('submit', function(){
      console.log("inside submit login");

      var items = $('form');
      var user ={
              username: $('[name=username]', items).val(),
              password: $('[name=password]', items).val()
           };

      $.ajax({
          type: 'POST',
          url: '/testAction',
          data: user,
          success: function(data, textStatus, jqXHR){
            var resp = JSON.parse(JSON.stringify(jqXHR));
            console.log(" resp :::::: " + resp);
            if(resp["status"]==200){
                console.log("status == 200");
                var respData =JSON.parse(JSON.stringify(data));
                var enteredPassword = JSON.parse(JSON.stringify(user));
                console.log(" respData password :::::: " + respData.password);
                console.log(" enteredPassword password :::::: " + enteredPassword.password);

                if(enteredPassword.password==respData.password){
                    console.log("success Matched");
                }else {
                    console.log("unsuccessful not-Matched");
                }

            }
              return data;
          },
          error:function (jqXHR, textStatus, errorThrown) {

              console.log('error  ' + JSON.stringify(user));
              console.log("resp1 :::::: " + JSON.stringify(jqXHR));
              var resp = JSON.parse(JSON.stringify(jqXHR));
              console.log("resp :::::: " + resp);
          }
        });
         return false;
  });
});

ejs File :

<form action="/testAction">
    <label for="username"> Username </label>
    <input type="text" for="username" name="username"/>
    <label for="password"> Password </label>
    <input type="password" for="password" name="password" />

    <button type="submit">Log In</button>
</form>


来源: stackexchange

问:
Django error message "Add a related_name argument to the definition"
```<code>D:\zjm_code\basic_project>python manage.py syncdb
Error: One or more models did not validate:
topics.topic: Accessor for field 'content_type' clashes with related field 'Cont
entType.topic_set'. Add a related_name argument to the definition for 'content_t
ype'.
topics.topic: Accessor for field 'creator' clashes with related field 'User.crea
ted_topics'. Add a related_name argument to the definition for 'creator'.
topics.topic: Reverse query name for field 'creator' clashes with related field
'User.created_topics'. Add a related_name argument to the definition for 'creato
r'.
topicsMap.topic: Accessor for field 'content_type' clashes with related field 'C
ontentType.topic_set'. Add a related_name argument to the definition for 'conten
t_type'.
topicsMap.topic: Accessor for field 'creator' clashes with related field 'User.c
reated_topics'. Add a related_name argument to the definition for 'creator'.
topicsMap.topic: Reverse query name for field 'creator' clashes with related fie
ld 'User.created_topics'. Add a related_name argument to the definition for 'cre
ator'.
</code>```

答:
Example:

```<code>class Article(models.Model):
    author = models.ForeignKey('accounts.User')
    editor = models.ForeignKey('accounts.User')

</code>```

This will cause the error, because Django tries to automatically create a backwards relation for instances of accounts.User for each foreign key relation to user like user.article_set.  This default method is ambiguous.  Would user.article_set.all() refer to the user's articles related by the author field, or by the editor field?

Solution:

```<code>class Article(models.Model):
    author = models.ForeignKey('accounts.User', related_name='author_article_set')
    editor = models.ForeignKey('accounts.User', related_name='editor_article_set')
</code>```

Now, for an instance of user user, there are two different manager methods:

user.author_article_set — user.author_article_set.all() will return a Queryset of all Article objects that have author == user

user.editor_article_set — user.editor_article_set.all() will return a Queryset of all Article objects that have editor == user

Note:
This is an old example — on_delete is now another required argument to models.ForeignKey.  Details at What does on_delete do on Django models?

ContentLicense: CC BY-SA 3.0

Body:
Example:

class Article(models.Model):
    author = models.ForeignKey('accounts.User')
    editor = models.ForeignKey('accounts.User')

This will cause the error, because Django tries to automatically create a backwards relation for instances of accounts.User for each foreign key relation to user like user.article_set.  This default method is ambiguous.  Would user.article_set.all() refer to the user's articles related by the author field, or by the editor field?

Solution:

class Article(models.Model):
    author = models.ForeignKey('accounts.User', related_name='author_article_set')
    editor = models.ForeignKey('accounts.User', related_name='editor_article_set')

Now, for an instance of user user, there are two different manager methods:

user.author_article_set — user.author_article_set.all() will return a Queryset of all Article objects that have author == user

user.editor_article_set — user.editor_article_set.all() will return a Queryset of all Article objects that have editor == user

Note:
This is an old example — on_delete is now another required argument to models.ForeignKey.  Details at What does on_delete do on Django models?

ContentLicense: CC BY-SA 4.0


问:
Legal site SQL injection attack
i have to write a report based on an a simple SQL injection attack. In this report i have to provide screenshots of my "walkthrough" so i cannot use pictures of other tutorials on the web. Now my question is: can anybody tell me the names of some websites vulnerable to SQL injection attack on which i can test my attack legally? Thanks to Google dorks i have already found some vulnerable websites, but i think that running the attack over them is illegal. I want to avoid the setting up of a personal website for this purpose, but if there are no other solutions i need an help also in setting up this kind of site.</p>

答:
There is a web application called DVWA (Damn Vulnerable Web Application), it's not hosted on the internet. you have to download it and run as localhost on your computer. However it has a range of vulnerabilities, i have used it in the past for trying out a brute force attack. As its localhost its legal. it should be ideal for a walk through tutorial. I know you said that you didn't want to setup your own website, but the setup is a few minutes. Hope this Helps :D

Link: http://www.dvwa.co.uk/

Title: Legal site SQL injection attack


问:
C# - Creating X and Y axis with customizable rectangles
I'm working on a school project.

The goal is to create X and Y axis with numbers, that part I can handle.

Problem is, I have to create numericUpDowns that will allow me to create rectangles on specific X and Y axis with specific size. The size and position is to be controlled by the numericUpDowns. I could use some help as I do not know any command that could connect the two.

Also if there is a way for the numbers on the axis to repeat itself without me having to write it individualy then I could use that as well.

How it should look

```<code>        public void tvary(float x, float y, float polomer, Graphics gr)
        {

        gr.DrawEllipse(Pens.Black, x, y, polomer, polomer);
        gr.DrawEllipse(Pens.Black, x - 15, y - 15, polomer * 2, polomer * 2);
        gr.DrawEllipse(Pens.Black, x - 30, y - 30, polomer * 3, polomer * 3);

        gr.DrawRectangle(Pens.Red, x-30, y-30, polomer * 3, polomer * 3);
        }
</code>```

Right now the X and Y position of the rectangles are written in the code itself. I would like to move the rectangles by using the numericUpDows that are shown on Pic 3.
The thing is that I do not know how to do that.

Unfortunately I cannot post more than 1 picture at the moment.

答:
NumericUpDownhave ValueChanged ActionEvent. So every time when you change the value in NumericUpDown method for that action will be execute. You just need in method for ActionEvent to call your method for drawing rectangle. So you need to send parameters for x and y. First you need to take it from NumericUpDown

```<code>private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    int x = Convert.ToInt16(numericUpDown1.Value);
    int x = Convert.ToInt16(numericUpDown2.Value);
    tvary(x, y, polomer, gr);
}
</code>```

code is the same for second numericUpDown.

PS: You can put start Value for numericUpDown control.

Body:
I'm working on a school project.

The goal is to create X and Y axis with numbers, that part I can handle.

Problem is, I have to create numericUpDowns that will allow me to create rectangles on specific X and Y axis with specific size. The size and position is to be controlled by the numericUpDowns. I could use some help as I do not know any command that could connect the two.

Also if there is a way for the numbers on the axis to repeat itself without me having to write it individualy then I could use that as well.

How it should look

        public void tvary(float x, float y, float polomer, Graphics gr)
        {

        gr.DrawEllipse(Pens.Black, x, y, polomer, polomer);
        gr.DrawEllipse(Pens.Black, x - 15, y - 15, polomer * 2, polomer * 2);
        gr.DrawEllipse(Pens.Black, x - 30, y - 30, polomer * 3, polomer * 3);

        gr.DrawRectangle(Pens.Red, x-30, y-30, polomer * 3, polomer * 3);
        }

Right now the X and Y position of the rectangles are written in the code itself. I would like to move the rectangles by using the numericUpDows that are shown on Pic 3.
The thing is that I do not know how to do that.

Unfortunately I cannot post more than 1 picture at the moment.

Body:
NumericUpDownhave ValueChanged ActionEvent. So every time when you change the value in NumericUpDown method for that action will be execute. You just need in method for ActionEvent to call your method for drawing rectangle. So you need to send parameters for x and y. First you need to take it from NumericUpDown

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    int x = Convert.ToInt16(numericUpDown1.Value);
    int x = Convert.ToInt16(numericUpDown2.Value);
    tvary(x, y, polomer, gr);
}

code is the same for second numericUpDown.

PS: You can put start Value for numericUpDown control.


问:
Repeat state until it doesn't change / is stable
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

```<code>Eq s => State s () -> State s ()
</code>```

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

答:
Expanding on the answer from https://stackoverflow.com/a/44381834/1319998, so keeping the iteration out of State, but avoiding the function monad magic with a clearer use of until

```<code>untilStable :: Eq a => (a -> a) -> a -> a
untilStable f a = until (\w -> f w == w) f a
</code>```

... and similarly extracting the s -> s from a state using execState

```<code>untilStable (execState stateTransformToRunRepeatedly) initialState
</code>```

Point-free style isn't used, but to me it is clearer what's going on.

Also, I wonder if this reveals an inefficiency of both this and https://stackoverflow.com/a/44381834/1319998, where f a may be computed twice: once privately inside until, and once in the predicate used to test whether to stop.

Body:
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

Eq s => State s () -> State s ()

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

Body:
Expanding on the answer from https://stackoverflow.com/a/44381834/1319998, so keeping the iteration out of State, but avoiding the function monad magic with a clearer use of until

untilStable :: Eq a => (a -> a) -> a -> a
untilStable f a = until (\w -> f w == w) f a

... and similarly extracting the s -> s from a state using execState

untilStable (execState stateTransformToRunRepeatedly) initialState

Point-free style isn't used, but to me it is clearer what's going on.

Also, I wonder if this reveals an inefficiency of both this and https://stackoverflow.com/a/44381834/1319998, where f a may be computed twice: once privately inside until, and once in the predicate used to test whether to stop.


问:
Using SpringBoot CrudRepository to find one known entry
I am currently working with a project that uses SpringBoot.

I have created a tabled called configuration_documents using Hibernate.  This table can store different types of document objects that I have created.

One of the document objects I have created is Index, and I want to retrieve Index data, so I created a repository like this:

```<code>public interface IndexRepository extends CrudRepository<Index, Long> {
}
</code>```

I know for a fact that the configuration_document table should only have one entry of Index, or else just return the 1st Index in the table.  What is best way of implementing this?

Without modifying IndexRepository, I am currently thinking of something like this (The IndexRepository is autowired in):

```<code>StreamSupport.stream(this.configurationRepository.findAll().spliterator(), false).
                map(
                    return Index;
                ).//A Collector here perhaps?
</code>```

Thanks.

答:
First of all I suggest you to think what do you want to do with that Index in the future.
In case it is just readonly immutable entity then probably the best option is to make some 'IndexHolder' component inject entity into it just after application start (using raw EntityManager for example) and use this component to access Index across the application.

But I'm assuming that you want to be able to update Index as well.
So in this case I can suggest extending an org.springframework.data.repository.Repository instead of CrudRepository. It will limit the possible set of operation on Index entity to NONE but we're still be able to use spring-data features.

So the repository might look like this:

```<code>// Can only insert/update index entity for now
interface IndexRepository extends Repository<Index, String> {

    Index save(Index index);
}
</code>```

Obviously it isn't enough, we need at least a retrieve operation.
And here I suggest to rely on some fixed ID for Index.
It could be some value out of sequence range or '0' or guid (depends on what you're using).

Then we will need to enforce using this ID on all persistence operations with this entity, but as a result query will be fast and simple.

I suppose you're modeling your classes like this:

```<code>@Entity
@Table(name = "configuration_documents")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("DOCUMENT")
public class ConfigurationDocument {
    @Id
    private String id;

    public void setId(String id) {
        this.id = id;
    }
}

@Entity(name = "Index")
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("INDEX")
public class Index extends ConfigurationDocument {
    ...
}
</code>```

Let's add that fixed id:

```<code>@Entity(name = "Index")
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("INDEX")
@EntityListeners(Index.IndexPersistentId.class)
public class Index extends ConfigurationDocument {
    //This is going to be our fixed id.
    public static final String INDEX_ID = "42";

    public static class IndexPersistentId {
        @PrePersist
        public void prePersist(Index index) {
            index.setId(INDEX_ID); //enforce using fixed ID
        }
    }
}
</code>```

And the last step is to add a retrieve operation to the repository:

```<code>interface IndexRepository extends Repository<Index, String> {
    @Query("select i from Index i where i.id = :#{T(com.stackoverflow.so44249828.Index).INDEX_ID}")
    Index load();

    Index save(Index index);
}
</code>```

Body:
I am currently working with a project that uses SpringBoot.

I have created a tabled called configuration_documents using Hibernate.  This table can store different types of document objects that I have created.

One of the document objects I have created is Index, and I want to retrieve Index data, so I created a repository like this:

public interface IndexRepository extends CrudRepository<Index, Long> {
}

I know for a fact that the configuration_document table should only have one entry of Index, or else just return the 1st Index in the table.  What is best way of implementing this?

Without modifying IndexRepository, I am currently thinking of something like this (The IndexRepository is autowired in):

StreamSupport.stream(this.configurationRepository.findAll().spliterator(), false).
                map(
                    return Index;
                ).//A Collector here perhaps?

Thanks.

Body:
First of all I suggest you to think what do you want to do with that Index in the future.
In case it is just readonly immutable entity then probably the best option is to make some 'IndexHolder' component inject entity into it just after application start (using raw EntityManager for example) and use this component to access Index across the application.

But I'm assuming that you want to be able to update Index as well.
So in this case I can suggest extending an org.springframework.data.repository.Repository instead of CrudRepository. It will limit the possible set of operation on Index entity to NONE but we're still be able to use spring-data features.

So the repository might look like this:

// Can only insert/update index entity for now
interface IndexRepository extends Repository<Index, String> {

    Index save(Index index);
}

Obviously it isn't enough, we need at least a retrieve operation.
And here I suggest to rely on some fixed ID for Index.
It could be some value out of sequence range or '0' or guid (depends on what you're using).

Then we will need to enforce using this ID on all persistence operations with this entity, but as a result query will be fast and simple.

I suppose you're modeling your classes like this:

@Entity
@Table(name = "configuration_documents")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("DOCUMENT")
public class ConfigurationDocument {
    @Id
    private String id;

    public void setId(String id) {
        this.id = id;
    }
}

@Entity(name = "Index")
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("INDEX")
public class Index extends ConfigurationDocument {
    ...
}

Let's add that fixed id:

@Entity(name = "Index")
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("INDEX")
@EntityListeners(Index.IndexPersistentId.class)
public class Index extends ConfigurationDocument {
    //This is going to be our fixed id.
    public static final String INDEX_ID = "42";

    public static class IndexPersistentId {
        @PrePersist
        public void prePersist(Index index) {
            index.setId(INDEX_ID); //enforce using fixed ID
        }
    }
}

And the last step is to add a retrieve operation to the repository:

interface IndexRepository extends Repository<Index, String> {
    @Query("select i from Index i where i.id = :#{T(com.stackoverflow.so44249828.Index).INDEX_ID}")
    Index load();

    Index save(Index index);
}


问:
Autopostback not updating updatePanels in IE6
having an issue supporting IE6 (meh)..

I have an update panel that is triggered by radio buttons.  Its pretty straightforward.. show a form if one button it clicked, or another form if another button is clicked.  In IE 7, 8, Firefox, etc. this works fine.

In IE6, the radiobutton selection doesnt update the form.  If I make a selection, then click the submit button, when the page reloads it will be in it's desired state (meaning the correct form will show). So it's almost like the AutoPostback isnt firing to update the page.

Has anyone encountered this issue?  Thanks In Advance..

Here's a shortened sample of what Im running into:

```<code><asp:UpdatePanel ID="updrdoBuyingFor" runat="server">
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="rdoBuyingFor" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
    <asp:RadioButtonList ID="rdoBuyingFor" runat="server" AutoPostBack="true" >
        <asp:ListItem Text="I am buying for someone else" Value="1" />
        <asp:ListItem Text="It's for me" Value="2" />
    </asp:RadioButtonList>
</ContentTemplate>
</code>```

```<code><asp:UpdatePanel ID="updMyInfo" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddlMyInfo_Country" EventName="SelectedIndexChanged" />
        <asp:AsyncPostBackTrigger ControlID="imgBtnContinue" EventName="Click" />
        <asp:AsyncPostBackTrigger ControlID="rdoBuyingFor" EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>
        ...Code for Form A...
    </ContentTemplate>
<asp:UpdatePanel ID="updFriendsInfo" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddlMyInfo_Country" EventName="SelectedIndexChanged" />
        <asp:AsyncPostBackTrigger ControlID="imgBtnContinue" EventName="Click" />
        <asp:AsyncPostBackTrigger ControlID="rdoBuyingFor" EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>
        ...Code for Form B...
    </ContentTemplate>
</code>```

In response to @Pabuc below, Im setting the visible property of the table in "Code for Form A\B" to true or false depending on the radio button selection.

答: Attributing this issue to the same question\answer I posted here: asp net 4 - autopostback doesnt fire in ie6</p>

ContentLicense: CC BY-SA 2.5

Body:
having an issue supporting IE6 (meh)..

I have an update panel that is triggered by radio buttons.  Its pretty straightforward.. show a form if one button it clicked, or another form if another button is clicked.  In IE 7, 8, Firefox, etc. this works fine.

In IE6, the radiobutton selection doesnt update the form.  If I make a selection, then click the submit button, when the page reloads it will be in it's desired state (meaning the correct form will show). So it's almost like the AutoPostback isnt firing to update the page.

Has anyone encountered this issue?  Thanks In Advance..

Here's a shortened sample of what Im running into:

<asp:UpdatePanel ID="updrdoBuyingFor" runat="server">
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="rdoBuyingFor" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
    <asp:RadioButtonList ID="rdoBuyingFor" runat="server" AutoPostBack="true" >
        <asp:ListItem Text="I am buying for someone else" Value="1" />
        <asp:ListItem Text="It's for me" Value="2" />
    </asp:RadioButtonList>
</ContentTemplate>

<asp:UpdatePanel ID="updMyInfo" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddlMyInfo_Country" EventName="SelectedIndexChanged" />
        <asp:AsyncPostBackTrigger ControlID="imgBtnContinue" EventName="Click" />
        <asp:AsyncPostBackTrigger ControlID="rdoBuyingFor" EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>
        ...Code for Form A...
    </ContentTemplate>
<asp:UpdatePanel ID="updFriendsInfo" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddlMyInfo_Country" EventName="SelectedIndexChanged" />
        <asp:AsyncPostBackTrigger ControlID="imgBtnContinue" EventName="Click" />
        <asp:AsyncPostBackTrigger ControlID="rdoBuyingFor" EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>
        ...Code for Form B...
    </ContentTemplate>

In response to @Pabuc below, Im setting the visible property of the table in "Code for Form A\B" to true or false depending on the radio button selection.


问:
Levenstein distance substring
Is there a good way to use levenstein distance to match one particular string to any region within a second longer string?

Example:

```<code>str1='aaaaa'
str2='bbbbbbaabaabbbb'

if str1 in str2 with a distance < 2:
    return True
</code>```

So in the above example part of string 2 is aabaa and distance(str1,str2) < 2 so the statement should return True.

The only way I can think to do this is take 5 chars from str2 at a time, compare that with str1 and then repeat this moving through str2. Unfortunately this seems really inefficient and I need to process a large amount of data this way.

答:
You might have a look at the regex module that supports fuzzy matching:

```<code>>>> import regex
>>> regex.search("(aaaaa){s<2}", 'bbbbbbaabaabbbb')
<regex.Match object; span=(6, 11), match='aabaa', fuzzy_counts=(1, 0, 0)>
</code>```

Since you are looking are strings of equal length, you can also do a a Hamming distance which is likely far faster than a Levenstein distance on the same two strings:

```<code>str1='aaaaa'
str2='bbbbbbaabaabbbb'
for s in [str2[i:i+len(str1)] for i in range(0,len(str2)-len(str1)+1)]:
    if sum(a!=b for a,b in zip(str1,s))<2:
        print s    # prints 'aabaa'
</code>```

Title: Levenstein distance substring

Body:
Is there a good way to use levenstein distance to match one particular string to any region within a second longer string?

Example:

str1='aaaaa'
str2='bbbbbbaabaabbbb'

if str1 in str2 with a distance < 2:
    return True

So in the above example part of string 2 is aabaa and distance(str1,str2) < 2 so the statement should return True.

The only way I can think to do this is take 5 chars from str2 at a time, compare that with str1 and then repeat this moving through str2. Unfortunately this seems really inefficient and I need to process a large amount of data this way.

Body:
You might have a look at the regex module that supports fuzzy matching:

>>> import regex
>>> regex.search("(aaaaa){s<2}", 'bbbbbbaabaabbbb')
<regex.Match object; span=(6, 11), match='aabaa', fuzzy_counts=(1, 0, 0)>

Since you are looking are strings of equal length, you can also do a a Hamming distance which is likely far faster than a Levenstein distance on the same two strings:

str1='aaaaa'
str2='bbbbbbaabaabbbb'
for s in [str2[i:i+len(str1)] for i in range(0,len(str2)-len(str1)+1)]:
    if sum(a!=b for a,b in zip(str1,s))<2:
        print s    # prints 'aabaa'


问:
Get list of all instantiated controls in registry
I understand that OpenUI5's has a registry of instantiated controls and can be queried with sap.ui.getCore().byId.

But, is there a way to get a full list of instances in the control registry?

Something like this:

```<code>var aControls = sap.ui.getCore().allControls();
</code>```

答:
There is no public API for this.

If your page has a  root view you could create a recuresive function that traverse the view tree by applying getters for each control aggregations and going over all they content (and so on).

You can use the control's getMetadata() method for getting the public aggregations names.

Note that in this way you only have access to controls on the public aggregations and not to inner ones.

Body:
I understand that OpenUI5's has a registry of instantiated controls and can be queried with sap.ui.getCore().byId.

But, is there a way to get a full list of instances in the control registry?

Something like this:

var aControls = sap.ui.getCore().allControls();


问:
Properties file vs environment variable
Hey i wondered what is the difference between .properties file to environment variable in java.

.Properties file

```<code>arg1=text1

arg2=text2
</code>```

environment variable

```<code>java -jar -arg1=text1 -arg2=text2 myJAR.jar
</code>```

答:
Environment variables are key-value pairs passed to a program while it's invoked whereas properties file consists of list of properties along with their values. Generally, properties file is considered to be the best practice to maintain configuration values, here's why:

Properties file are more readable than environment variables. Also, they are not tied to startup script, we can pass any file while running the program.

Frameworks like Spring provide different ways to create a collection or map from properties file.

It's easy to use different properties files for different environments (e.g. stage, prod etc)

Title: Properties file vs environment variable

Body:
Hey i wondered what is the difference between .properties file to environment variable in java.

.Properties file

arg1=text1

arg2=text2

environment variable

java -jar -arg1=text1 -arg2=text2 myJAR.jar


问:
Memory leak synchronous reading interrupt transfer data via libUSB
I discovered a memory leak reading data via USB interrupt transfer using libUSB synchronously. My simple user program is not using any dynamic memory allocation itself. Internally libusb makes excessive use of dynamic memory allocation. The communication flow is working as expected. Is there a special function to free any internal dynamic memory after using libusb_interrupt_transfer? Does anyone have an idea what causes the continously increase of memory during runtime?

My protocol implements a two way handshake. Because of this a simple data exchange causes a OUT(request), IN(Ack/Nack), IN(Response) and OUT(Ack/Nack) transfer. The report size is 32 Bytes, the outEndpointAddr is 1, the inEndpointAddr is 129, Here are the relevant code snippets.

```<code>int main (void)
{
    uint32_t devFound = 0;
    uint32_t devErrors = 0;

    ...

    int libUsbErr = 0;
    if(!findSensor(&devFound, &devErrors, &libUsbErr, foundCB))
        printf("finding sensor failed %d\n", libUsbErr);

    if(!openSensor(mySensor, &libUsbErr))
        printf("open sensor failed %d\n", libUsbErr);

    int i = 0;
    while(1)
    {
        printf("[%06d] Int Temp %f C\n",i++, readIntTemper());
        Delay(0.5);
    }
    closeSensor(&mySensor, NULL);

    closeSensorContext();
    return 0;
}

float readIntTemper()
{
    static uint8_t tmp[32];
    static uint8_t response[32];

    ...//Prepare request frame

    int libUsbErr = 0;
    if(!HID_Write(mySensor, tmp, &written, 4000, &libUsbErr))
    {
        printf("write request failed %d\n", libUsbErr);
        return 0;
    }

    //Read Ack / Nack
    if(!HID_Read(mySensor, tmp, &read, 4000, &libUsbErr))
    {
        printf("Read ACK NACK failed %d\n", libUsbErr);
        return 0;
    }

    ...//Test if Ack / Nack

    if(!HID_Read(mySensor, response, &read, 4000, &libUsbErr))
    {
        printf("Read response failed %d\n", libUsbErr);
        return 0;
    }

    ... //Prepare ACK

    if(!HID_Write(mySensor, tmp, &written, 4000, &libUsbErr))
    {
        printf("Ack response failed %d\n", libUsbErr);
        return 0;
    }

    ...

    float* temper = (float*)&response[8];
    return *temper;
}

bool HID_Write(const Sensor* sens, uint8_t* repBuf, int* transferred, uint32_t timeout, int* libUsbErr)
{
    if(sens == NULL || repBuf == NULL || transferred == NULL)
        return returnlibUSBErr(libUsbErr, -1008); ///TODO nice error codes;

    if(!sens->claimed)
        return returnlibUSBErr(libUsbErr, -1012); ///TODO nice error codes;

    int r = libusb_interrupt_transfer(sens->devHandle, sens->outEndpointAddr,
                          repBuf, sens->outRepSize, transferred, timeout);
    if (r < 0)
        return returnlibUSBErr(libUsbErr, r);
    return returnlibUSBErr(libUsbErr, LIB_USB_OK);
}

bool HID_Read(const Sensor* sens, uint8_t* repBuf, int* read, uint32_t timeout, int* libUsbErr)
{
    if(sens == NULL || read == NULL)
        return returnlibUSBErr(libUsbErr, -1008); ///TODO nice error codes;

    if(!sens->claimed)
        return returnlibUSBErr(libUsbErr, -1012); ///TODO nice error codes;

    int r = libusb_interrupt_transfer(sens->devHandle, sens->inEndpointAddr, repBuf,sens->inRepSize, read, timeout);
    if (r < 0)
        return returnlibUSBErr(libUsbErr, r);
    return returnlibUSBErr(libUsbErr, LIB_USB_OK);
}
</code>```

EDIT

If followed this instruction to monitor memory usage:

https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-performance-monitor-to-find-a-user-mode-memory-leak

To find the leak I used UMDH Windows tool like mentioned here:

https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-umdh-to-find-a-user-mode-memory-leak

The problem is that I have to use CVI NI compilter to build my application. I wasn't able to get the symbol table out of this compilter. So my heap dump diff only shows addresses.

```<code>// Each log entry has the following syntax:
//
// + BYTES_DELTA (NEW_BYTES - OLD_BYTES) NEW_COUNT allocs BackTrace TRACEID
// + COUNT_DELTA (NEW_COUNT - OLD_COUNT) BackTrace TRACEID allocations
//     ... stack trace ...
//
// where:
//
//     BYTES_DELTA - increase in bytes between before and after log
//     NEW_BYTES - bytes in after log
//     OLD_BYTES - bytes in before log
//     COUNT_DELTA - increase in allocations between before and after log
//     NEW_COUNT - number of allocations in after log
//     OLD_COUNT - number of allocations in before log
//     TRACEID - decimal index of the stack trace in the trace database
//         (can be used to search for allocation instances in the original
//         UMDH logs).
//

+   80000 ( 80000 -     0)      1 allocs    BackTrace4920B3C
+       1 (     1 -     0)  BackTrace4920B3C    allocations

    ntdll!RtlAllocateHeap+274
    cvirte!LoadExternalModule+291EC
    cvirte!CVIDynamicMemoryInfo+12B6
    cvirte!CVIDynamicMemoryInfo+1528
    cvirte!CVIDynamicMemoryInfo+1AF9
    cvirte!mblen+84D
    cvirte!_CVI_Resource_Acquire+116
    cvirte!malloc+68
    libUSB_HID!???+0 : 41DCE8
    libUSB_HID!???+0 : 4E95C7
    libUSB_HID!???+0 : 4C13BE
    libUSB_HID!???+0 : 4BA09D
    libUSB_HID!???+0 : 4C7ABA
    libUSB_HID!???+0 : 4F92F0
    libUSB_HID!???+0 : 4FB3BD
    libUSB_HID!???+0 : 4FC50E
    libUSB_HID!???+0 : 415C31
    libUSB_HID!???+0 : 408847
    libUSB_HID!???+0 : 402967
    libUSB_HID!???+0 : 41B51E
    libUSB_HID!???+0 : 41A021
    kernel32!BaseThreadInitThunk+E
    ntdll!__RtlUserThreadStart+70
</code>```

I also replaced all free, alloc, calloc and realloc cmds within libUSB with my a own implementation tracking every single memory request. This tracking is not showing any memory leak. The amount of allocated bytes stays constant during runtime as expected. Anyway the UMDH tools shows a heap allocation difference. So I'm completely out of ideas what to test next atm.

答:
My simple user program is not using any dynamic memory allocation.

Unfortunately, those libusb_xxx_transfer functions do stuff with malloc() internally. But it is also suppsed to do the corresponding free() just before exiting to the caller.

That memory is not normally returned to the OS, but retained in the appliction to be used in the next malloc() calls. As a result you will see some memory use in task manager.

That is why you need better tools to detect actual memory leaks, like valgrind.

Body:
I discovered a memory leak reading data via USB interrupt transfer using libUSB synchronously. My simple user program is not using any dynamic memory allocation itself. Internally libusb makes excessive use of dynamic memory allocation. The communication flow is working as expected. Is there a special function to free any internal dynamic memory after using libusb_interrupt_transfer? Does anyone have an idea what causes the continously increase of memory during runtime?

My protocol implements a two way handshake. Because of this a simple data exchange causes a OUT(request), IN(Ack/Nack), IN(Response) and OUT(Ack/Nack) transfer. The report size is 32 Bytes, the outEndpointAddr is 1, the inEndpointAddr is 129, Here are the relevant code snippets.

int main (void)
{
    uint32_t devFound = 0;
    uint32_t devErrors = 0;

    ...

    int libUsbErr = 0;
    if(!findSensor(&devFound, &devErrors, &libUsbErr, foundCB))
        printf("finding sensor failed %d\n", libUsbErr);

    if(!openSensor(mySensor, &libUsbErr))
        printf("open sensor failed %d\n", libUsbErr);

    int i = 0;
    while(1)
    {
        printf("[%06d] Int Temp %f C\n",i++, readIntTemper());
        Delay(0.5);
    }
    closeSensor(&mySensor, NULL);

    closeSensorContext();
    return 0;
}

float readIntTemper()
{
    static uint8_t tmp[32];
    static uint8_t response[32];

    ...//Prepare request frame

    int libUsbErr = 0;
    if(!HID_Write(mySensor, tmp, &written, 4000, &libUsbErr))
    {
        printf("write request failed %d\n", libUsbErr);
        return 0;
    }

    //Read Ack / Nack
    if(!HID_Read(mySensor, tmp, &read, 4000, &libUsbErr))
    {
        printf("Read ACK NACK failed %d\n", libUsbErr);
        return 0;
    }

    ...//Test if Ack / Nack

    if(!HID_Read(mySensor, response, &read, 4000, &libUsbErr))
    {
        printf("Read response failed %d\n", libUsbErr);
        return 0;
    }

    ... //Prepare ACK

    if(!HID_Write(mySensor, tmp, &written, 4000, &libUsbErr))
    {
        printf("Ack response failed %d\n", libUsbErr);
        return 0;
    }

    ...

    float* temper = (float*)&response[8];
    return *temper;
}

bool HID_Write(const Sensor* sens, uint8_t* repBuf, int* transferred, uint32_t timeout, int* libUsbErr)
{
    if(sens == NULL || repBuf == NULL || transferred == NULL)
        return returnlibUSBErr(libUsbErr, -1008); ///TODO nice error codes;

    if(!sens->claimed)
        return returnlibUSBErr(libUsbErr, -1012); ///TODO nice error codes;

    int r = libusb_interrupt_transfer(sens->devHandle, sens->outEndpointAddr,
                          repBuf, sens->outRepSize, transferred, timeout);
    if (r < 0)
        return returnlibUSBErr(libUsbErr, r);
    return returnlibUSBErr(libUsbErr, LIB_USB_OK);
}

bool HID_Read(const Sensor* sens, uint8_t* repBuf, int* read, uint32_t timeout, int* libUsbErr)
{
    if(sens == NULL || read == NULL)
        return returnlibUSBErr(libUsbErr, -1008); ///TODO nice error codes;

    if(!sens->claimed)
        return returnlibUSBErr(libUsbErr, -1012); ///TODO nice error codes;

    int r = libusb_interrupt_transfer(sens->devHandle, sens->inEndpointAddr, repBuf,sens->inRepSize, read, timeout);
    if (r < 0)
        return returnlibUSBErr(libUsbErr, r);
    return returnlibUSBErr(libUsbErr, LIB_USB_OK);
}

EDIT

If followed this instruction to monitor memory usage:

https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-performance-monitor-to-find-a-user-mode-memory-leak

To find the leak I used UMDH Windows tool like mentioned here:

https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-umdh-to-find-a-user-mode-memory-leak

The problem is that I have to use CVI NI compilter to build my application. I wasn't able to get the symbol table out of this compilter. So my heap dump diff only shows addresses.

// Each log entry has the following syntax:
//
// + BYTES_DELTA (NEW_BYTES - OLD_BYTES) NEW_COUNT allocs BackTrace TRACEID
// + COUNT_DELTA (NEW_COUNT - OLD_COUNT) BackTrace TRACEID allocations
//     ... stack trace ...
//
// where:
//
//     BYTES_DELTA - increase in bytes between before and after log
//     NEW_BYTES - bytes in after log
//     OLD_BYTES - bytes in before log
//     COUNT_DELTA - increase in allocations between before and after log
//     NEW_COUNT - number of allocations in after log
//     OLD_COUNT - number of allocations in before log
//     TRACEID - decimal index of the stack trace in the trace database
//         (can be used to search for allocation instances in the original
//         UMDH logs).
//

+   80000 ( 80000 -     0)      1 allocs    BackTrace4920B3C
+       1 (     1 -     0)  BackTrace4920B3C    allocations

    ntdll!RtlAllocateHeap+274
    cvirte!LoadExternalModule+291EC
    cvirte!CVIDynamicMemoryInfo+12B6
    cvirte!CVIDynamicMemoryInfo+1528
    cvirte!CVIDynamicMemoryInfo+1AF9
    cvirte!mblen+84D
    cvirte!_CVI_Resource_Acquire+116
    cvirte!malloc+68
    libUSB_HID!???+0 : 41DCE8
    libUSB_HID!???+0 : 4E95C7
    libUSB_HID!???+0 : 4C13BE
    libUSB_HID!???+0 : 4BA09D
    libUSB_HID!???+0 : 4C7ABA
    libUSB_HID!???+0 : 4F92F0
    libUSB_HID!???+0 : 4FB3BD
    libUSB_HID!???+0 : 4FC50E
    libUSB_HID!???+0 : 415C31
    libUSB_HID!???+0 : 408847
    libUSB_HID!???+0 : 402967
    libUSB_HID!???+0 : 41B51E
    libUSB_HID!???+0 : 41A021
    kernel32!BaseThreadInitThunk+E
    ntdll!__RtlUserThreadStart+70

I also replaced all free, alloc, calloc and realloc cmds within libUSB with my a own implementation tracking every single memory request. This tracking is not showing any memory leak. The amount of allocated bytes stays constant during runtime as expected. Anyway the UMDH tools shows a heap allocation difference. So I'm completely out of ideas what to test next atm.


问:
How to use a specific version of a known DLL?
I distribute a Win32 Delphi application that uses ADVAPI32.DLL to call some encryption and decryption routines. It works great on modern versions of Windows, but a few customers use some very old versions of Windows, like Windows Vista and unpatched Windows 7. For those customers, the version of ADVAPI32.Dll is obsolete and sometimes causes decryption errors.
I know that advapi32.dll is a "known" system DLL, and as such it cannot be loaded locally (I mean, from my app folder instead of System32), so how can I solve this issue? I tried using a renamed local copy of the DLL but that didnt work either...</p>

答:
Even if you are able to load a different version of advapi32.dll, there is no guarantee that it will actually work on the target systems.

The advapi32.dll is only an interface dll that provides the "public API". Internally it delegates much functionality to the windows kernel, so if this interface changes or the kernel of the target system does not implement a function, your app will crash. You should think of advapi32.dllmore as an interface than an implementation - you call methods provided by it but it may do different things on different platforms that provide a version of the dll.

On Windows Nano Server the advapi32.dll is only a forwarding dll that delegates API calls to other DLLs ("OneCore" API).


问:
Struts Action class execute() method........mapping.findForward('null')
In my struts application i want to pass the null value to the mapping.findForward('null') the reason to do this is that i do not want to call any jsp page

More details

```<code>public ActionForward saveSurveyTakersDetails(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception
    {
     // something
     return mapping.findForward(null);
     }
</code>```

Is it is valid to pass null at findForward parameter.. Please answer
thanks

答:
It's no problem returning null in an action to prevent redirecting to a JSP page, but I would suggest leaving out the findForward() call and just return null outright:

```<code>public ActionForward saveSurveyTakersDetails(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
    // something
    return null;
}
</code>```

It will have the same result, but is a little easier understand at a glance.

Body:
In my struts application i want to pass the null value to the mapping.findForward('null') the reason to do this is that i do not want to call any jsp page

More details

public ActionForward saveSurveyTakersDetails(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception
    {
     // something
     return mapping.findForward(null);
     }

Is it is valid to pass null at findForward parameter.. Please answer
thanks

Body:
It's no problem returning null in an action to prevent redirecting to a JSP page, but I would suggest leaving out the findForward() call and just return null outright:

public ActionForward saveSurveyTakersDetails(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
    // something
    return null;
}

It will have the same result, but is a little easier understand at a glance.


问:
jquery how to fill select option in my form
enter image description here
The json (data) looks like this
guys! I have a little form. Like this:

```<code><form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
        <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
        </select>
<input type="submit" value="GO GO GO"/>
</form>
<script src="/add-information/aa.js"></script>
</code>```

In this little code i receive a json with data from my database:

```<code>        var data = JSON.parse(response);
        console.log(data);
</code>```

in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:

```<code>var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?
</code>```

help me please, how i can fill select with data from 'data'?

THE SOLUTION BY ADEON IS:

var data = JSON.parse(response);
        console.log(data);

```<code>    var select = document.getElementById('activity_2');

    for (var i = 0; i < data.data.length; i++) {
    select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
        }
</code>```

答:
You can use $.append in jquery to add new option into a select input.
Html:

```<code><select id="selinput" name="activity_2"> <option value="">Exmaple</option> </select>
</code>```

Jquery:

```<code>$("#selinput").append('<option value="1">value</option>');
</code>```

Or you can use jquery.selec2 plugin.

Body:
enter image description here
The json (data) looks like this
guys! I have a little form. Like this:

<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
        <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
        </select>
<input type="submit" value="GO GO GO"/>
</form>

In this little code i receive a json with data from my database:

        var data = JSON.parse(response);
        console.log(data);

in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:

var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?

help me please, how i can fill select with data from 'data'?

THE SOLUTION BY ADEON IS:

var data = JSON.parse(response);
        console.log(data);

    var select = document.getElementById('activity_2');

    for (var i = 0; i < data.data.length; i++) {
    select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
        }

Body:
You can use $.append in jquery to add new option into a select input.
Html:

<select id="selinput" name="activity_2"> <option value="">Exmaple</option> </select>

Jquery:

$("#selinput").append('<option value="1">value</option>');

Or you can use jquery.selec2 plugin.


问:
Faceting (autocomplete) out of memory
our solr crashes from time to time due to OutOfMemory error. We are stil on 4.0.0 version, but are planning to migrate to latest version after we solve following problem(s).

When I looked at tomcat log I see the following error:

```<code>SEVERE: null:java.lang.RuntimeException: java.lang.OutOfMemoryError: Java heap space
    at org.apache.solr.servlet.SolrDispatchFilter.sendError(SolrDispatchFilter.java:469)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:297)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.OutOfMemoryError: Java heap space
    at org.apache.lucene.search.FieldComparator$TermOrdValComparator.<init>(FieldComparator.java:1124)
    at org.apache.lucene.search.SortField.getComparator(SortField.java:425)
    at org.apache.lucene.search.FieldValueHitQueue$MultiComparatorsFieldValueHitQueue.<init>(FieldValueHitQueue.java:110)
    at org.apache.lucene.search.FieldValueHitQueue.create(FieldValueHitQueue.java:173)
    at org.apache.lucene.search.TopFieldCollector.create(TopFieldCollector.java:1123)
    at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:552)
    at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:507)
    at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:484)
    at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:309)
    at si.amebis.termania.solr.ExternalSearch.search(ExternalSearch.java:307)
    at si.amebis.termania.solr.ExternalSearch.handleRequestBody(ExternalSearch.java:235)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:129)
    at org.apache.solr.core.SolrCore.execute(SolrCore.java:1699)
    at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:455)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:276)
    ... 12 more
</code>```

just after the request for a autocomplete field (suggest as you type). Request details are below:

```<code>q - *:*
start - 0
rows - 0
fq - (Type:1 OR Type:2)
facet - true
facet.limit - 20
facet.mincount - 1
facet.sort - true
facet.prefix - "mi"
facet.field - "Autocomplete"
--
which returns 8105170 hits
</code>```

where Autocomplete field is defined as:

```<code><field name="Autocomplete" type="grams" indexed="true" stored="false" omitNorms="true" required="False" multiValued="true" />
    <fieldtype name="grams" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory" />
        <filter class="solr.ShingleFilterFactory" maxShingleSize="10" outputUnigrams="true" />
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.TrimFilterFactory" />
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory" />
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.TrimFilterFactory" />
      </analyzer>
    </fieldtype>
</code>```

Index details:

```<code>Num document: 4338603
Index size: 10.1 Gb
Ram: 64Gb (-Xmx45000M)
Terms count in Autocomplete field: 70.459.723
</code>```

I assume faceting on a text field and so many terms requires a lot of memory.

How can I calculate how much memory requires and is there any more efficient way to provide autocomplete (with phrases - n-grams)?

Thanks in advance!

答:
Can you connect connect to the Solr instance to check where is the memory going? I'm guessing that is on the FieldCache, but is always good to check to be sure, Solr's faceting treats each field separately, so you should be able to check the memory consumption for that particular field. To estimate the memory usage for a facet query you could check this thread (http://lucene.472066.n3.nabble.com/Solr-using-a-ridiculous-amount-of-memory-td4050840.html)

There is something also on your question you said that your query returns 8105170 hits, but your index has only 4338603 documents. Usually faceting on a text field is challenging because the number of terms could increase really fast, specially if you use shingles/ngrams.

Take a look at https://github.com/cominvent/autocomplete is a great starting point for an autocomplete feature backed by Solr (I've used this as my starting point for a few projects).

Depending on how have you implemented your autocomplete feature you could also try changing the facet.method (https://cwiki.apache.org/confluence/display/solr/Faceting
) parameter and check if it helps.

Also take a look at https://cwiki.apache.org/confluence/display/solr/Suggester.

Title: Faceting (autocomplete) out of memory

Body:
our solr crashes from time to time due to OutOfMemory error. We are stil on 4.0.0 version, but are planning to migrate to latest version after we solve following problem(s).

When I looked at tomcat log I see the following error:

SEVERE: null:java.lang.RuntimeException: java.lang.OutOfMemoryError: Java heap space
    at org.apache.solr.servlet.SolrDispatchFilter.sendError(SolrDispatchFilter.java:469)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:297)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.OutOfMemoryError: Java heap space
    at org.apache.lucene.search.FieldComparator$TermOrdValComparator.<init>(FieldComparator.java:1124)
    at org.apache.lucene.search.SortField.getComparator(SortField.java:425)
    at org.apache.lucene.search.FieldValueHitQueue$MultiComparatorsFieldValueHitQueue.<init>(FieldValueHitQueue.java:110)
    at org.apache.lucene.search.FieldValueHitQueue.create(FieldValueHitQueue.java:173)
    at org.apache.lucene.search.TopFieldCollector.create(TopFieldCollector.java:1123)
    at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:552)
    at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:507)
    at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:484)
    at org.apache.lucene.search.IndexSearcher.search(IndexSearcher.java:309)
    at si.amebis.termania.solr.ExternalSearch.search(ExternalSearch.java:307)
    at si.amebis.termania.solr.ExternalSearch.handleRequestBody(ExternalSearch.java:235)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:129)
    at org.apache.solr.core.SolrCore.execute(SolrCore.java:1699)
    at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:455)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:276)
    ... 12 more

just after the request for a autocomplete field (suggest as you type). Request details are below:

q - *:*
start - 0
rows - 0
fq - (Type:1 OR Type:2)
facet - true
facet.limit - 20
facet.mincount - 1
facet.sort - true
facet.prefix - "mi"
facet.field - "Autocomplete"
--
which returns 8105170 hits

where Autocomplete field is defined as:

<field name="Autocomplete" type="grams" indexed="true" stored="false" omitNorms="true" required="False" multiValued="true" />
    <fieldtype name="grams" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory" />
        <filter class="solr.ShingleFilterFactory" maxShingleSize="10" outputUnigrams="true" />
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.TrimFilterFactory" />
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory" />
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.TrimFilterFactory" />
      </analyzer>
    </fieldtype>

Index details:

Num document: 4338603
Index size: 10.1 Gb
Ram: 64Gb (-Xmx45000M)
Terms count in Autocomplete field: 70.459.723

I assume faceting on a text field and so many terms requires a lot of memory.

How can I calculate how much memory requires and is there any more efficient way to provide autocomplete (with phrases - n-grams)?

Thanks in advance!


问:
Roslyn (Lambda) Expression Bodied Property Syntax
I wrote a function to convert LocalDeclaration's to Global Resources.  Right now I'm replacing with each definition with a property, but I want to replace it with a property using the new syntax =>

```<code>    public PropertyDeclarationSyntax ConvertToResourceProperty(string resouceClassIdentifier, string fieldName, string resourceKey, CSharpSyntaxNode field)
    {
        var stringType = SyntaxFactory.ParseTypeName("string");

        var resourceReturnIdentifier = SyntaxFactory.IdentifierName(resouceClassIdentifier + "." + resourceKey);
        var returnResourceStatement = SyntaxFactory.ReturnStatement(resourceReturnIdentifier).NormalizeWhitespace();
        var getRescourceBlock = SyntaxFactory.Block(returnResourceStatement);

        var getAccessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getRescourceBlock).WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);

        var propertyDeclaration = SyntaxFactory.PropertyDeclaration(stringType, fieldName).AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword)).NormalizeWhitespace();

        propertyDeclaration = propertyDeclaration.AddAccessorListAccessors(getAccessor).WithAdditionalAnnotations(Formatter.Annotation);

        SyntaxTrivia[] leadingTrivia = field.GetLeadingTrivia().ToArray() ?? new[] { SyntaxFactory.Whitespace("\t") };
        return propertyDeclaration.WithTrailingTrivia(SyntaxFactory.Whitespace("\r\n"))
                    .WithLeadingTrivia(leadingTrivia)
                    .WithAdditionalAnnotations(Simplifier.Annotation);
    }
</code>```

This code create a property like so:

```<code>public static string LocalResourceName
{
    get{ return Resources.LocalResourceName; }
}
</code>```

I would like it to make the property like so:

```<code>public static string LocalResourceName =>Resources.LocalResourceName;
</code>```

I'm not too sure what will create an expression bodied property from the syntaxfactory? Can anyone point me to the right method?

答:
After scouring the internet I've found a way to do it. Why is there no documentation for roslyn?</p>

```<code>public PropertyDeclarationSyntax ConvertToResourceProperty(string resouceClassIdentifier, string fieldName, string resourceKey, CSharpSyntaxNode field)
{
    var stringType = SyntaxFactory.ParseTypeName("string");

    var resourceClassName = SyntaxFactory.IdentifierName(resouceClassIdentifier);
    var resourceKeyName = SyntaxFactory.IdentifierName(resourceKey);
    var memberaccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, resourceClassName, resourceKeyName);

    var propertyLambda = SyntaxFactory.ArrowExpressionClause(memberaccess);

    var propertyDeclaration = SyntaxFactory.PropertyDeclaration(new SyntaxList<AttributeListSyntax>(), new SyntaxTokenList(),
                                                                stringType, null, SyntaxFactory.Identifier(fieldName), null,
                                                                propertyLambda, null, SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                                                                        .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword),
                                                                    SyntaxFactory.Token(SyntaxKind.StaticKeyword)).WithAdditionalAnnotations(Formatter.Annotation).NormalizeWhitespace();

    return propertyDeclaration.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)
                .WithLeadingTrivia(field.GetLeadingTrivia().ToArray())
                .WithAdditionalAnnotations(Simplifier.Annotation);
}
</code>```

Body:
I wrote a function to convert LocalDeclaration's to Global Resources.  Right now I'm replacing with each definition with a property, but I want to replace it with a property using the new syntax =>

    public PropertyDeclarationSyntax ConvertToResourceProperty(string resouceClassIdentifier, string fieldName, string resourceKey, CSharpSyntaxNode field)
    {
        var stringType = SyntaxFactory.ParseTypeName("string");

        var resourceReturnIdentifier = SyntaxFactory.IdentifierName(resouceClassIdentifier + "." + resourceKey);
        var returnResourceStatement = SyntaxFactory.ReturnStatement(resourceReturnIdentifier).NormalizeWhitespace();
        var getRescourceBlock = SyntaxFactory.Block(returnResourceStatement);

        var getAccessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getRescourceBlock).WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);

        var propertyDeclaration = SyntaxFactory.PropertyDeclaration(stringType, fieldName).AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword)).NormalizeWhitespace();

        propertyDeclaration = propertyDeclaration.AddAccessorListAccessors(getAccessor).WithAdditionalAnnotations(Formatter.Annotation);

        SyntaxTrivia[] leadingTrivia = field.GetLeadingTrivia().ToArray() ?? new[] { SyntaxFactory.Whitespace("\t") };
        return propertyDeclaration.WithTrailingTrivia(SyntaxFactory.Whitespace("\r\n"))
                    .WithLeadingTrivia(leadingTrivia)
                    .WithAdditionalAnnotations(Simplifier.Annotation);
    }

This code create a property like so:

public static string LocalResourceName
{
    get{ return Resources.LocalResourceName; }
}

I would like it to make the property like so:

public static string LocalResourceName =>Resources.LocalResourceName;

I'm not too sure what will create an expression bodied property from the syntaxfactory? Can anyone point me to the right method?

Body:
After scouring the internet I've found a way to do it. Why is there no documentation for roslyn?

public PropertyDeclarationSyntax ConvertToResourceProperty(string resouceClassIdentifier, string fieldName, string resourceKey, CSharpSyntaxNode field)
{
    var stringType = SyntaxFactory.ParseTypeName("string");

    var resourceClassName = SyntaxFactory.IdentifierName(resouceClassIdentifier);
    var resourceKeyName = SyntaxFactory.IdentifierName(resourceKey);
    var memberaccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, resourceClassName, resourceKeyName);

    var propertyLambda = SyntaxFactory.ArrowExpressionClause(memberaccess);

    var propertyDeclaration = SyntaxFactory.PropertyDeclaration(new SyntaxList<AttributeListSyntax>(), new SyntaxTokenList(),
                                                                stringType, null, SyntaxFactory.Identifier(fieldName), null,
                                                                propertyLambda, null, SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                                                                        .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword),
                                                                    SyntaxFactory.Token(SyntaxKind.StaticKeyword)).WithAdditionalAnnotations(Formatter.Annotation).NormalizeWhitespace();

    return propertyDeclaration.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)
                .WithLeadingTrivia(field.GetLeadingTrivia().ToArray())
                .WithAdditionalAnnotations(Simplifier.Annotation);
}


问:
Ada why check if an objects length is not equal to itself. Ex if(variable'Length /= variable'length)
I am reviewing some ada code and I keep seeing the following code throughout the project.

```<code>if(variable'Length /= variable'length)
   return;
end if
</code>```

Codepeer flags this as always false which makes perfect sense to me, but I have very little ada experience. Is this valid, and if so under what circumstance would it be true?

Thanks.

答: Never.  You can only ask for the length of an array object, and once that object has been declared, it can't change.</p>

Body:
I am reviewing some ada code and I keep seeing the following code throughout the project.

if(variable'Length /= variable'length)
   return;
end if

Codepeer flags this as always false which makes perfect sense to me, but I have very little ada experience. Is this valid, and if so under what circumstance would it be true?

Thanks.


答: First and foremost, you are not legally allowed to redistribute advapi32.dll. Second, you cannot reliably run newer system DLLs on old systems, they come with dependencies and you need to provide the updated dependencies. Many system DLLs have special protection mechanisms preventing from loading an incorrect one as part of elementary DLL hijacking prevention security mechanisms. And finally, CryptDecrypt and friends, as well as other similar functions are working perfectly fine in Vista and Windows 7. If you encounter issues, is either a bug in your code, or you are simply not respecting the stated restrictions of Crypto API for said platforms. So better post the code you use, and the error you get on those older systems.

Title: How to use a specific version of a known DLL?

Body:
I distribute a Win32 Delphi application that uses ADVAPI32.DLL to call some encryption and decryption routines. It works great on modern versions of Windows, but a few customers use some very old versions of Windows, like Windows Vista and unpatched Windows 7. For those customers, the version of ADVAPI32.Dll is obsolete and sometimes causes decryption errors.
I know that advapi32.dll is a "known" system DLL, and as such it cannot be loaded locally (I mean, from my app folder instead of System32), so how can I solve this issue? I tried using a renamed local copy of the DLL but that didnt work either...


问:
Is it safe to use http inside service fabric cluster for service to service commiunication?
I created a secure service fabric and have full control. Only services developed by me will be deployed and all public facing apis are using https. The question is for communication between service to service in cluster, is it safe to use http instead of https?

Thanks,

答:
I recommend using service fabric remoting (instead of http). This can be secured using certificates, with little effort.

More info here: https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reliable-services-secure-communication


问:
how i convert a bool to a Unityengine.Cursorlockmode
I have a small script to hide and put a cursor visible and I miss an error that specifically is this

error CS0029: Cannot implicitly convert type bool' toUnityEngine.CursorLockMode'

and this is the code

```<code>    using UnityEngine;
using System.Collections;

public class yea : MonoBehaviour {
    bool isLocked;
    void Start () {
        SetCursorLock(true);
    }

    void SetCursorLock(bool isLocked)
    {
        this.isLocked = isLocked;
        Cursor.lockState = isLocked;
        Cursor.visible = !isLocked;
    }

    void Update () {
        if (Input.GetKeyDown(KeyCode.I))
        {
            SetCursorLock(!isLocked);
        }

        if (Input.GetKeyDown(KeyCode.H))
        {
            SetCursorLock(isLocked);
        }
    }
}
</code>```

答:
Cursor.lockState  is an enum (CursorLockMode) so you can't assign bool to it.

```<code>void SetCursorLock(bool isLocked)
{
    this.isLocked = isLocked;
    if(this.isLocked)
    {
        Cursor.lockState = CursorLockMode.Locked;
    }else
    {
        Cursor.lockState = CursorLockMode.None;
    }
    Cursor.visible = !isLocked;
}
</code>```

Body:
I have a small script to hide and put a cursor visible and I miss an error that specifically is this

error CS0029: Cannot implicitly convert type bool' toUnityEngine.CursorLockMode'

and this is the code

    using UnityEngine;
using System.Collections;

public class yea : MonoBehaviour {
    bool isLocked;
    void Start () {
        SetCursorLock(true);
    }

    void SetCursorLock(bool isLocked)
    {
        this.isLocked = isLocked;
        Cursor.lockState = isLocked;
        Cursor.visible = !isLocked;
    }

    void Update () {
        if (Input.GetKeyDown(KeyCode.I))
        {
            SetCursorLock(!isLocked);
        }

        if (Input.GetKeyDown(KeyCode.H))
        {
            SetCursorLock(isLocked);
        }
    }
}

Body:
Cursor.lockState  is an enum (CursorLockMode) so you can't assign bool to it.

void SetCursorLock(bool isLocked)
{
    this.isLocked = isLocked;
    if(this.isLocked)
    {
        Cursor.lockState = CursorLockMode.Locked;
    }else
    {
        Cursor.lockState = CursorLockMode.None;
    }
    Cursor.visible = !isLocked;
}


问:
How to convert UTC date to local date object?
I dont know why, but I have tried all the solutions available around the internet but still couldnt succeed. Event MomentJs couldnt help.
So, I have a date string, "2017-06-05T15:00:00Z", it is coming from rest api.
I even tried with moment js but doenst help.
Note I want date object to be returned as the library expects date object not local string.
So, far I tried:

```<code>var d = new Date('2017-06-05T15:00:00Z')
console.log(d.getHours())
</code>```

The above code prints 17 rather than 15! So, what is it I am doing wrong? As the library also while doing its own thing gets 1700 hours as in calendar it shows 1700 hrs rather than 1500 hrs.

答:
```<code>'2017-06-05T15:00:00Z'
</code>```

The Z means Zulu (UTC +0:00). So this timestring specifies that it is no local but rather a global time. The Date Object is local, so:

```<code>new Date('2017-06-05T15:00:00Z');
</code>```

Gives back the local Date, when it was 15 a clock at Zulu. So youre currently at the timezone UTC+2:00.

So all you need to get the timestring to become local is to remove the "Z":

```<code>new Date('2017-06-05T15:00:00Z'.replace("Z",""));
</code>```

or you remove the timezone offset, see other answer...

Body:
I dont know why, but I have tried all the solutions available around the internet but still couldnt succeed. Event MomentJs couldnt help.
So, I have a date string, "2017-06-05T15:00:00Z", it is coming from rest api.
I even tried with moment js but doenst help.
Note I want date object to be returned as the library expects date object not local string.
So, far I tried:

var d = new Date('2017-06-05T15:00:00Z')
console.log(d.getHours())

The above code prints 17 rather than 15! So, what is it I am doing wrong? As the library also while doing its own thing gets 1700 hours as in calendar it shows 1700 hrs rather than 1500 hrs.

Body:
'2017-06-05T15:00:00Z'

The Z means Zulu (UTC +0:00). So this timestring specifies that it is no local but rather a global time. The Date Object is local, so:

new Date('2017-06-05T15:00:00Z');

Gives back the local Date, when it was 15 a clock at Zulu. So youre currently at the timezone UTC+2:00.

So all you need to get the timestring to become local is to remove the "Z":

new Date('2017-06-05T15:00:00Z'.replace("Z",""));

or you remove the timezone offset, see other answer...


问:
Running Read heavy queries on Percona XtraDB cluster
I am creating a new 3 node Percona XtraDB cluster from scratch for a brand new application. Part of the application will generate read heavy queries which we intend to loadbalance across the cluster. Previously in a Master slave setup those read queries used to generate replication lag which effected our application. Since we needed to fetch reads with not more than 3 seconds latency.

Now with Galera cluster it looks as if that problem is solved as replication is managed differently.

My question is, would those read heavy queries would cause galera cluster to cause some problems ?. More importantly would these queries slow down write performance of the cluster ?

Any experience in this area would be helpful.

答:
Yes and no.

Galera-based solutions (such as PXC) do have different characteristics.  It depends read vs write, distance between nodes, length of transactions, etc, etc.  Also, Galera has a way to deal with "critical reads" (wsrep_sync_wait) that Master-Slave did not have.

In any kind of system, you should study read-heavy queries to look for better indexes and/or better query formulation; this will improve any system.  Would you care to start another question to tackle such?


问:
Converting pdf file to bitmap images
I am working with pdf files, I want to implement page viewer to my pdf file. My idea is to convert pdf file into bmp images, and then to use viewPager. but I am stuck in converting pdf to bitmap. Any suggestions?</p>

答:
Include dependencies in your gradle

```<code>compile 'com.github.barteksc:android-pdf-viewer:2.8.1'
</code>```

Use following function to convert PDF page to bitmap image

```<code>private  Bitmap generateImageFromPdf(String assetFileName, int pageNumber, int width, int height) {

    PdfiumCore pdfiumCore = new PdfiumCore(mActivity);
    try {
        File f = FileUtils.fileFromAsset(mActivity, assetFileName);
        ParcelFileDescriptor fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
        PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
        pdfiumCore.openPage(pdfDocument, pageNumber);
        //int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNumber);
        //int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNumber);
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        pdfiumCore.renderPageBitmap(pdfDocument, bmp, pageNumber, 0, 0, width, height);
        //saveImage(bmp, filena);
        pdfiumCore.closeDocument(pdfDocument);

        return bmp;
    } catch(Exception e) {
        //todo with exception
    }
    return null;
}
</code>```

Title: Converting pdf file to bitmap images

Body:
Include dependencies in your gradle

compile 'com.github.barteksc:android-pdf-viewer:2.8.1'

Use following function to convert PDF page to bitmap image

private  Bitmap generateImageFromPdf(String assetFileName, int pageNumber, int width, int height) {

    PdfiumCore pdfiumCore = new PdfiumCore(mActivity);
    try {
        File f = FileUtils.fileFromAsset(mActivity, assetFileName);
        ParcelFileDescriptor fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
        PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
        pdfiumCore.openPage(pdfDocument, pageNumber);
        //int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNumber);
        //int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNumber);
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        pdfiumCore.renderPageBitmap(pdfDocument, bmp, pageNumber, 0, 0, width, height);
        //saveImage(bmp, filena);
        pdfiumCore.closeDocument(pdfDocument);

        return bmp;
    } catch(Exception e) {
        //todo with exception
    }
    return null;
}


问:
Why does my code fail on this SIMPLE exercise?
I am doing a coding exercise:

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example

For sequence = [1, 3, 2, 1], the output should be
false;

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2], the output should be
true;

You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

.

So I wrote this code:

```<code>def almostIncreasingSequence(sequence):
    first_list, second_list = [x for x in sequence], [x for x in sequence]
    for i in range(len(sequence)-1):
        if sequence[i] >= sequence[i+1]:
            first_list.remove(sequence[i])
            second_list.remove(sequence[i+1])
            break

    if first_list == sorted(set(first_list)) or second_list == sorted(set(second_list)):
        return True
    else:
        return False
</code>```

The code passes 13/15 tests.

Below are the 2 inputs that my code fails on:

```<code>[1, 2, 3, 4, 3, 6]

[3, 5, 67, 98, 3]
</code>```

Both inputs should return True but my code returns False. Any thoughts?

答:
Read about list.remove:

Remove the first item from the list whose value is x. It is an error if there is no such item.

```<code>>>> l = [1, 2, 3, 4, 3, 6]
>>> l.remove(3)
>>> print(l)
[1, 2, 4, 3, 6]
</code>```

Instead of remove(value), use pop(index):

```<code>first_list.pop(i)
second_list.pop(i+1)
</code>```

Body:
I am doing a coding exercise:

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example

For sequence = [1, 3, 2, 1], the output should be
false;

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2], the output should be
true;

You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

.

So I wrote this code:

def almostIncreasingSequence(sequence):
    first_list, second_list = [x for x in sequence], [x for x in sequence]
    for i in range(len(sequence)-1):
        if sequence[i] >= sequence[i+1]:
            first_list.remove(sequence[i])
            second_list.remove(sequence[i+1])
            break

    if first_list == sorted(set(first_list)) or second_list == sorted(set(second_list)):
        return True
    else:
        return False

The code passes 13/15 tests.

Below are the 2 inputs that my code fails on:

[1, 2, 3, 4, 3, 6]

[3, 5, 67, 98, 3]

Both inputs should return True but my code returns False. Any thoughts?

Body:
Read about list.remove:

Remove the first item from the list whose value is x. It is an error if there is no such item.

>>> l = [1, 2, 3, 4, 3, 6]
>>> l.remove(3)
>>> print(l)
[1, 2, 4, 3, 6]

Instead of remove(value), use pop(index):

first_list.pop(i)
second_list.pop(i+1)


答: Simply returning null (as opposed to finding a forward of "null") from the saveSurveyTakersDetails method should accomplish what you are attempting.</p>

Title: Struts Action class execute() method........mapping.findForward('null')


问:
Mac OSX Sierra Play 2.5 Https Localhost - This site can’t provide a secure connection
I am not able to run Java Play 2.5 application locally.I am using Mac OSX Sierra, before I was using Windows 10 and had no problems. If I try to use application through https://localhost:9000 I always receive error in chrome:

his site can’t provide a secure connection

On Mozilla:

An error occurred during a connection to localhost:9000. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG

Safari:

safari cant open the page because Safari cant establish secure connection to the server.

I am sure there is an issue with autogenerated self signed certificated by Play but I do not know how to solve it...

I tried http and it works, but my application forces https.

答:
Use http://localhost:9000

I doubt you are set up to use HTTPS locally


问:
Finding similar strings (same words in different order) in a list
I have a list of strings:

```<code> listA = [u'hour block', u'block hour', u'package hour', u'hour block hour']
</code>```

I want to find all strings that are similar (i.e., from the above example 'hour block' and 'block hour') and include only the string that occurred first from the two (i.e., 'hour block' in this case), and the remaining strings occur in their order.

So, the output of the above should be:

```<code>[u'hour block', u'package hour', u'hour block hour']
</code>```

I'm thinking in the following terms:

```<code>>>> for x in listA:
...     y = x.split()
</code>```

But, I can't figure out how do I compare each word of the strings in the list optimally?

答:
You can use set or frozenset for making unique items.  Try following

```<code>listA = [u'hour block', u'block hour', u'package hour', u'hour block hour']

sets = set()
unique = []

for item in listA:
    splitted = item.split()

    # Storing set of items(unique) and its count for comparision.
    # hour block and hour block hour gives same set, so length is required
    s = frozenset( { frozenset(item.split()), len(item.split()) } )
    if s not in sets:
        unique.append(item)
    sets.add(s)

print(unique)
</code>```

Output ['hour block', 'package hour', 'hour block hour']

Body:
I have a list of strings:

 listA = [u'hour block', u'block hour', u'package hour', u'hour block hour']

I want to find all strings that are similar (i.e., from the above example 'hour block' and 'block hour') and include only the string that occurred first from the two (i.e., 'hour block' in this case), and the remaining strings occur in their order.

So, the output of the above should be:

[u'hour block', u'package hour', u'hour block hour']

I'm thinking in the following terms:

>>> for x in listA:
...     y = x.split()

But, I can't figure out how do I compare each word of the strings in the list optimally?

Body:
You can use set or frozenset for making unique items.  Try following

listA = [u'hour block', u'block hour', u'package hour', u'hour block hour']

sets = set()
unique = []

for item in listA:
    splitted = item.split()

    # Storing set of items(unique) and its count for comparision.
    # hour block and hour block hour gives same set, so length is required
    s = frozenset( { frozenset(item.split()), len(item.split()) } )
    if s not in sets:
        unique.append(item)
    sets.add(s)

print(unique)

Output ['hour block', 'package hour', 'hour block hour']


问:
You may need an appropriate loader to handle this file type. Typescript
I'm trying to make use of Typescript typings for you Youtube Data API here: https://github.com/Bolisov/typings-gapi/tree/master/gapi.client.youtube-v3

I am using Ionic framework and I receive the error below after I do Ionic Serve with the following line in code:

```<code>  gapi.client.load("client", "v3");

Module parse failed: /Users/yoko/Desktop/myApp/node_modules/gapi/lib/gapi.coffee Unexpected token (1:17)
You may need an appropriate loader to handle this file type.
| config = require './config'
|
| module.exports =
</code>```

This is how the api.coffee looks like

```<code>config = require './config'

module.exports =
  server:
    setApiKey: (apiKey) ->
      config.api.key = apiKey
    load: (apiName, apiVersion, callback) ->
      @[apiName] = require "./#{apiName}/#{apiVersion}"
      callback()
</code>```

What does that mean?

答:
Assuming you are using Gulp, install CoffeeScript via npm, then add it to your package.json via:

```<code>npm install gulp-coffee --save-dev #devDependencies
</code>```

or

```<code>npm install gulp-coffee --save #dependencies
</code>```

Then add the following to your Gulpfile.js:

```<code>var coffee = require('gulp-coffee');
var paths =  { coffee: ['/Users/yoko/Desktop/myApp/node_modules/gapi/lib/*.coffee'] };

function coffeePipe(done)
  {
  gulp.src(paths.coffee)
    .pipe(coffee({bare: true})
    .on('error', gutil.log.bind(gutil, 'Coffee Error')))
    .pipe(concat('application.js'))
    .pipe(gulp.dest('./www/js'))
    .on('end', done)
  }

gulp.task('coffee', coffeePipe);
</code>```

References

CoffeeScript-Ionic-Starter/gulpfile.js at master · StephenGrider/CoffeeScript-Ionic-Starter

Introduction to Gulp.js with practical examples | Julien Renaux Blog

gulp-coffee

05 - Using a package.json | npm Documentation

Quick tip: using gulp to customize the 'serve', 'run' and 'build' process for your Ionic framework apps by leob on CodePen

Alter The Ionic 2 Gulp Script To Include Browser JavaScript Files

10 Minutes with Ionic 2: Hello World | The Official Ionic Blog

Why You Should Not Use Ionic Serve For Hybrid Apps

Body:
I'm trying to make use of Typescript typings for you Youtube Data API here: https://github.com/Bolisov/typings-gapi/tree/master/gapi.client.youtube-v3

I am using Ionic framework and I receive the error below after I do Ionic Serve with the following line in code:

  gapi.client.load("client", "v3");

Module parse failed: /Users/yoko/Desktop/myApp/node_modules/gapi/lib/gapi.coffee Unexpected token (1:17)
You may need an appropriate loader to handle this file type.
| config = require './config'
|
| module.exports =

This is how the api.coffee looks like

config = require './config'

module.exports =
  server:
    setApiKey: (apiKey) ->
      config.api.key = apiKey
    load: (apiName, apiVersion, callback) ->
      @[apiName] = require "./#{apiName}/#{apiVersion}"
      callback()

What does that mean?

Body:
Assuming you are using Gulp, install CoffeeScript via npm, then add it to your package.json via:

npm install gulp-coffee --save-dev #devDependencies

or

npm install gulp-coffee --save #dependencies

Then add the following to your Gulpfile.js:

var coffee = require('gulp-coffee');
var paths =  { coffee: ['/Users/yoko/Desktop/myApp/node_modules/gapi/lib/*.coffee'] };

function coffeePipe(done)
  {
  gulp.src(paths.coffee)
    .pipe(coffee({bare: true})
    .on('error', gutil.log.bind(gutil, 'Coffee Error')))
    .pipe(concat('application.js'))
    .pipe(gulp.dest('./www/js'))
    .on('end', done)
  }

gulp.task('coffee', coffeePipe);

References

CoffeeScript-Ionic-Starter/gulpfile.js at master · StephenGrider/CoffeeScript-Ionic-Starter

Introduction to Gulp.js with practical examples | Julien Renaux Blog

gulp-coffee

05 - Using a package.json | npm Documentation

Quick tip: using gulp to customize the 'serve', 'run' and 'build' process for your Ionic framework apps by leob on CodePen

Alter The Ionic 2 Gulp Script To Include Browser JavaScript Files

10 Minutes with Ionic 2: Hello World | The Official Ionic Blog

Why You Should Not Use Ionic Serve For Hybrid Apps


问:
How to use background-image: with php
How can I use background-image: url() in conjunction with php in order to obtain the directory of the image I would like to display.

CSS

```<code>.imageGallery {
width: 960px;
position: relative;
background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png');
}
</code>```

Currently, this css does not work. No background image is displayed.

HTML

```<code><div class="imageGallery">
</div>
</code>```

For example:

this works fine

```<code><img src='<?php bloginfo("template_directory");?>/images/home.png' class="headImage" />
</code>```

but this doesn't

```<code>    background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png');
</code>```

答:
You can try this two options bellow

CSS

```<code>.imageGallery {
width: 960px;
position: relative;
background-image: url('images/visitus.png');
}
</code>```

HTML with inline CSS

```<code><div class="imageGallery" style="background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png')">
</div>
</code>```

If you use the second option, you need to remove background image url from your css rule for that element. Hope it helps

Title: How to use background-image: with php

Body:
How can I use background-image: url() in conjunction with php in order to obtain the directory of the image I would like to display.

CSS

.imageGallery {
width: 960px;
position: relative;
background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png');
}

Currently, this css does not work. No background image is displayed.

HTML

For example:

this works fine

<img src='<?php bloginfo("template_directory");?>/images/home.png' class="headImage" />

but this doesn't

    background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png');

Body:
You can try this two options bellow

CSS

.imageGallery {
width: 960px;
position: relative;
background-image: url('images/visitus.png');
}

HTML with inline CSS

<div class="imageGallery" style="background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png')">
</div>

If you use the second option, you need to remove background image url from your css rule for that element. Hope it helps