问:
implementation for java substring with negative values
in java,

```<code>String month= "November 2014";
</code>```

for making a substring giving the index from right hand side, I cannot use

```<code>someString.substring(-4);
</code>```

as negative values are not supported.

Is there any simple implementation I can use to achieve this.

答:
I love Python's indexing and prefer to be able to use it in Java as well ;)

A general implementation of substring with support for negative indexing could be implemented like this:

A method for converting negative indexes to their positive equivalent is useful:

```<code>private static int toPosIndex(String str, int index) {
    if (index >= 0) return index;
    else return str.length() + index;
</code>```

This method can then be used to declare a substring method with support for negative indexes:

```<code>public static String negSubstring(String str, int index1, int index2) {
    return str.substring(toPosIndex(str, index1), toPosIndex(str, index2));
}
</code>```

and if needed an equivalent to the version of substring with only one index parameter:

```<code>public static String negSubstring(String str, int index) {
    return str.substring(toPosIndex(str, index));
}
</code>```

(I realise the question is more than two years old, but figured that other new users might be interested in a general answer to the question).

Body:
in java,

String month= "November 2014";

for making a substring giving the index from right hand side, I cannot use

someString.substring(-4);

as negative values are not supported.

Is there any simple implementation I can use to achieve this.

Body:
I love Python's indexing and prefer to be able to use it in Java as well ;)

A general implementation of substring with support for negative indexing could be implemented like this:

A method for converting negative indexes to their positive equivalent is useful:

private static int toPosIndex(String str, int index) {
    if (index >= 0) return index;
    else return str.length() + index;

This method can then be used to declare a substring method with support for negative indexes:

public static String negSubstring(String str, int index1, int index2) {
    return str.substring(toPosIndex(str, index1), toPosIndex(str, index2));
}

and if needed an equivalent to the version of substring with only one index parameter:

public static String negSubstring(String str, int index) {
    return str.substring(toPosIndex(str, index));
}

(I realise the question is more than two years old, but figured that other new users might be interested in a general answer to the question).


来源: stackexchange

问:
Destroy not destroying GameObject
I have the following code in Unity3D for adding and deleting a line segment for a 3D drawing:

```<code>public class LinearPiecewiseTrajectory : MonoBehaviuor
{
    private List<LineSegment> lineSegmentRep;

    //other stuff here

    public void addSegment()
    {
        GameObject lineSegmentObject = new GameObject();
        lineSegmentObject.name = "LineSegment";

        LineSegment lineSegment = lineSegmentObject.AddComponent<LineSegment>();

        lineSegmentObject.transform.parent = this.transform;
        lineSegmentRep.Add(lineSegment);
    }
}

public void deleteSegment(int i)
{
    Destroy(lineSegmentRep[i]);
}
</code>```

LineSegment is a MonoBehavior I have defined.

However, this destroy call isn't actually destroying the LineSegment object.  The only discernible behavior I can find is that it's setting the old LineSegment's geometric transform back to identity.

What am I missing?

答:
it is destroying the component of type LineSegment.

You need to tell to destroy the game object.

```<code>Destroy(lineSegmentRep[i].gameObject);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Destroy not destroying GameObject

Body:
I have the following code in Unity3D for adding and deleting a line segment for a 3D drawing:

public class LinearPiecewiseTrajectory : MonoBehaviuor
{
    private List<LineSegment> lineSegmentRep;

    //other stuff here

    public void addSegment()
    {
        GameObject lineSegmentObject = new GameObject();
        lineSegmentObject.name = "LineSegment";

        LineSegment lineSegment = lineSegmentObject.AddComponent<LineSegment>();

        lineSegmentObject.transform.parent = this.transform;
        lineSegmentRep.Add(lineSegment);
    }
}

public void deleteSegment(int i)
{
    Destroy(lineSegmentRep[i]);
}

LineSegment is a MonoBehavior I have defined.

However, this destroy call isn't actually destroying the LineSegment object.  The only discernible behavior I can find is that it's setting the old LineSegment's geometric transform back to identity.

What am I missing?

Body:
it is destroying the component of type LineSegment.

You need to tell to destroy the game object.

Destroy(lineSegmentRep[i].gameObject);


问:
Actual numbers to the human readable values
I have data in bytes. I need to draw this values as human readable labels on a chart (like 2.5KB, 14MB etc.) and need to help with function (input data - actual value, output - human readable string).

I did funcion like this, but I want more elegant realization

```<code>function tickFormatter(value, type) {

    var suffix = (type == "bytes") ? ['B', 'KB', 'MB', 'GB'] : ['', 'K', 'M', 'G']

    if(value > (1024 * 1024 * 1024 * 1024)) {
        return (value / (1024 * 1024 * 1024 * 1024)).toFixed(2) + suffix[3]
    } else if(value > (1024 * 1024 * 1024)) {
        return (value / (1024 * 1024 * 1024)).toFixed(2) + suffix[2]
    } else if (value > (1024 * 1024)) {
        return (value / (1024 * 1024)).toFixed(2) + suffix[1]
    } else {
        return value.toFixed(2) + suffix[0]
    }
}
</code>```

答:
Perhaps something like this?

```<code>function readable (nb_bytes) {
    if (nb_bytes < 1024) return nb_bytes + 'B';
    else if (nb_bytes < 1024 * 1024) return (Math.round((nb_bytes / 1024) * 100) / 100) + 'KB';
    else return (Math.round((nb_bytes / 1024 / 1024) * 100) / 100) + 'MB';
}
</code>```

[EDIT]

Alright, since you want something more elegant, I assume you're thinking of a loop. Maybe this will suit your needs:

```<code>function readable (nb_bytes,type) {
    var suffix = type ? ['B','KB','MB','GB'] : ['','K','M','G'];
    var i = 0;
    while (nb_bytes > 1024 && i < suffix.length - 1) {
        ++i;
        nb_bytes = Math.round((nb_bytes / 1024) * 100) / 100;
    }
    return (nb_bytes) + suffix[i];
}
</code>```

Here I assumed type was a boolean - change to whatever suits you best.

ContentLicense: CC BY-SA 2.5

Body:
I have data in bytes. I need to draw this values as human readable labels on a chart (like 2.5KB, 14MB etc.) and need to help with function (input data - actual value, output - human readable string).

I did funcion like this, but I want more elegant realization

function tickFormatter(value, type) {

    var suffix = (type == "bytes") ? ['B', 'KB', 'MB', 'GB'] : ['', 'K', 'M', 'G']

    if(value > (1024 * 1024 * 1024 * 1024)) {
        return (value / (1024 * 1024 * 1024 * 1024)).toFixed(2) + suffix[3]
    } else if(value > (1024 * 1024 * 1024)) {
        return (value / (1024 * 1024 * 1024)).toFixed(2) + suffix[2]
    } else if (value > (1024 * 1024)) {
        return (value / (1024 * 1024)).toFixed(2) + suffix[1]
    } else {
        return value.toFixed(2) + suffix[0]
    }
}

Body:
Perhaps something like this?

function readable (nb_bytes) {
    if (nb_bytes < 1024) return nb_bytes + 'B';
    else if (nb_bytes < 1024 * 1024) return (Math.round((nb_bytes / 1024) * 100) / 100) + 'KB';
    else return (Math.round((nb_bytes / 1024 / 1024) * 100) / 100) + 'MB';
}

[EDIT]

Alright, since you want something more elegant, I assume you're thinking of a loop. Maybe this will suit your needs:

function readable (nb_bytes,type) {
    var suffix = type ? ['B','KB','MB','GB'] : ['','K','M','G'];
    var i = 0;
    while (nb_bytes > 1024 && i < suffix.length - 1) {
        ++i;
        nb_bytes = Math.round((nb_bytes / 1024) * 100) / 100;
    }
    return (nb_bytes) + suffix[i];
}

Here I assumed type was a boolean - change to whatever suits you best.


问:
Repo owner automatic notification after updating a pull request
I've created a pull request on GitHub, been asked for changes by the repo owner, committed the changes and pushed them to the same branch.

Now I can see the updates in the pull request but I'm not sure if the repo owner have received any kind of automatic notification (e.g. email) about the update in the pull request. Should I trigger such a notification manually by adding a comment? something else?

Reading this, this and this doesn't answer the question either.

答:
Since July 2016, your Pull Request not only will notify the repo owner, but also the code owners!

See "Introducing code owners":

While effective code review is essential to every successful project, it's not always clear who should review files—even with GitHub's reviewer suggestions.

  Now repository maintainers can define exactly which people and teams need to review projects using code owners.

  This new feature automatically requests reviews from the code owners when a pull request changes any owned files.

How code owners work

To specify code owners, create a file named CODEOWNERS in the repository's root directory (or in .github/ if you prefer) with the following format:

```<code># Lines starting with '#' are comments.
# Each line is a file pattern followed by one or more owners.

# These owners will be the default owners for everything in the repo.
*       @defunkt

# Order is important. The last matching pattern has the most precedence.
# So if a pull request only touches javascript files, only these owners
# will be requested to review.
*.js    @octocat @github/js

# You can also use email addresses if you prefer.
docs/*  docs@example.com
</code>```

This format may be familiar if you've used .gitattributes.

With that in place, code owners will automatically be requested for review whenever a pull request touches the files they own.

Body:
Since July 2016, your Pull Request not only will notify the repo owner, but also the code owners!

See "Introducing code owners":

While effective code review is essential to every successful project, it's not always clear who should review files—even with GitHub's reviewer suggestions.

  Now repository maintainers can define exactly which people and teams need to review projects using code owners.

  This new feature automatically requests reviews from the code owners when a pull request changes any owned files.

How code owners work

To specify code owners, create a file named CODEOWNERS in the repository's root directory (or in .github/ if you prefer) with the following format:

# Lines starting with '#' are comments.
# Each line is a file pattern followed by one or more owners.

# These owners will be the default owners for everything in the repo.
*       @defunkt

# Order is important. The last matching pattern has the most precedence.
# So if a pull request only touches javascript files, only these owners
# will be requested to review.
*.js    @octocat @github/js

# You can also use email addresses if you prefer.
docs/*  docs@example.com

This format may be familiar if you've used .gitattributes.

With that in place, code owners will automatically be requested for review whenever a pull request touches the files they own.


问:
Clear input if it's not an email address using Javascript or jquery
My client uses wordpress, the template he's using generates a dynamic form, so I don't know where the html is stored. Therefore I can't use email attribute in html, nor I can validate emails using php since I don't have a clue how his theme validates the form.

The form builder generates a text input called cp_email_address I want to check if the user entered a valid email, otherwise I want to clear the field, I don't have any other option, since I can't wait for the user to submit and then validate, I don't know where the submit code is. All I know is the name, class and id of the email field.

```<code><script type="text/javascript">
    $('#cp_email_address').blur(function() {
    var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    if (testEmail.test(this.value)) {}; // if true pass
    else {
        this.value="";
    };
});
</script>
</code>```

I also tried target.value= "";

And tried $('#cp_email_address').value = "";

And I tried document.getElementById('cp_email_address').value = "";

Nothing is clearing the the input field.

答:
As a seasoned WordPress expert, I could say the following:

WordPress generally doesn't allow you to use $ for jQuery. Try using jQuery instead.

Secondly, you haven't put inside the document's ready event, which is more important.

Ultimately, what I suggest you to do is, combine the both and try:

(function($) {
  $(function() {
    $('#cp_email_address').blur(function() {
      var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
      if (testEmail.test(this.value)) {}; // if true pass
      else {
        this.value = "";
      };
    });
  });
})(jQuery)
```

<p>What I had done above is, I created an IIFE, which takes in its first parameter as <code>jQuery</code> so, this gets associated with <code>$</code> inside the function. So this should 90% work, if you don't get any errors.</p>

<p>Try to add this function in the <code>footer.php</code> or somewhere, which definitely gets called.</p>

<p><strong>Update:</strong> Well, I know this already, but just wanted to be sure. Anyway, as adeneo pointed out, it is fine to use this variant as well:</p>

```jQuery(function($) {
  $('#cp_email_address').blur(function() {
    var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    if (testEmail.test(this.value)) {}; // if true pass
    else {
      this.value = "";
    };
  });
});
```

Again, quoting from his comment:

If you have no idea how Wordpress works, maybe you should hire someone that can edit the plugin to make it actually work the way it should, with server side validation!

Body:
My client uses wordpress, the template he's using generates a dynamic form, so I don't know where the html is stored. Therefore I can't use email attribute in html, nor I can validate emails using php since I don't have a clue how his theme validates the form.

The form builder generates a text input called cp_email_address I want to check if the user entered a valid email, otherwise I want to clear the field, I don't have any other option, since I can't wait for the user to submit and then validate, I don't know where the submit code is. All I know is the name, class and id of the email field.

I also tried target.value= "";

And tried $('#cp_email_address').value = "";

And I tried document.getElementById('cp_email_address').value = "";

Nothing is clearing the the input field.

Body:
As a seasoned WordPress expert, I could say the following:

WordPress generally doesn't allow you to use $ for jQuery. Try using jQuery instead.

Secondly, you haven't put inside the document's ready event, which is more important.

Ultimately, what I suggest you to do is, combine the both and try:

(function($) {
  $(function() {
    $('#cp_email_address').blur(function() {
      var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
      if (testEmail.test(this.value)) {}; // if true pass
      else {
        this.value = "";
      };
    });
  });
})(jQuery)

What I had done above is, I created an IIFE, which takes in its first parameter as jQuery so, this gets associated with $ inside the function. So this should 90% work, if you don't get any errors.

Try to add this function in the footer.php or somewhere, which definitely gets called.

Update: Well, I know this already, but just wanted to be sure. Anyway, as adeneo pointed out, it is fine to use this variant as well:

jQuery(function($) {
  $('#cp_email_address').blur(function() {
    var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    if (testEmail.test(this.value)) {}; // if true pass
    else {
      this.value = "";
    };
  });
});

Again, quoting from his comment:

If you have no idea how Wordpress works, maybe you should hire someone that can edit the plugin to make it actually work the way it should, with server side validation!


问:
Why Doesn't My Mario Sprite (a JComponent) Show Up?
I'm trying to write a Mario 3 level 1 clone, and previously, I was able to get it to show up in JFrames when I had the pulling of the sprite in the constructor of Mario itself. However, because I realized that I'll need to link things like the coordinates and state (small, large) to the moving image itself, I decided to tear it up and have a Mario and MarioComponent. I have a MarioComponent class but it doesn't show up.

```<code>public class MarioComponent extends JComponent{

  private Mario m;

  public MarioComponent(){
    m = new Mario();
  }

  public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    m.draw();

  }

    public void moveMario(){
    m.move();
    repaint();
  }

  public static void main(String[] args){
    JFrame f = new JFrame();
    f.setSize(868,915);
    MarioComponent m = new MarioComponent();
    m.setLocation(100,100);
    f.add(m);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  }

}
</code>```

my Mario class:

```<code>public class Mario{
//all numbers multiplied by 2 from OG game
  protected MarioState state;
  protected int x, y;
  BufferedImage sprite;

  public Mario(){
    this.state = MarioState.SMALL;
    this.x = 54;
    this.y = 806;
  }

  public Mario(MarioState s, int x, int y){
    this.state = s;
    this.x = x;
    this.y = y;
  }

  public void move(){
    this.x+=2;

  }

  public void jump(){
    this.y -= 46;

  }

  public String getCoordinates(){
    return "Mario coords: " + this.x + ", " + this.y + ".";
  }

  public void draw(){
    URL spriteAtLoc = getClass().getResource("sprites/Mario/SmallStandFaceRight.bmp");

    try{
      sprite = ImageIO.read(spriteAtLoc);

    } catch(IOException e){
      System.out.println("sprite not found");
      e.printStackTrace();
    }
  }
}
</code>```

When I try to place a MarioComponent on a JFrame, its not there. How can I remedy this?

答:
You need to use the Graphics object, g (or g2 -- they're the same object) within your paintComponent as the "pen" with which to draw. You don't do this, so there's no way that anything could or should render. Graphics has a method, g.drawImage(...) that accepts an image as one of its parameters and would be the best way for this to work.

Suggestions:

Change draw so that it accepts a Graphics parameter: public void draw(Graphics g){

Within paintComponent, pass the Graphics parameter given to the method by the JVM into your draw call: m.draw(g);

Don't keep re-reading in the image within the draw method. This is wasteful and will only cause lag. Read it in once and store it into a variable.

All the code within the current draw method shouldn't be there. Again, the image should be read in once, likely within the constructor, and draw should instead actually draw the image, not read the file.

Don't guess at this, but rather read the appropriate tutorials

Lesson: Performing Custom Painting: introductory tutorial to Swing graphics

Painting in AWT and Swing: advanced tutorial on Swing graphics

Body:
I'm trying to write a Mario 3 level 1 clone, and previously, I was able to get it to show up in JFrames when I had the pulling of the sprite in the constructor of Mario itself. However, because I realized that I'll need to link things like the coordinates and state (small, large) to the moving image itself, I decided to tear it up and have a Mario and MarioComponent. I have a MarioComponent class but it doesn't show up.

public class MarioComponent extends JComponent{

  private Mario m;

  public MarioComponent(){
    m = new Mario();
  }

  public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    m.draw();

  }

    public void moveMario(){
    m.move();
    repaint();
  }

  public static void main(String[] args){
    JFrame f = new JFrame();
    f.setSize(868,915);
    MarioComponent m = new MarioComponent();
    m.setLocation(100,100);
    f.add(m);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  }

}

my Mario class:

public class Mario{
//all numbers multiplied by 2 from OG game
  protected MarioState state;
  protected int x, y;
  BufferedImage sprite;

  public Mario(){
    this.state = MarioState.SMALL;
    this.x = 54;
    this.y = 806;
  }

  public Mario(MarioState s, int x, int y){
    this.state = s;
    this.x = x;
    this.y = y;
  }

  public void move(){
    this.x+=2;

  }

  public void jump(){
    this.y -= 46;

  }

  public String getCoordinates(){
    return "Mario coords: " + this.x + ", " + this.y + ".";
  }

  public void draw(){
    URL spriteAtLoc = getClass().getResource("sprites/Mario/SmallStandFaceRight.bmp");

    try{
      sprite = ImageIO.read(spriteAtLoc);

    } catch(IOException e){
      System.out.println("sprite not found");
      e.printStackTrace();
    }
  }
}

When I try to place a MarioComponent on a JFrame, its not there. How can I remedy this?


问:
Can't convert object of type java.util.ArrayList to type model
I'm trying to load data to RecycleView from Firebase. But I get convert error.

```<code>com.google.firebase.database.DatabaseException: Can't convert object of type java.util.ArrayList to type uk.co.stableweb.kithunugee.model.Hymn
     at com.google.android.gms.internal.zzaix.zzd(Unknown Source)
     at com.google.android.gms.internal.zzaix.zzb(Unknown Source)
     at com.google.android.gms.internal.zzaix.zza(Unknown Source)
     at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
     at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
     at com.firebase.ui.database.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:147)
     at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:136)
     at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:176)
     at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5471)
     at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5504)
     at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4741)
     at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617)
     at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1994)
     at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1390)
     at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353)
     at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574)
     at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028)
     at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2625)
     at android.view.View.measure(View.java:18850)
     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:716)
     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:462)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
     at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
     at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1192)
     at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:733)
     at android.view.View.measure(View.java:18850)
     at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1075)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2671)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2107)
</code>```

This is how I load data from RecycleView.

```<code>DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
mRecyclerViewAdapter = new FirebaseRecyclerAdapter<Hymn, HymnHolder>(Hymn.class, R.layout.hymn_row, HymnHolder.class, ref) {
       @Override
       protected void populateViewHolder(HymnHolder viewHolder, Hymn hymn, int position) {
              viewHolder.setTitle(hymn.getTitle());
              viewHolder.setIndex(String.valueOf(hymn.getIndex()));
      }
};

// Scroll to bottom on new messages
mRecyclerViewAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
       @Override
       public void onItemRangeInserted(int positionStart, int itemCount) {
              mLayoutManager.smoothScrollToPosition(recyclerView, null, mRecyclerViewAdapter.getItemCount());
       }
});

recyclerView.setAdapter(mRecyclerViewAdapter);
</code>```

And my ViewHolder class is,

```<code>public class HymnHolder extends RecyclerView.ViewHolder {
    View mView;

    public HymnHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setTitle(String name) {
        TextView field = (TextView) mView.findViewById(R.id.title);
        field.setText(name);
    }

    public void setIndex(String index) {
        TextView field = (TextView) mView.findViewById(R.id.index);
        field.setText(index);
    }
}
</code>```

And this is my model.

```<code>public class Hymn {
    private int index;
    private String title;
    private String content;

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}
</code>```

Here is the structure of my Firebase database.

I refered this Firebase UI tutorial. There were few previous questions regarding this problem, but it's not clear to me. If you have any hint on this issue, it would be really helpful.

答:
Change your database reference

old code

```<code>DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
</code>```

new code

```<code> mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("geethika");
</code>```

Body:
I'm trying to load data to RecycleView from Firebase. But I get convert error.

com.google.firebase.database.DatabaseException: Can't convert object of type java.util.ArrayList to type uk.co.stableweb.kithunugee.model.Hymn
     at com.google.android.gms.internal.zzaix.zzd(Unknown Source)
     at com.google.android.gms.internal.zzaix.zzb(Unknown Source)
     at com.google.android.gms.internal.zzaix.zza(Unknown Source)
     at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
     at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
     at com.firebase.ui.database.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:147)
     at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:136)
     at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:176)
     at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5471)
     at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5504)
     at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4741)
     at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617)
     at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1994)
     at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1390)
     at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353)
     at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574)
     at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028)
     at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2625)
     at android.view.View.measure(View.java:18850)
     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:716)
     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:462)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
     at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
     at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1192)
     at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:733)
     at android.view.View.measure(View.java:18850)
     at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1075)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5956)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2671)
     at android.view.View.measure(View.java:18850)
     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2107)

This is how I load data from RecycleView.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
mRecyclerViewAdapter = new FirebaseRecyclerAdapter<Hymn, HymnHolder>(Hymn.class, R.layout.hymn_row, HymnHolder.class, ref) {
       @Override
       protected void populateViewHolder(HymnHolder viewHolder, Hymn hymn, int position) {
              viewHolder.setTitle(hymn.getTitle());
              viewHolder.setIndex(String.valueOf(hymn.getIndex()));
      }
};

// Scroll to bottom on new messages
mRecyclerViewAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
       @Override
       public void onItemRangeInserted(int positionStart, int itemCount) {
              mLayoutManager.smoothScrollToPosition(recyclerView, null, mRecyclerViewAdapter.getItemCount());
       }
});

recyclerView.setAdapter(mRecyclerViewAdapter);

And my ViewHolder class is,

public class HymnHolder extends RecyclerView.ViewHolder {
    View mView;

    public HymnHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setTitle(String name) {
        TextView field = (TextView) mView.findViewById(R.id.title);
        field.setText(name);
    }

    public void setIndex(String index) {
        TextView field = (TextView) mView.findViewById(R.id.index);
        field.setText(index);
    }
}

And this is my model.

public class Hymn {
    private int index;
    private String title;
    private String content;

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

Here is the structure of my Firebase database.

I refered this Firebase UI tutorial. There were few previous questions regarding this problem, but it's not clear to me. If you have any hint on this issue, it would be really helpful.

Body:
Change your database reference

old code

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

new code

 mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("geethika");


问:
javascript bitwise xor producing inconsistent result
I am using bitwise operations in javascript but I have noticed something that appears inconsistent.

Right now, I'm using the XOR (^) operation. When I do '0101'^'0001', I get 4, which makes sense since 4 = 0100 in binary.
But when I do '10001'^'01111', I get 9030, when I think I should get 11110.
The format is, to best that I can tell, the same; only the strings are different.

```<code>console.log(5^1); //4
console.log('0101'^'0001'); // 100 = 4

console.log(17^15); //30
console.log('10001'^'01111'); //9030...why? shouldn't it be '11110'?
</code>```

Why is this code producing this result?

Now, If I do this:

```<code>console.log(('0b'+'10001')^('0b' + '01111')); //30
</code>```

Why did I have to add '0b' to specify that the strings were binary sequences when doing bitwise ops on 17 and 15, but not with 5 and 1?

答:
You are using the ^ operator on strings. When using any numerical operator on a string JavaScript will implicitly convert the string to a number. Adding 0b tells JavaScript to treat your number as a binary or base 2 number.

Otherwise, by default they will be converted to decimal or base 10 values.

Do operations on binary values represented in a string you have to convert your values to numerical base 2 values first.

You can verify in a calculator 10,001^1111 = 9030.

In binary 1111=15 and 10001=17. 15^17= 30 which is 11110 in binary.

101 Xor 1 is a special case, In decimal 101 Xor 1 = 100. In Binary 101 = 5 and  5 Xor 1 = 4 which is written out in binary as 100.

Body:
I am using bitwise operations in javascript but I have noticed something that appears inconsistent.

Right now, I'm using the XOR (^) operation. When I do '0101'^'0001', I get 4, which makes sense since 4 = 0100 in binary.
But when I do '10001'^'01111', I get 9030, when I think I should get 11110.
The format is, to best that I can tell, the same; only the strings are different.

console.log(5^1); //4
console.log('0101'^'0001'); // 100 = 4

console.log(17^15); //30
console.log('10001'^'01111'); //9030...why? shouldn't it be '11110'?

Why is this code producing this result?

Now, If I do this:

console.log(('0b'+'10001')^('0b' + '01111')); //30

Why did I have to add '0b' to specify that the strings were binary sequences when doing bitwise ops on 17 and 15, but not with 5 and 1?


问:
Matplotlib PyPlot Lines in Histogram
I'm a beginner to matplotlib's pyplot and was wondering how to get black lines between the bars of the histogram. I did some googling and others were seeming to get this behavior out of the box with the same commands as I was using.

答:
With matplotlib version 2, transparent edges in histograms became the default(Reference), to modify that just add the edgecolor = 'black' parameter to your plt.hist:

```<code>plt.hist(data, 20, alpha=.5, edgecolor = 'black')
</code>```

Demo with random data:

```<code>import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)
plt.hist(x, 20, alpha=0.5, edgecolor = 'black')
plt.show()
</code>```

Title: Matplotlib PyPlot Lines in Histogram

Body:
With matplotlib version 2, transparent edges in histograms became the default(Reference), to modify that just add the edgecolor = 'black' parameter to your plt.hist:

plt.hist(data, 20, alpha=.5, edgecolor = 'black')

Demo with random data:

import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)
plt.hist(x, 20, alpha=0.5, edgecolor = 'black')
plt.show()


答:
However, this destroy call isn't actually destroying the LineSegment
  object

When you call Destroy(componentName);, the component that is passed in will be destroyed but the GameObject the component is attached to will not be destroyed.

If you want the GameObject to destroy with all the scripts attached to it then Destroy(componentName.gameObject); should be used.

So replace Destroy(lineSegmentRep[i]); with Destroy(lineSegmentRep[i].gameObject);.

Also before destroying each LineSegment, it is important that you also remove them from the List so that you won't have an empty/null LineSegment in that lineSegmentRep List.

```<code>public void deleteSegment(int i)
{
    //Remove from the List
    lineSegmentRep.Remove(lineSegmentRep[i]);
    //Now, destroy its object+script
    Destroy(lineSegmentRep[i].gameObject);
}
</code>```

Title: Destroy not destroying GameObject

Body:
However, this destroy call isn't actually destroying the LineSegment
  object

When you call Destroy(componentName);, the component that is passed in will be destroyed but the GameObject the component is attached to will not be destroyed.

If you want the GameObject to destroy with all the scripts attached to it then Destroy(componentName.gameObject); should be used.

So replace Destroy(lineSegmentRep[i]); with Destroy(lineSegmentRep[i].gameObject);.

Also before destroying each LineSegment, it is important that you also remove them from the List so that you won't have an empty/null LineSegment in that lineSegmentRep List.

public void deleteSegment(int i)
{
    //Remove from the List
    lineSegmentRep.Remove(lineSegmentRep[i]);
    //Now, destroy its object+script
    Destroy(lineSegmentRep[i].gameObject);
}


问:
List item inside model always null on post - Asp.net MVC
I am trying to post model which contains List<> item looks like below:

```<code>public class AddSubscriptionPlanModel
{
    public AddSubscriptionPlanModel()
    {
        AllFeatures = new List<Feature>();
    }
    public int Id { get; set; }
    public int SubscriptionPlanId { get; set; }
    public int SubscriptionId { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    [Display(Name = "No Of Users")]
    public int? NoOfUsers { get; set; }
    [Display(Name = "Duration Type")]
    public DurationType DurationType { get; set; }
    public int Duration { get; set; }
    public decimal Amount { get; set; }
    public int SubscriptionPlanTrailId { get; set; }
    public int FeatureId { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public DateTime LastUpdatedUtc { get; set; }
    public int CreatedBy { get; set; }
    public int LastUpdatedBy { get; set; }
    public List<Feature> AllFeatures { get; set; }
}
</code>```

I am populating all required fields on get method and feeding List from database

```<code>public ActionResult Mapping(int id)
{
    var features = FeatureManager.GetAllFeatures();
    var model = new Ejyle.DevAccelerate.Web.App.Models.SubscriptionPlan.AddSubscriptionPlanModel();

    model.AllFeatures = features;
    model.Id = id;
    model.SubscriptionId = id;
    model.NoOfUsers = 20;
    model.SubscriptionPlanId = 1;
    model.SubscriptionPlanTrailId = 1;
    model.Amount = 1000;
    model.CreatedBy = 1;
    model.LastUpdatedBy = 1;
    model.FeatureId = 1;
    model.Duration = 20;

    return View(model);
}
</code>```

And my view code looks like below :

```<code>@using (Html.BeginForm("Mapping", "SubscriptionPlans", FormMethod.Post))
{
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.Amount)
    @Html.HiddenFor(model => model.Duration)
    @Html.HiddenFor(model => model.FeatureId)
    @Html.HiddenFor(model => model.CreatedBy)
    @Html.HiddenFor(model => model.LastUpdatedBy)
    @Html.HiddenFor(model => model.NoOfUsers)
    @Html.HiddenFor(model => model.SubscriptionId)
    @Html.HiddenFor(model => model.SubscriptionPlanId)
    @Html.HiddenFor(model => model.SubscriptionPlanTrailId)
    @Html.HiddenFor(model => model.AllFeatures)
    <table class="table table-striped">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.IsActive)
                </th>
            </tr>
        </thead>
        <tbody>
            @for (int i=0; i < Model.AllFeatures.Count; i++)
            {
                <tr>
                    @Html.HiddenFor(model => model.AllFeatures[i].Id)
                    @Html.HiddenFor(model => model.AllFeatures[i].Name)
                    @Html.HiddenFor(model => model.AllFeatures[i].IsActive)
                    <td>
                        @Html.TextBoxFor(model => model.AllFeatures[i].Id)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.AllFeatures[i].Name)
                    </td>
                    <td>
                        @Html.EditorFor(model => model.AllFeatures[i].IsActive)
                    </td>
                </tr>
            }
        </tbody>
    </table>
    <input type="submit" class="btn btn-success" value="Submit" name="Submit"/>
}
</code>```

On View, the list items rendered properly and even I am able to edit those fields.

But On post, all properties have the value except AllFeatures list item property which always shows count = 0.

Edit 1: This is how my view looks like while rendering features

Edit 2:

Signature of the method posting to:

```<code>[HttpPost]
public ActionResult Mapping(AddSubscriptionPlanModel model)
{
}
</code>```

答:
This how to do it, as in the context of binding to a list from a view is incorrect.

View:

```<code>@model Testy20161006.Controllers.AddSubscriptionPlanModel
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Mapping</title>
</head>
<body>
    @*I am using controller home*@
    @using (Html.BeginForm("Mapping", "Home", FormMethod.Post))
    {
        @Html.HiddenFor(model => model.Id)
        @Html.HiddenFor(model => model.Amount)
        @Html.HiddenFor(model => model.Duration)
        @Html.HiddenFor(model => model.FeatureId)
        @Html.HiddenFor(model => model.CreatedBy)
        @Html.HiddenFor(model => model.LastUpdatedBy)
        @Html.HiddenFor(model => model.NoOfUsers)
        @Html.HiddenFor(model => model.SubscriptionId)
        @Html.HiddenFor(model => model.SubscriptionPlanId)
        @Html.HiddenFor(model => model.SubscriptionPlanTrailId)
        @Html.HiddenFor(model => model.AllFeatures)
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Name)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.IsActive)
                    </th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < Model.AllFeatures.Count; i++)
                {
                    <tr>
                        @*BE SURE to get rid of these*@
                        @*@Html.HiddenFor(model => model.AllFeatures[i].Id)
                            @Html.HiddenFor(model => model.AllFeatures[i].Name)
                            @Html.HiddenFor(model => model.AllFeatures[i].IsActive)*@
                        <td>
                            @Html.TextBoxFor(model => model.AllFeatures[i].Id)
                        </td>
                        <td>
                            @Html.TextBoxFor(model => model.AllFeatures[i].Name)
                        </td>
                        <td>
                            @Html.EditorFor(model => model.AllFeatures[i].IsActive)
                        </td>
                    </tr>
                }
            </tbody>
        </table>
        <input type="submit" class="btn btn-success" value="Submit" name="Submit" />
    }
</body>
</html>
</code>```

Controller:

```<code>[HttpPost]
public ActionResult Mapping(AddSubscriptionPlanModel addSubscriptionModel, FormCollection formCollection)
    {
        var AllFeatures = String.Empty;
        var index = "AllFeatures[";
        foreach (var item in formCollection)
        {
            if (item.ToString().Contains(index))
            {
                AllFeatures += " " + formCollection.GetValues(item.ToString())[0];
            }
        }

        //put breakpoint here to see userValues
</code>```

Body:
I am trying to post model which contains List<> item looks like below:

public class AddSubscriptionPlanModel
{
    public AddSubscriptionPlanModel()
    {
        AllFeatures = new List<Feature>();
    }
    public int Id { get; set; }
    public int SubscriptionPlanId { get; set; }
    public int SubscriptionId { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    [Display(Name = "No Of Users")]
    public int? NoOfUsers { get; set; }
    [Display(Name = "Duration Type")]
    public DurationType DurationType { get; set; }
    public int Duration { get; set; }
    public decimal Amount { get; set; }
    public int SubscriptionPlanTrailId { get; set; }
    public int FeatureId { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public DateTime LastUpdatedUtc { get; set; }
    public int CreatedBy { get; set; }
    public int LastUpdatedBy { get; set; }
    public List<Feature> AllFeatures { get; set; }
}

I am populating all required fields on get method and feeding List from database

public ActionResult Mapping(int id)
{
    var features = FeatureManager.GetAllFeatures();
    var model = new Ejyle.DevAccelerate.Web.App.Models.SubscriptionPlan.AddSubscriptionPlanModel();

    model.AllFeatures = features;
    model.Id = id;
    model.SubscriptionId = id;
    model.NoOfUsers = 20;
    model.SubscriptionPlanId = 1;
    model.SubscriptionPlanTrailId = 1;
    model.Amount = 1000;
    model.CreatedBy = 1;
    model.LastUpdatedBy = 1;
    model.FeatureId = 1;
    model.Duration = 20;

    return View(model);
}

And my view code looks like below :

@using (Html.BeginForm("Mapping", "SubscriptionPlans", FormMethod.Post))
{
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.Amount)
    @Html.HiddenFor(model => model.Duration)
    @Html.HiddenFor(model => model.FeatureId)
    @Html.HiddenFor(model => model.CreatedBy)
    @Html.HiddenFor(model => model.LastUpdatedBy)
    @Html.HiddenFor(model => model.NoOfUsers)
    @Html.HiddenFor(model => model.SubscriptionId)
    @Html.HiddenFor(model => model.SubscriptionPlanId)
    @Html.HiddenFor(model => model.SubscriptionPlanTrailId)
    @Html.HiddenFor(model => model.AllFeatures)

                    @Html.DisplayNameFor(model => model.Name)

                    @Html.DisplayNameFor(model => model.IsActive)

            @for (int i=0; i < Model.AllFeatures.Count; i++)
            {

                    @Html.HiddenFor(model => model.AllFeatures[i].Id)
                    @Html.HiddenFor(model => model.AllFeatures[i].Name)
                    @Html.HiddenFor(model => model.AllFeatures[i].IsActive)

                        @Html.TextBoxFor(model => model.AllFeatures[i].Id)

                        @Html.TextBoxFor(model => model.AllFeatures[i].Name)

                        @Html.EditorFor(model => model.AllFeatures[i].IsActive)

            }

    <input type="submit" class="btn btn-success" value="Submit" name="Submit"/>
}

On View, the list items rendered properly and even I am able to edit those fields.

But On post, all properties have the value except AllFeatures list item property which always shows count = 0.

Edit 1: This is how my view looks like while rendering features

Edit 2:

Signature of the method posting to:

[HttpPost]
public ActionResult Mapping(AddSubscriptionPlanModel model)
{
}

Body:
This how to do it, as in the context of binding to a list from a view is incorrect.

View:

@model Testy20161006.Controllers.AddSubscriptionPlanModel
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Mapping</title>
</head>
<body>
    @*I am using controller home*@
    @using (Html.BeginForm("Mapping", "Home", FormMethod.Post))
    {
        @Html.HiddenFor(model => model.Id)
        @Html.HiddenFor(model => model.Amount)
        @Html.HiddenFor(model => model.Duration)
        @Html.HiddenFor(model => model.FeatureId)
        @Html.HiddenFor(model => model.CreatedBy)
        @Html.HiddenFor(model => model.LastUpdatedBy)
        @Html.HiddenFor(model => model.NoOfUsers)
        @Html.HiddenFor(model => model.SubscriptionId)
        @Html.HiddenFor(model => model.SubscriptionPlanId)
        @Html.HiddenFor(model => model.SubscriptionPlanTrailId)
        @Html.HiddenFor(model => model.AllFeatures)
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Name)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.IsActive)
                    </th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < Model.AllFeatures.Count; i++)
                {
                    <tr>
                        @*BE SURE to get rid of these*@
                        @*@Html.HiddenFor(model => model.AllFeatures[i].Id)
                            @Html.HiddenFor(model => model.AllFeatures[i].Name)
                            @Html.HiddenFor(model => model.AllFeatures[i].IsActive)*@
                        <td>
                            @Html.TextBoxFor(model => model.AllFeatures[i].Id)
                        </td>
                        <td>
                            @Html.TextBoxFor(model => model.AllFeatures[i].Name)
                        </td>
                        <td>
                            @Html.EditorFor(model => model.AllFeatures[i].IsActive)
                        </td>
                    </tr>
                }
            </tbody>
        </table>
        <input type="submit" class="btn btn-success" value="Submit" name="Submit" />
    }
</body>
</html>

Controller:

[HttpPost]
public ActionResult Mapping(AddSubscriptionPlanModel addSubscriptionModel, FormCollection formCollection)
    {
        var AllFeatures = String.Empty;
        var index = "AllFeatures[";
        foreach (var item in formCollection)
        {
            if (item.ToString().Contains(index))
            {
                AllFeatures += " " + formCollection.GetValues(item.ToString())[0];
            }
        }

        //put breakpoint here to see userValues


问:
Finding Currently Focused Application
I've been using this code to try and get the current process that's running (other that my application).

All over the internet it's been telling me to use the code below but it seems to be giving me issues.

```<code>[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

private string GetActiveWindowTitle()
{
    const int nChars = 256;
    StringBuilder Buff = new StringBuilder(nChars);
    IntPtr handle = GetForegroundWindow();

    if (GetWindowText(handle, Buff, nChars) > 0)
    {
     return Buff.ToString();
    }
  return null;
}
</code>```

It's giving me two errors.

Expected class, delegate, enum, interface, or struct

The modifier 'extern' is not valid for this item

Could anybody help?

答:
Expected class, delegate, enum, interface, or struct

If you are getting this error then most probably you are defining or declaring those method within namespace and not within your class body

Title: Finding Currently Focused Application

Body:
I've been using this code to try and get the current process that's running (other that my application).

All over the internet it's been telling me to use the code below but it seems to be giving me issues.

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

private string GetActiveWindowTitle()
{
    const int nChars = 256;
    StringBuilder Buff = new StringBuilder(nChars);
    IntPtr handle = GetForegroundWindow();

    if (GetWindowText(handle, Buff, nChars) > 0)
    {
     return Buff.ToString();
    }
  return null;
}

It's giving me two errors.

Expected class, delegate, enum, interface, or struct

The modifier 'extern' is not valid for this item

Could anybody help?


问:
Function that generates all combinations of a string
I am new to javascript still trying to learn things.

I've found a solution to a problem about a function that should generate all combinations of a characters within a string.

I'm trying to figure out:

What is happening inside the loop?

How does the loops execute step by step?

I cannot figure how it reaches to that final output.

I tried for a long time to figure out but I m not sure what happens inside those
   loops. I don't understand tho how it gets "ab", "ac". ... together
   in the final output and where arrTemp pushes result[x] and char. I saw that the result array is initially empty, then is concatenated with arrTemp.

Here is the code I'm struggling with:

```<code> function combString(str){
     var lenStr = str.length;
     var result = [];
     var indexCurrent = 0;

     while(indexCurrent < lenStr){
         var char = str.charAt(indexCurrent);
         var x;
         var arrTemp = [char];

         for(x in result) {
             arrTemp.push(""+result[x]+char);
         }
         result = result.concat(arrTemp);

         indexCurrent++;
     }

     return result;
}

console.log(combString("abc"));
</code>```

And this is the output

```<code>["a", "b", "ab", "c", "ac", "bc", "abc"]
</code>```

答:
Simple use of for loop and while statement to get different combinations. </p>

```<code>function combu(s){
var buff = [];
var res = [];
for (i=0;i<s.length;i++){
    buff = [s[i]];
    var index=0;
    while(res[index]){
        buff.push(''+res[index]+s[i]);
        index++;
    }
    res = res.concat(buff);
}
return res;
}

combu('abc');
</code>```

Body:
I am new to javascript still trying to learn things.

I've found a solution to a problem about a function that should generate all combinations of a characters within a string.

I'm trying to figure out:

What is happening inside the loop?

How does the loops execute step by step?

I cannot figure how it reaches to that final output.

I tried for a long time to figure out but I m not sure what happens inside those
   loops. I don't understand tho how it gets "ab", "ac". ... together
   in the final output and where arrTemp pushes result[x] and char. I saw that the result array is initially empty, then is concatenated with arrTemp.

Here is the code I'm struggling with:

 function combString(str){
     var lenStr = str.length;
     var result = [];
     var indexCurrent = 0;

     while(indexCurrent < lenStr){
         var char = str.charAt(indexCurrent);
         var x;
         var arrTemp = [char];

         for(x in result) {
             arrTemp.push(""+result[x]+char);
         }
         result = result.concat(arrTemp);

         indexCurrent++;
     }

     return result;
}

console.log(combString("abc"));

And this is the output

["a", "b", "ab", "c", "ac", "bc", "abc"]

Body:
Simple use of for loop and while statement to get different combinations.

function combu(s){
var buff = [];
var res = [];
for (i=0;i<s.length;i++){
    buff = [s[i]];
    var index=0;
    while(res[index]){
        buff.push(''+res[index]+s[i]);
        index++;
    }
    res = res.concat(buff);
}
return res;
}

combu('abc');


问:
How can I structure these kodi parameter checks?
I'm creating an add-on for Kodi and am in the middle of restructuring the directory structure and router function as my programmatic flow and features have drastically changed since first starting the project. The new directory structure I'm looking to implement goes like so:

By Animal

Animal 1 (eg Cats)

Suggested Category/Search 1 (eg Cats on Roombas)

Suggested Category/Search 2 (eg Cats & Cucumbers)

All

By Site

Random Video

Random Continuous

Search

Animal 2

Suggested Category/Search 1

Suggested Category/Search 2

All

By Site

Random Video

Random Continuous

Search

By Site

Site 1 (Active)

Site 2 (Dormant)

Site 3 (Active/Large Selection)

Site 4 (Dormant/Large Selection)

By Category

Educational/Wildlife

All

By Animal

By Site

Random Video

Random Continuous

Search

Heartwarming

All

By Animal

By Site

Random Video

Random Continuous

Search

Cute/Funny

All

By Animal

By Site

Random Video

Random Continuous

Search

Live Streams

Random Video

Random Continuous

Global Search

As you can see there are some repeating directory items, which I intend of having to allow users to refine their searches as they get deeper into the directory structure. Those repeating items are where I'm currently lost pertaining to how to deal with them. My reworked router function currently looks like this:

```<code>MAIN_MENU = ['By Animal',
             'By Site',
             'By Category',
             'Live Streams',
             'Random Video',
             'Random Continuous',
             'Search']

def get_url(**kwargs):
    return '{0}?{1}'.format(_url, urlencode(kwargs))

def main_menu():
    for menu_item in MAIN_MENU:
        list_item = xbmcgui.ListItem(label=menu_item)
        is_folder = True
        url = get_url(action='listing', section=menu_item)
        xbmcplugin.addDirectoryItem(_handle, url, list_item, is_folder)
    xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_NONE)
    xbmcplugin.endOfDirectory(_handle)

def router(paramstring):
    params = dict(parse_qsl(paramstring))
    if params:
        if params['action'] == 'listing':
            if 'topic' in params:
                meta.get_directory(params['section'], params['topic'])
            else:
                meta.get_directory(params['section'])
        elif params['action'] == 'query':
            if 'section' in params:
                #further checks
                if 'topic' in params:
                    #Only search sources under this topic (suggested category, all, by site, random video, etc)
                    #meta.get_results(params['section'], params['topic'], params['query'])
                elif 'animal' in params:
                    #Only search sources with this animal in their meta tags
            else:
                #global search
                #scraper.Site.search(params['QUERY'])
        elif params['action'] == 'play':

        else:
            raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
    else:
        main_menu()
</code>```

Obviously it's a pretty big mess right now. I feel like it's stuck in an infinite loop. I have what I think should be the parameters worked out in my head, but am not sure how to correctly implement them to recursively work with the directory structure above.

Parameter List

ACTION:

listing (by section, then by topic)

query (by section [checks if global search], by source, by animal, by term/query)

play (link has been retrieved, play it)

SECTION: which directory we're in (By Animal, By Site, By Category, etc)

TOPIC: which subdirectory is selected from the section (Animal 1 under By Animal, Cute/Funny under By Category, etc)

ANIMAL?: which animal we've selected or are in

SOURCE?: which source we've selected or are in

QUERY: contains the search term

VIDEO: contains the link to play

Finally, the questions

Is it possible to make this structure work?

If so, how?

In what order do I need to check the parameters in order to cover all the possibilities?

Should I structure this differently in order for it to work?

If so, how?

答:
For complex path hierarchy I'd recommend not to invent a wheel but use this routing library: https://github.com/tamland/kodi-plugin-routing . It's script.module.routing in the Kodi official addon repository.

This library creates "pretty" URLs with arbitrary paths much like popular Flask web framework, doing all heavy lifting like paths parsing "under the hood".

Copy-paste from the library's Readme:

```<code>import routing
from xbmcgui import ListItem
from xbmcplugin import addDirectoryItem, endOfDirectory

plugin = routing.Plugin()

@plugin.route('/')
def index():
    addDirectoryItem(plugin.handle, plugin.url_for(show_category, "one"), ListItem("Category One"), True)
    addDirectoryItem(plugin.handle, plugin.url_for(show_category, "two"), ListItem("Category Two"), True)
    endOfDirectory(plugin.handle)

@plugin.route('/category/<category_id>')
def show_category(category_id):
    addDirectoryItem(plugin.handle, "", ListItem("Hello category %s!" % category_id))
    endOfDirectory(plugin.handle)

if __name__ == '__main__':
    plugin.run()
</code>```

Body:
I'm creating an add-on for Kodi and am in the middle of restructuring the directory structure and router function as my programmatic flow and features have drastically changed since first starting the project. The new directory structure I'm looking to implement goes like so:

By Animal

Animal 1 (eg Cats)

Suggested Category/Search 1 (eg Cats on Roombas)

Suggested Category/Search 2 (eg Cats & Cucumbers)

All

By Site

Random Video

Random Continuous

Search

Animal 2

Suggested Category/Search 1

Suggested Category/Search 2

All

By Site

Random Video

Random Continuous

Search

By Site

Site 1 (Active)

Site 2 (Dormant)

Site 3 (Active/Large Selection)

Site 4 (Dormant/Large Selection)

By Category

Educational/Wildlife

All

By Animal

By Site

Random Video

Random Continuous

Search

Heartwarming

All

By Animal

By Site

Random Video

Random Continuous

Search

Cute/Funny

All

By Animal

By Site

Random Video

Random Continuous

Search

Live Streams

Random Video

Random Continuous

Global Search

As you can see there are some repeating directory items, which I intend of having to allow users to refine their searches as they get deeper into the directory structure. Those repeating items are where I'm currently lost pertaining to how to deal with them. My reworked router function currently looks like this:

MAIN_MENU = ['By Animal',
             'By Site',
             'By Category',
             'Live Streams',
             'Random Video',
             'Random Continuous',
             'Search']

def get_url(**kwargs):
    return '{0}?{1}'.format(_url, urlencode(kwargs))

def main_menu():
    for menu_item in MAIN_MENU:
        list_item = xbmcgui.ListItem(label=menu_item)
        is_folder = True
        url = get_url(action='listing', section=menu_item)
        xbmcplugin.addDirectoryItem(_handle, url, list_item, is_folder)
    xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_NONE)
    xbmcplugin.endOfDirectory(_handle)

def router(paramstring):
    params = dict(parse_qsl(paramstring))
    if params:
        if params['action'] == 'listing':
            if 'topic' in params:
                meta.get_directory(params['section'], params['topic'])
            else:
                meta.get_directory(params['section'])
        elif params['action'] == 'query':
            if 'section' in params:
                #further checks
                if 'topic' in params:
                    #Only search sources under this topic (suggested category, all, by site, random video, etc)
                    #meta.get_results(params['section'], params['topic'], params['query'])
                elif 'animal' in params:
                    #Only search sources with this animal in their meta tags
            else:
                #global search
                #scraper.Site.search(params['QUERY'])
        elif params['action'] == 'play':

        else:
            raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
    else:
        main_menu()

Obviously it's a pretty big mess right now. I feel like it's stuck in an infinite loop. I have what I think should be the parameters worked out in my head, but am not sure how to correctly implement them to recursively work with the directory structure above.

Parameter List

ACTION:

listing (by section, then by topic)

query (by section [checks if global search], by source, by animal, by term/query)

play (link has been retrieved, play it)

SECTION: which directory we're in (By Animal, By Site, By Category, etc)

TOPIC: which subdirectory is selected from the section (Animal 1 under By Animal, Cute/Funny under By Category, etc)

ANIMAL?: which animal we've selected or are in

SOURCE?: which source we've selected or are in

QUERY: contains the search term

VIDEO: contains the link to play

Finally, the questions

Is it possible to make this structure work?

If so, how?

In what order do I need to check the parameters in order to cover all the possibilities?

Should I structure this differently in order for it to work?

If so, how?

Body:
For complex path hierarchy I'd recommend not to invent a wheel but use this routing library: https://github.com/tamland/kodi-plugin-routing . It's script.module.routing in the Kodi official addon repository.

This library creates "pretty" URLs with arbitrary paths much like popular Flask web framework, doing all heavy lifting like paths parsing "under the hood".

Copy-paste from the library's Readme:

import routing
from xbmcgui import ListItem
from xbmcplugin import addDirectoryItem, endOfDirectory

plugin = routing.Plugin()

@plugin.route('/')
def index():
    addDirectoryItem(plugin.handle, plugin.url_for(show_category, "one"), ListItem("Category One"), True)
    addDirectoryItem(plugin.handle, plugin.url_for(show_category, "two"), ListItem("Category Two"), True)
    endOfDirectory(plugin.handle)

@plugin.route('/category/<category_id>')
def show_category(category_id):
    addDirectoryItem(plugin.handle, "", ListItem("Hello category %s!" % category_id))
    endOfDirectory(plugin.handle)

if __name__ == '__main__':
    plugin.run()


问:
Approximate pattern matching?
I am trying to write code for Approximate Pattern Matching which is as below:

```<code>def HammingDistance(p, q):
    d = 0
    for p, q in zip(p, q): # your code here
        if p!= q:
            d += 1
    return d
Pattern = "ATTCTGGA"
Text = "CGCCCGAATCCAGAACGCATTCCCATATTTCGGGACCACTGGCCTCCACGGTACGGACGTCAATCAAAT"
d = 3
def ApproximatePatternMatching(Pattern, Text, d):
    positions = [] # initializing list of positions
    for i in range(len(Text) - len(Pattern)+1):
        if Pattern == Text[i:i+len(Pattern)]:
            positions.append(i)# your code here
    return positions
print (ApproximatePatternMatching(Pattern, Text, d))
</code>```

I keep getting the following error:
Failed test #3. You may be failing to account for patterns starting at the first index of text.

Test Dataset:

```<code>GAGCGCTGG
GAGCGCTGGGTTAACTCGCTACTTCCCGACGAGCGCTGTGGCGCAAATTGGCGATGAAACTGCAGAGAGAACTGGTCATCCAACTGAATTCTCCCCGCTATCGCATTTTGATGCGCGCCGCGTCGATT
2
</code>```

Your output:

```<code>['[]', '0']
</code>```

Correct output:

```<code>['0', '30', '66']
</code>```

Can not figure out what I am doing wrong as I am trying to learn python so don't have any idea about programming. Need help?

答:
```<code>def ApproximatePatternMatching(Pattern, Text, d):
    positions = []

    for i in range(len(Text)-len(Pattern)+1):
        x = Text[i:i+len(Pattern)+1]
        if x != Pattern:
            y = HammingDistance(Pattern,x)
            if y <= d:
                positions.append(i)
    return positions

def HammingDistance(p, q):

   count = 0

   for i in range(len(p)):
       x = p[i]
       y = q[i]
       if x != y:
           count = count + 1
   return count
</code>```

Title: Approximate pattern matching?

Body:
I am trying to write code for Approximate Pattern Matching which is as below:

def HammingDistance(p, q):
    d = 0
    for p, q in zip(p, q): # your code here
        if p!= q:
            d += 1
    return d
Pattern = "ATTCTGGA"
Text = "CGCCCGAATCCAGAACGCATTCCCATATTTCGGGACCACTGGCCTCCACGGTACGGACGTCAATCAAAT"
d = 3
def ApproximatePatternMatching(Pattern, Text, d):
    positions = [] # initializing list of positions
    for i in range(len(Text) - len(Pattern)+1):
        if Pattern == Text[i:i+len(Pattern)]:
            positions.append(i)# your code here
    return positions
print (ApproximatePatternMatching(Pattern, Text, d))

I keep getting the following error:
Failed test #3. You may be failing to account for patterns starting at the first index of text.

Test Dataset:

GAGCGCTGG
GAGCGCTGGGTTAACTCGCTACTTCCCGACGAGCGCTGTGGCGCAAATTGGCGATGAAACTGCAGAGAGAACTGGTCATCCAACTGAATTCTCCCCGCTATCGCATTTTGATGCGCGCCGCGTCGATT
2

Your output:

['[]', '0']

Correct output:

['0', '30', '66']

Can not figure out what I am doing wrong as I am trying to learn python so don't have any idea about programming. Need help?


问:
Visual Studio 2017 Slow File Operations (delete, rename, create)
While using Visual Studio 2017 (latest release) as of April 13, when I try to delete or rename a file within vs.net it takes roughly 2-4 minutes to delete the file.  Visual Studio hangs while this file operation is occurring. This does not happen in previously releases of Visual Studio.</p>

答:
The best option for me is to disable source control

Settings -> Source Control -> Nothing.

And use an other source control like smartGit.


问:
Unable to load controller within $routeProvider in AngularJS
This is my very first AngularJs app and created it after going through many examples on the web but I am doing something wrong here. It is highly likely because files are stored in dedicated folders. The HomeView.html template gets loaded fine but the controller doesn't. I mean I cannot get greetingMessage printed in the template. All I see is {{ greetingMessage }} instead of "Welcome!". What am I missing?

Error

```<code>Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.4/$controller/ctrlreg?p0=HomeController
</code>```

App Structure

```<code>app
   conponents
      home
         HomeView.html
         HomeController.js
      ...
   ...
index.js
index.html
</code>```

index.html

```<code><body ng-app="myApp">

    <h3>AngularJS</h3>
    <hr />
    <p><a href="#!">Home</a></p>

    <div ng-view></div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
    <script src="index.js"></script>

</body>
</code>```

index.js

```<code>var module = angular.module('myApp', ['ngRoute']);

module.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'components/home/HomeView.html',
            controller: 'HomeController'
            // I tried -> controller: 'components/home/HomeController'
        })
        .otherwise({
            redirectTo: '/'
        });
});
</code>```

HomeView.html

```<code><div ng-controller="HomeController">
    <h4>Home</h4>
    <p>{{ greetingMessage }}</p>
</div>
</code>```

HomeController.js

```<code>var module = angular.module('myApp', []);
module.controller('HomeController', [
    '$scope',
    function(
        $scope
    ) {
        $scope.greetingMessage = 'Welcome!';
    }]);
</code>```

答:
You must be attach app file and next attache your controller file in your hoem page or master page.

This example helped you
Angular js routing

Body:
This is my very first AngularJs app and created it after going through many examples on the web but I am doing something wrong here. It is highly likely because files are stored in dedicated folders. The HomeView.html template gets loaded fine but the controller doesn't. I mean I cannot get greetingMessage printed in the template. All I see is {{ greetingMessage }} instead of "Welcome!". What am I missing?

Error

Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.4/$controller/ctrlreg?p0=HomeController

App Structure

app
   conponents
      home
         HomeView.html
         HomeController.js
      ...
   ...
index.js
index.html

index.html

AngularJS

Home

index.js

var module = angular.module('myApp', ['ngRoute']);

module.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'components/home/HomeView.html',
            controller: 'HomeController'
            // I tried -> controller: 'components/home/HomeController'
        })
        .otherwise({
            redirectTo: '/'
        });
});

HomeView.html

Home

{{ greetingMessage }}

HomeController.js

var module = angular.module('myApp', []);
module.controller('HomeController', [
    '$scope',
    function(
        $scope
    ) {
        $scope.greetingMessage = 'Welcome!';
    }]);


问:
C# String Equals comparison method fails for strings that have special characters in them
I am currently comparing property values of type string using the string Equals method.

Example: f.rfgmodel.Equals(model, StringComparison.OrdinalIgnoreCase)

Now the problem I am running into is that for strings like ‘M&P9 Shield’ (a Firearm Model stored in my Accessories table in the DB), that has the ‘&’ symbol, the string Equals method doesn’t work.

Sadly, I cannot ignore the  ‘&’ symbol in such model values, so stripping out the ‘&’ symbol from existing DB records in the DB is not an option.

Here is what my code looks like:

```<code>[Route("filter/{pcategory}")]
        public IQueryable<AccessoryDto> GetAccessoryFilter(string pcategory = "", string model = "")
        {
            return db.Accessories.Where(f => (f.rfgacctype.Equals("holsters", StringComparison.OrdinalIgnoreCase) & f.rfgparentcategory.Equals(pcategory, StringComparison.OrdinalIgnoreCase) & f.rfgmodel.Equals(model, StringComparison.OrdinalIgnoreCase)))
            .Select(AsAccessoryDto);
        }
</code>```

Example of my DB table:
Accessory Table

I have searched quite a bit and the few matches don’t have a solution, much less provide enough hints to lead me in the right direction in attempting to resolve my current problem.

Example 1:
C# String comparison fails for string having special character in it
In this particular thread, the user @Biki left a comment to the first answer, stating that the Equals method doesn’t work. This is true.

Example 2: This one didn’t help either: Elastic Search-Search string having spaces and special characters in it using C#

Please if anyone could help with a solution of provide hints pointing me in the right direction.
Thanks in advance. Much appreciated.

答:
Have you looked at the database collation? In my experience, most are set to

Case Insensitive, Accent Sensitive

The following screenshot shows the database properties of one that I work with. The collation is the default, Latin1_General_CI_AS. CI = Case Insensitive, AS = Accent Sensitive. So "user" and "User" will be treated the same whereas "Como" and "Cómo" will be different.

So if that is the case, you can do without the call the .Equals() that specifies StringComparison.OrdinalIgnoreCase because the db is doing that for you. Consider:

```<code>// Search db for items with an ampersand
var item = db.AssetMakes.Where(x => x.Name == "m & n").SingleOrDefault();
Console.WriteLine($"ID: {item?.AssetMakeID}, Name: {item?.Name}");
</code>```

I used that code against my own database that has an item with that name, below is the output that I got. That may help in your case.

Body:
I am currently comparing property values of type string using the string Equals method.

Example: f.rfgmodel.Equals(model, StringComparison.OrdinalIgnoreCase)

Now the problem I am running into is that for strings like ‘M&P9 Shield’ (a Firearm Model stored in my Accessories table in the DB), that has the ‘&’ symbol, the string Equals method doesn’t work.

Sadly, I cannot ignore the  ‘&’ symbol in such model values, so stripping out the ‘&’ symbol from existing DB records in the DB is not an option.

Here is what my code looks like:

[Route("filter/{pcategory}")]
        public IQueryable<AccessoryDto> GetAccessoryFilter(string pcategory = "", string model = "")
        {
            return db.Accessories.Where(f => (f.rfgacctype.Equals("holsters", StringComparison.OrdinalIgnoreCase) & f.rfgparentcategory.Equals(pcategory, StringComparison.OrdinalIgnoreCase) & f.rfgmodel.Equals(model, StringComparison.OrdinalIgnoreCase)))
            .Select(AsAccessoryDto);
        }

Example of my DB table:
Accessory Table

I have searched quite a bit and the few matches don’t have a solution, much less provide enough hints to lead me in the right direction in attempting to resolve my current problem.

Example 1:
C# String comparison fails for string having special character in it
In this particular thread, the user @Biki left a comment to the first answer, stating that the Equals method doesn’t work. This is true.

Example 2: This one didn’t help either: Elastic Search-Search string having spaces and special characters in it using C#

Please if anyone could help with a solution of provide hints pointing me in the right direction.
Thanks in advance. Much appreciated.

Body:
Have you looked at the database collation? In my experience, most are set to

Case Insensitive, Accent Sensitive

The following screenshot shows the database properties of one that I work with. The collation is the default, Latin1_General_CI_AS. CI = Case Insensitive, AS = Accent Sensitive. So "user" and "User" will be treated the same whereas "Como" and "Cómo" will be different.

So if that is the case, you can do without the call the .Equals() that specifies StringComparison.OrdinalIgnoreCase because the db is doing that for you. Consider:

// Search db for items with an ampersand
var item = db.AssetMakes.Where(x => x.Name == "m & n").SingleOrDefault();
Console.WriteLine($"ID: {item?.AssetMakeID}, Name: {item?.Name}");

I used that code against my own database that has an item with that name, below is the output that I got. That may help in your case.


问:
Importance of getting resolved at run-time or compile-time for .GetType () and Typeof () in c#
I recently read and article about .GetType () and Typeof () methods in c#. Now, I know that both of them return System. Type. That article also indicated that it's important to know .GetType () gets resolved at run-time while the other one does at compile-time.

I wonder why it should be considered this fact? Having in mind that the return value of both functions is the same, why we need to know 'when' they get resolved?

Thank you

答:
typeof isn't a method - it's an operator. That's how it's resolved at compile time. They don't do the same thing, in that for typeof you need to know the actual type or type parameter1 you want at compile-time, whereas for GetType you don't. For example:

```<code>Stream x = GetStreamFromSomewhere();
Type t1 = typeof(Stream); // Always exactly System.IO.Stream
Type t2 = x.GetType();    // Never System.IO.Stream
</code>```

t2 can never be System.IO.Stream, because that's an abstract type. It could be System.IO.MemoryStream, System.IO.FileStream, or some kind of stream subclass that didn't even exist when I wrote this code. It's the type of the actual object that the value of x refers to. That will always be a stream of some kind, but we don't know until we ask what the type actually is.

1 If you're using typeof(T) then the actual type isn't know by that piece of code at compile-time, but it's the type argument for any particular call. It's not using the execution-time type of a particular object.

Body:
typeof isn't a method - it's an operator. That's how it's resolved at compile time. They don't do the same thing, in that for typeof you need to know the actual type or type parameter1 you want at compile-time, whereas for GetType you don't. For example:

Stream x = GetStreamFromSomewhere();
Type t1 = typeof(Stream); // Always exactly System.IO.Stream
Type t2 = x.GetType();    // Never System.IO.Stream

t2 can never be System.IO.Stream, because that's an abstract type. It could be System.IO.MemoryStream, System.IO.FileStream, or some kind of stream subclass that didn't even exist when I wrote this code. It's the type of the actual object that the value of x refers to. That will always be a stream of some kind, but we don't know until we ask what the type actually is.

1 If you're using typeof(T) then the actual type isn't know by that piece of code at compile-time, but it's the type argument for any particular call. It's not using the execution-time type of a particular object.


问:
AngularJS and ExpressJS session management?
I would like to keep session across all the page.  For this project, I am using expressJs, nodeJS as server side. AngularJS in front end.

I am not sure, how to handle session when view changes or url changes. Because I need to take care of both expressJS router or angularJs router.

What approach should I follow?

angularJS router

```<code>     myApp.config(['$routeProvider', function($routeProvider) {

    $routeProvider.when('/welcome', {templateUrl: 'partials/welcome.html', controller: 'MyCtrl2'});
    $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'MyCtrl2'});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', controller: 'singupController'});
    $routeProvider.otherwise({redirectTo: '/'});
  }]);
</code>```

Signup controller

```<code>myApp.controller('singupController',function($scope,$rootScope,$http){

    $scope.doSingnup = function() {

       var formData = {
          'username' : this.username,
          'password' : this.password,
           'email' : null
      };

      var jdata = JSON.stringify(formData);

      $http({method:'POST',url:'/signup',data:jdata})
      .success(function(data,status,headers,config){

                console.log(data);

      }).
      error(function(data,status,headers,config){

        console.log(data)

      });
    }
  })
</code>```

ExpressJS router

```<code>    module.exports = exports = function(app, db) {

    var sessionHandler = new SessionHandler(db);
    var contentHandler = new ContentHandler(db);

    // Middleware to see if a user is logged in
    app.use(sessionHandler.isLoggedInMiddleware);

    app.get('/', contentHandler.displayMainPage);

    app.post('/login', sessionHandler.handleLoginRequest);

    app.get('/logout', sessionHandler.displayLogoutPage);

    app.get("/welcome", sessionHandler.displayWelcomePage);

    app.post('/signup', sessionHandler.handleSignup);

    app.get('*', contentHandler.displayMainPage);

    // Error handling middleware
    app.use(ErrorHandler);
}
</code>```

After signup, I would like to redirect to the login page. How can I do that in the above router. which one of the following  should I use to change the view of app

          1) $location of angularJS

          2) redirect of ExpressJS

答:
Of all the answers here, I like @alknows's approach best. However, like the other answers that suggest you send a request to the server to get the current user data, there are a couple issues I take with them:

You have to deal with race conditions as a result of your AJAX ($http) call.

You're sending an unnecessary request to the server after it already rendered your index.html

I tried @alknow's approach and it worked out for me after I was able to resolve the many race conditions that came up as a result of my angular app controllers and config needing the current user to do their job. I try my best to avoid race conditions when appropriate, so I was a bit reluctant to continue with this approach. So I thought of a better approach: send the current user data down with your index.html and store it locally.

My Approach: Embed currentUser in index.html & store locally on client

In index.html on your server, make a script tag to hold whatever data you want to pass to the client:

```</p>

```

```

<p>```

Then, as @alknows suggested, in app.js or wherever you initiate your angular app, add app.run(..., () => {...}). In app.run(), you will want to grab the server side rendered client data object, which I named obscurely __ssr_CData so that I am less likely to run into name collisions across the global namespace later in my other javascript:

```<code>var myAngularApp = angular.module("mainApp", ['ngRoute']);

myAngularApp.run(function ($rootScope) {
    const currentUserFromServer = __ssr__CData.currentUser
    const currentUserAccessTokenFromServer = __ssr__CData.accessToken
    const currentUser =
    CurrentUser.set(currentUserAccessTokenFromServer, currentUserFromServer)
    $rootScope.currentUser = currentUser
});
</code>```

As you know app.run() will be called whenever the page does a full reload. CurrentUser is a global class for managing my angular app's current user in the single page environment. So when I call CurrentUser.set(...) it stores the current user data in a place I can retrieve later in my angular app by calling CurrentUser.get(). So in any of your angular app controller's you can now retrieve the current user the server provided by simply doing this:

```<code>myAngularApp.controller('loginController',function($scope, $rootScope, $http){
   //check if the user is already logged in:
   var currentUser = CurrentUser.get()
   if(currentUser) {
       alert("HEY! You're already logged in as " +currentUser.username)
      return $window.location.href = "/";
   }

   //there is no current user, so let user log in
   //...
}
</code>```

In that example, I made use of CurrentUser.get(), which I explained above, to get the previously stored current user from the server. I could have also retrieved that current user by accessing $rootScope.currentUser because I stored it there, too. It's up to you.

```<code>myAngularApp.controller('signupController',function($scope, $rootScope, $http){
   //check if the user is already logged in:
   var currentUser = CurrentUser.get()
   if(currentUser) {
       alert("HEY! You're already logged in as " +currentUser.username)
      return $window.location.href = "/";
   }

   //there is no current user, so let user signup
   //... you run your signup code after getting form data
   $http({method:'POST',url:'/signup',data:jdata})
       .success(function(data,status,headers,config){
           //signup succeeded!
           //set the current user locally just like in app.js
           CurrentUser.set(data.newUser)
           //send user to profile
           return $window.location.href = "/profile";
       })
       .error(function(data,status,headers,config){
           //something went wrong
           console.log(data)
      });

}
</code>```

Now, after a new user has signed up, your server returned the new user from the AJAX call. We set that new user as the current user by calling CurrentUser.set(...) and send the user to their profile. You can now get the current user in the profile controller the same way you did to check if the current user existed in the login and signup controllers.

I hope this helps anyone who comes across this. For your reference, I'm using the client-sessions module to handle sessions on my server.

ContentLicense: CC BY-SA 4.0

Body:
I would like to keep session across all the page.  For this project, I am using expressJs, nodeJS as server side. AngularJS in front end.

I am not sure, how to handle session when view changes or url changes. Because I need to take care of both expressJS router or angularJs router.

What approach should I follow?

angularJS router

     myApp.config(['$routeProvider', function($routeProvider) {

    $routeProvider.when('/welcome', {templateUrl: 'partials/welcome.html', controller: 'MyCtrl2'});
    $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'MyCtrl2'});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', controller: 'singupController'});
    $routeProvider.otherwise({redirectTo: '/'});
  }]);

Signup controller

myApp.controller('singupController',function($scope,$rootScope,$http){

    $scope.doSingnup = function() {

       var formData = {
          'username' : this.username,
          'password' : this.password,
           'email' : null
      };

      var jdata = JSON.stringify(formData);

      $http({method:'POST',url:'/signup',data:jdata})
      .success(function(data,status,headers,config){

                console.log(data);

      }).
      error(function(data,status,headers,config){

        console.log(data)

      });
    }
  })

ExpressJS router

    module.exports = exports = function(app, db) {

    var sessionHandler = new SessionHandler(db);
    var contentHandler = new ContentHandler(db);

    // Middleware to see if a user is logged in
    app.use(sessionHandler.isLoggedInMiddleware);

    app.get('/', contentHandler.displayMainPage);

    app.post('/login', sessionHandler.handleLoginRequest);

    app.get('/logout', sessionHandler.displayLogoutPage);

    app.get("/welcome", sessionHandler.displayWelcomePage);

    app.post('/signup', sessionHandler.handleSignup);

    app.get('*', contentHandler.displayMainPage);

    // Error handling middleware
    app.use(ErrorHandler);
}

After signup, I would like to redirect to the login page. How can I do that in the above router. which one of the following  should I use to change the view of app

          1) $location of angularJS

          2) redirect of ExpressJS

Body:
Of all the answers here, I like @alknows's approach best. However, like the other answers that suggest you send a request to the server to get the current user data, there are a couple issues I take with them:

You have to deal with race conditions as a result of your AJAX ($http) call.

You're sending an unnecessary request to the server after it already rendered your index.html

I tried @alknow's approach and it worked out for me after I was able to resolve the many race conditions that came up as a result of my angular app controllers and config needing the current user to do their job. I try my best to avoid race conditions when appropriate, so I was a bit reluctant to continue with this approach. So I thought of a better approach: send the current user data down with your index.html and store it locally.

My Approach: Embed currentUser in index.html & store locally on client

In index.html on your server, make a script tag to hold whatever data you want to pass to the client:

```</p>

<pre><code><!--YOUR OTHER index.html stuff go above here-->
<script id="server-side-rendered-client-data" type="text/javascript">
    var __ssr__CData = {
        currentUser: { id: '12345', username: 'coolguy', etc: 'etc.' }
    }
</script>
</code></pre>

<p>```

Then, as @alknows suggested, in app.js or wherever you initiate your angular app, add app.run(..., () => {...}). In app.run(), you will want to grab the server side rendered client data object, which I named obscurely __ssr_CData so that I am less likely to run into name collisions across the global namespace later in my other javascript:

var myAngularApp = angular.module("mainApp", ['ngRoute']);

myAngularApp.run(function ($rootScope) {
    const currentUserFromServer = __ssr__CData.currentUser
    const currentUserAccessTokenFromServer = __ssr__CData.accessToken
    const currentUser =
    CurrentUser.set(currentUserAccessTokenFromServer, currentUserFromServer)
    $rootScope.currentUser = currentUser
});

As you know app.run() will be called whenever the page does a full reload. CurrentUser is a global class for managing my angular app's current user in the single page environment. So when I call CurrentUser.set(...) it stores the current user data in a place I can retrieve later in my angular app by calling CurrentUser.get(). So in any of your angular app controller's you can now retrieve the current user the server provided by simply doing this:

myAngularApp.controller('loginController',function($scope, $rootScope, $http){
   //check if the user is already logged in:
   var currentUser = CurrentUser.get()
   if(currentUser) {
       alert("HEY! You're already logged in as " +currentUser.username)
      return $window.location.href = "/";
   }

   //there is no current user, so let user log in
   //...
}

In that example, I made use of CurrentUser.get(), which I explained above, to get the previously stored current user from the server. I could have also retrieved that current user by accessing $rootScope.currentUser because I stored it there, too. It's up to you.

myAngularApp.controller('signupController',function($scope, $rootScope, $http){
   //check if the user is already logged in:
   var currentUser = CurrentUser.get()
   if(currentUser) {
       alert("HEY! You're already logged in as " +currentUser.username)
      return $window.location.href = "/";
   }

   //there is no current user, so let user signup
   //... you run your signup code after getting form data
   $http({method:'POST',url:'/signup',data:jdata})
       .success(function(data,status,headers,config){
           //signup succeeded!
           //set the current user locally just like in app.js
           CurrentUser.set(data.newUser)
           //send user to profile
           return $window.location.href = "/profile";
       })
       .error(function(data,status,headers,config){
           //something went wrong
           console.log(data)
      });

}

Now, after a new user has signed up, your server returned the new user from the AJAX call. We set that new user as the current user by calling CurrentUser.set(...) and send the user to their profile. You can now get the current user in the profile controller the same way you did to check if the current user existed in the login and signup controllers.

I hope this helps anyone who comes across this. For your reference, I'm using the client-sessions module to handle sessions on my server.