问:
Using jQuery to add content to multiple elements returned by find()
How can I add content to the second and third td?

I just found that the following will not work.  I can find a way by creating some variable to hold the found elements, but would like to learn cleaner "more jQueryish" way if available.

```<code><tr id="clone"><td></td><td></td><td></td></tr>

$.each(records, function( index, row ) {
    $('#clone').clone()
    .removeAttr('id')
    .find('td')
    .eq(1).text(row.name).parent()
    .eq(2).text(row.message).parent()
    .appendTo(content)
});
</code>```

答:
It would be much easier to read in the future by storing  variables for the clone and the td's obtained by find() instead of trying to make one long chain

```<code>$.each(records, function( index, row ) {
    var $clone = $('#clone').clone().removeAttr('id');
    var $td = $clone.find('td');
    $td.eq(1).text(row.name);
    $td.eq(2).text(row.message);
    content.append( $clone);
});
</code>```

Note the amount of code is not significantly different in length

Body:
How can I add content to the second and third td?

I just found that the following will not work.  I can find a way by creating some variable to hold the found elements, but would like to learn cleaner "more jQueryish" way if available.

$.each(records, function( index, row ) {
    $('#clone').clone()
    .removeAttr('id')
    .find('td')
    .eq(1).text(row.name).parent()
    .eq(2).text(row.message).parent()
    .appendTo(content)
});

Body:
It would be much easier to read in the future by storing  variables for the clone and the td's obtained by find() instead of trying to make one long chain

$.each(records, function( index, row ) {
    var $clone = $('#clone').clone().removeAttr('id');
    var $td = $clone.find('td');
    $td.eq(1).text(row.name);
    $td.eq(2).text(row.message);
    content.append( $clone);
});

Note the amount of code is not significantly different in length


来源: stackexchange

问:
Javascript - How to remove all active classes unless the element being clicked on already has a active class
```<code>    const offCanvasLinks = document.querySelectorAll('.off-canvas__link');

    [].forEach.call(offCanvasLinks, function(link) {
        link.addEventListener('click', (event) => {
            const typeVal = link.getAttribute('data-type')

            if (typeVal === "star") {
                document.querySelector('[data-star-links]').classList.toggle('active');
            } else if (typeVal === "how-to") {
                document.querySelector('[data-how-to]').classList.toggle('active');
            } else {
                document.querySelector('[data-presenters]').classList.toggle('active');
            }
        })
    });
</code>```

I have the above code that clicks on a navigation to toggle a class of active.

If I click on another element in the navigation I need to remove all active classes unless the clicked on element already has a active class.

In Jquery this is super easy with the ability to use .not(). Where you can just past through the event target to check and remove all other active classes.

So to make this more clear what I'm looking for is a way to remove all active classes unless the element being clicked has already got an active class.

Let me know your thoughts

*********** UPDATE ******************
Ok...
Click on a link at the bottom it'll show a screen nicely if you then click on another link it will close the previous one then open the next one. HOWEVER if you click on the same link it does not close the menu.

how do I remove the class if it is already open?

Link: https://jsfiddle.net/2oqm0r2n/3/

答:
maybe something like this?

for example:

```<code>// unless the clicked on element has already an active class
if(!link.classList.contains('active')){
    // remove all active classes
    var actives = document.querySelectorAll('.active');
    [].forEach.call(actives, function(elem) {
        elem.classList.remove("active");
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
    const offCanvasLinks = document.querySelectorAll('.off-canvas__link');

    [].forEach.call(offCanvasLinks, function(link) {
        link.addEventListener('click', (event) => {
            const typeVal = link.getAttribute('data-type')

            if (typeVal === "star") {
                document.querySelector('[data-star-links]').classList.toggle('active');
            } else if (typeVal === "how-to") {
                document.querySelector('[data-how-to]').classList.toggle('active');
            } else {
                document.querySelector('[data-presenters]').classList.toggle('active');
            }
        })
    });

I have the above code that clicks on a navigation to toggle a class of active.

If I click on another element in the navigation I need to remove all active classes unless the clicked on element already has a active class.

In Jquery this is super easy with the ability to use .not(). Where you can just past through the event target to check and remove all other active classes.

So to make this more clear what I'm looking for is a way to remove all active classes unless the element being clicked has already got an active class.

Let me know your thoughts

*********** UPDATE ******************
Ok...
Click on a link at the bottom it'll show a screen nicely if you then click on another link it will close the previous one then open the next one. HOWEVER if you click on the same link it does not close the menu.

how do I remove the class if it is already open?

Link: https://jsfiddle.net/2oqm0r2n/3/

Body:
maybe something like this?

for example:

// unless the clicked on element has already an active class
if(!link.classList.contains('active')){
    // remove all active classes
    var actives = document.querySelectorAll('.active');
    [].forEach.call(actives, function(elem) {
        elem.classList.remove("active");
    });
}


问:
How to learn CouchDB API without documentation?
Since CouchDB has very few API documentation (at least I can not find it), I would like to inspect some JavaScript objecs myself. What is the best way to do this?

For example, show functions recive the request object req as argument. How to find out, which properties (cookies, requested url,...) this request object precisely has?

答:
For your specific question - how to write _show functions - see the relevant documentation in the CouchDB Wiki: Formatting with Show and List.  That document then cross-references to the External Processes documentation for details on the request object.  In general, the wiki is a treasure trove of information - most of the API documentation is there.  It can just take some looking.

You can also experiment directly with JavaScript, as indicated by Nathan.  You could write a show function that just stringifies the parameters (with JSON.stringify()) and displays them so you can see what they actually are.

ContentLicense: CC BY-SA 2.5


问:
Flood Fill algorithm, works for a few seconds but then errors out. (pygame)
Trying to implement flood fill algorithm in pygame just as a learning experience. I have a good start I think and it is mostly functional, but after several seconds of working properly, it gives me a  max recursion depth error.

```<code>import pygame, random, math
from pygame.locals import *

class GameMain():
done = False
color_bg = Color('white')

def __init__(self, width=800, height=800):
    pygame.init()

    self.width, self.height = width, height
    self.screen = pygame.display.set_mode((self.width, self.height))
    self.clock = pygame.time.Clock()

def main_loop(self):
    while not self.done:
        self.handle_events()
        self.draw()
        self.clock.tick(60)
    pygame.quit()

def draw(self):
    self.screen.fill(self.color_bg)
    pygame.draw.rect(self.screen,Color("grey30"), [100,100,400,300],2)
    pygame.draw.rect(self.screen,Color("grey30"), [ 300,300,400,300],2)
    pygame.display.flip()

def handle_events(self):
    events = pygame.event.get()

    # keystates
    keys = pygame.key.get_pressed()

    # events
    for event in events:
        if event.type == pygame.QUIT:
            self.done = True
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                self.done = True
        if event.type == MOUSEBUTTONDOWN:
            x,y = pygame.mouse.get_pos()
            coord = [x,y]
            self.flood_fill(self.screen,coord)
def flood_fill(self,screen,coord):

    if screen.get_at((coord[0],coord[1])) == Color("grey30"):
        return
    screen.set_at((coord[0],coord[1]),Color("grey30"))
    pygame.display.flip()
    self.flood_fill(self.screen, [coord[0] +1, coord[1]])
    self.flood_fill(self.screen, [coord[0] -1, coord[1]])
    self.flood_fill(self.screen, [coord[0], coord[1]+1])
    self.flood_fill(self.screen, [coord[0], coord[1]-1])

if __name__ == "__main__":
game = GameMain()
game.main_loop()
</code>```

My program runs for a second or two and changes the color of a few x,y coordinates, but then it goes crazy and I get a recursion depth error. Not sure why it works for a second and then fails.

答:
Python isn't particularly designed or inclined to recursion operations. In the CPython implementation, the recursion depth is limited to 1000.

You can check this via:

```<code>import sys
print(sys.getrecursionlimit())
</code>```

Consequently, you can override the limit by using sys.setrecursionlimit() instead.

However, that's not particularly the safe/best option.

You're better off in rewriting your code to have an iterative implementation.

EDIT: Apologies, I realized I haven't pointed where you should look at the code.

The recursion actually happens in your flood_fill() method, as it actually calls self.floor_fill() again four (4) times.

For more info, you can read up: http://seriously.dontusethiscode.com/2013/04/14/setrecursionlimit.html

Body:
Trying to implement flood fill algorithm in pygame just as a learning experience. I have a good start I think and it is mostly functional, but after several seconds of working properly, it gives me a  max recursion depth error.

import pygame, random, math
from pygame.locals import *

class GameMain():
done = False
color_bg = Color('white')

def __init__(self, width=800, height=800):
    pygame.init()

    self.width, self.height = width, height
    self.screen = pygame.display.set_mode((self.width, self.height))
    self.clock = pygame.time.Clock()

def main_loop(self):
    while not self.done:
        self.handle_events()
        self.draw()
        self.clock.tick(60)
    pygame.quit()

def draw(self):
    self.screen.fill(self.color_bg)
    pygame.draw.rect(self.screen,Color("grey30"), [100,100,400,300],2)
    pygame.draw.rect(self.screen,Color("grey30"), [ 300,300,400,300],2)
    pygame.display.flip()

def handle_events(self):
    events = pygame.event.get()

    # keystates
    keys = pygame.key.get_pressed()

    # events
    for event in events:
        if event.type == pygame.QUIT:
            self.done = True
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                self.done = True
        if event.type == MOUSEBUTTONDOWN:
            x,y = pygame.mouse.get_pos()
            coord = [x,y]
            self.flood_fill(self.screen,coord)
def flood_fill(self,screen,coord):

    if screen.get_at((coord[0],coord[1])) == Color("grey30"):
        return
    screen.set_at((coord[0],coord[1]),Color("grey30"))
    pygame.display.flip()
    self.flood_fill(self.screen, [coord[0] +1, coord[1]])
    self.flood_fill(self.screen, [coord[0] -1, coord[1]])
    self.flood_fill(self.screen, [coord[0], coord[1]+1])
    self.flood_fill(self.screen, [coord[0], coord[1]-1])

if __name__ == "__main__":
game = GameMain()
game.main_loop()

My program runs for a second or two and changes the color of a few x,y coordinates, but then it goes crazy and I get a recursion depth error. Not sure why it works for a second and then fails.

Body:
Python isn't particularly designed or inclined to recursion operations. In the CPython implementation, the recursion depth is limited to 1000.

You can check this via:

import sys
print(sys.getrecursionlimit())

Consequently, you can override the limit by using sys.setrecursionlimit() instead.

However, that's not particularly the safe/best option.

You're better off in rewriting your code to have an iterative implementation.

EDIT: Apologies, I realized I haven't pointed where you should look at the code.

The recursion actually happens in your flood_fill() method, as it actually calls self.floor_fill() again four (4) times.

For more info, you can read up: http://seriously.dontusethiscode.com/2013/04/14/setrecursionlimit.html


问:
SQL Server where clause order count > 0
I have a query that works but returns all students, whether they place orders or not.  I just want those with orders.  The query works fine until I add the where clause.  How can I properly write this?</p>

```<code>SELECT top 100 percent s.id, s.fname as [First Name], s.lname as [Last Name],
(select count(student_id) from orderX x where x.student_id=s.id) as [Order Count],
(select sum(no_attendees) from orderX x where x.student_id=s.id) as [Attendees / Participants],
(select sum(eventHours) from orderX x where x.student_id=s.id) as [Event Hours],
oc1.text as [Occupation 1], oc2.text as [Occupation 2],
oc3.text as [Occupation 3], s.OccupationOther, s.dateGraduated, s.organization, s.city, s.zip, s.st, s.county,
aud.text as [Preferred Audience], pts.text as [Plans to Share], mr.text as [Main Reason]
FROM  student s
left join occupation1 oc1 on s.Occupation1 = oc1.id
left  join occupation2 oc2 on s.Occupation2 = oc2.id
left  join occupation3 oc3 on s.Occupation3 = oc3.id
left  join audience aud on s.audience = aud.id
left  join PlanToShare pts on s.PlanToShare = pts.id
left  join mainReason mr on s.mainReason = mr.id

where [Order Count] > 0
</code>```

答:
For starters you could replace your where clause by

where (select count(student_id) from orderX x where x.student_id=s.id) > 0

Title: SQL Server where clause order count > 0

Body:
I have a query that works but returns all students, whether they place orders or not.  I just want those with orders.  The query works fine until I add the where clause.  How can I properly write this?

SELECT top 100 percent s.id, s.fname as [First Name], s.lname as [Last Name],
(select count(student_id) from orderX x where x.student_id=s.id) as [Order Count],
(select sum(no_attendees) from orderX x where x.student_id=s.id) as [Attendees / Participants],
(select sum(eventHours) from orderX x where x.student_id=s.id) as [Event Hours],
oc1.text as [Occupation 1], oc2.text as [Occupation 2],
oc3.text as [Occupation 3], s.OccupationOther, s.dateGraduated, s.organization, s.city, s.zip, s.st, s.county,
aud.text as [Preferred Audience], pts.text as [Plans to Share], mr.text as [Main Reason]
FROM  student s
left join occupation1 oc1 on s.Occupation1 = oc1.id
left  join occupation2 oc2 on s.Occupation2 = oc2.id
left  join occupation3 oc3 on s.Occupation3 = oc3.id
left  join audience aud on s.audience = aud.id
left  join PlanToShare pts on s.PlanToShare = pts.id
left  join mainReason mr on s.mainReason = mr.id

where [Order Count] > 0


问:
What is a preferred way of closing a third-application thread without waiting for it to complete?
I am currently running the JAR that I cannot change, and sometimes it simply gets stuck for no good reason. I have tried finding the ways to interrupt the thread, stop the thread, etceteras, but no luck.

Each solution offered was about doing the complete exit or waiting for a thread to complete.

What I want to do is to simply close the thread, exactly when the timeout completes, and carry on with the program.

What I do not want to do is use the while loop with a timeout, java.util.concurrent.Future, System.exit, and make a Thread.interrupt call.

None of these will help!

答:
You can't forcibly stop a thread in mid-execution.  The Thread.destroy() method would have done that, but it was never implemented, and its documentation explains why it would be unsafe to use even if it worked.

There are some other deprecated methods like Thread.stop() and Thread.suspend() which may actually work, but they're also unsafe to use; again, their documentation explains why.

Telling the thread that it should terminate itself, and then waiting for it to do so, is the only safe way to stop a thread.

As an workaround, you could run your task in an entirely separate process, so that you can destroy it when you want it to stop.  That is safe, since processes are isolated from each other and destroying the child process can't leave the parent process in an unstable state.

Interacting with a separate process is more difficult, though, since you can't share variables between processes like you can with threads.  You'd need to send messages through the process's input and output streams.


问:
Is it possible to stack a list of ragged arrays (where each array in the list is of size 1 row and n columns)?
I have a list of arrays.

```<code>[array([   2.,    4.,    6.,    8.,   10.,   12.,   14.,   16.,   18.,
         20.,   22.,   24.,   26.,   28.,   30.,   32.,   34.,   36.,
         38.,   40.,   42.,   44.,   46.,   48.,   50.,   52.,   54.,
         56.,   58.,   60.,   62.,   64.,   66.,   68.,   70.,   72.,
         74.,   76.,   78.,   80.,   82.,   84.,   86.,   88.,   90.,
         92.,   94.,   96.,   98.,  100.]), array([   4.,    8.,   12.,   16.,   20.,   24.,   28.,   32.,   36.,
         40.,   44.,   48.,   52.,   56.,   60.,   64.,   68.,   72.,
         76.,   80.,   84.,   88.,   92.,   96.,  100.]), array([  8.,  16.,  24.,  32.,  40.,  48.,  56.,  64.,  72.,  80.,  88.,
        96.])]
</code>```

I have tried np.vstack to stack the list array by array. But because the arrays are not of equal size (ie, different number of columns), I received this error:

```<code>ValueError: all the input array dimensions except for the concatenation axis must match exactly
</code>```

I do not want to concatenate them because I want to store the rows for future computations. How can I stack them row by row if the rows are ragged?

Edit: Is it possible to concatenate along a variable axis for this purpose?

答:
You could use a pandas DataFrame:

```<code>import pandas as pd
data = pd.DataFrame([pd.Series(i) for i in yourlist])
</code>```

The result will be something like this:

The drawback is that you will have to deal with the missing values while doing your calculations.

Body:
I have a list of arrays.

[array([   2.,    4.,    6.,    8.,   10.,   12.,   14.,   16.,   18.,
         20.,   22.,   24.,   26.,   28.,   30.,   32.,   34.,   36.,
         38.,   40.,   42.,   44.,   46.,   48.,   50.,   52.,   54.,
         56.,   58.,   60.,   62.,   64.,   66.,   68.,   70.,   72.,
         74.,   76.,   78.,   80.,   82.,   84.,   86.,   88.,   90.,
         92.,   94.,   96.,   98.,  100.]), array([   4.,    8.,   12.,   16.,   20.,   24.,   28.,   32.,   36.,
         40.,   44.,   48.,   52.,   56.,   60.,   64.,   68.,   72.,
         76.,   80.,   84.,   88.,   92.,   96.,  100.]), array([  8.,  16.,  24.,  32.,  40.,  48.,  56.,  64.,  72.,  80.,  88.,
        96.])]

I have tried np.vstack to stack the list array by array. But because the arrays are not of equal size (ie, different number of columns), I received this error:

ValueError: all the input array dimensions except for the concatenation axis must match exactly

I do not want to concatenate them because I want to store the rows for future computations. How can I stack them row by row if the rows are ragged?

Edit: Is it possible to concatenate along a variable axis for this purpose?

Body:
You could use a pandas DataFrame:

import pandas as pd
data = pd.DataFrame([pd.Series(i) for i in yourlist])

The result will be something like this:

The drawback is that you will have to deal with the missing values while doing your calculations.


问:
What is the use of BaseColumns in Android
What is the use of implementing a class from BaseColumns in Android?

答:
The BaseColumn interface only provides the column names _ID and _COUNT.  You must still specify columns that use them when constructing tables.  For example, to create a column using the column name _ID you might do the following:

```<code>public static final String CREATE_TABLE =
    "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ("
    + _ID + " INTEGER PRIMARY KEY, "
    + USERNAME + " TEXT NOT NULL, "
    + PASSWORD + " TEXT NOT NULL, "
    + EMAIL + " TEXT NOT NULL UNIQUE)";
</code>```

Body:
The BaseColumn interface only provides the column names _ID and _COUNT.  You must still specify columns that use them when constructing tables.  For example, to create a column using the column name _ID you might do the following:

public static final String CREATE_TABLE =
    "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ("
    + _ID + " INTEGER PRIMARY KEY, "
    + USERNAME + " TEXT NOT NULL, "
    + PASSWORD + " TEXT NOT NULL, "
    + EMAIL + " TEXT NOT NULL UNIQUE)";


问:
JavaScript function in function, returning and accessing a value
Im totally new to JavaScript but my friend asked me for help. Im wondering if something like this would be possible in JS?

If the value of project is "garden"

I should get couple values for example for a name:

Garden Project

I tried that:

```<code>var myProject="garden";
ProjectNew.detectTemplate(myProject).choosenProject.name;
</code>```

Im getting:

```<code>Unexpected exception 'ReferenceError: ProjectsNew is not defined
</code>```

But it doesn't work. Is it possible what I described and would like to do in JS?

```<code>var ProjectNew = function() {

   function detectTemplate(project) {

      if (project=='garden'){
        var choosenProject = {
          name: "Garden Project",
          description: "sample description'",
          ansprechpartner: "Greg",
          branche: "shoping",
          partner: "'Stihl",
          technik: 'lawn mover selling'
          };
          return choosenProject;
       }
       }
        return {
               detectTemplate: detectTemplate
      }

}();
</code>```

答:
Your code mostly works. There are just two parts you missed:

Since you are defining ProjectNew using an assignment statement, you need to assign it before you try to use it. The error you are seeing means that it does not yet have a value when you are attempting to use it (or it is not within the scope where you are trying to use it).

detectTemplate() returns the choosenProject itself, not an object with a property named choosenProject, so you need to remove that portion from your series of property accesses.

Working code:

var ProjectNew = function() {
  function detectTemplate(project) {

    if (project == 'garden') {
      var choosenProject = {
        name: "Garden Project",
        description: "sample description'",
        ansprechpartner: "Greg",
        branche: "shoping",
        partner: "'Stihl",
        technik: 'lawn mover selling'
      };
      return choosenProject;
    }
  }
  return {
    detectTemplate: detectTemplate
  }

}();
var myProject = "garden";
console.log(ProjectNew.detectTemplate(myProject).name);```

Body:
Im totally new to JavaScript but my friend asked me for help. Im wondering if something like this would be possible in JS?

If the value of project is "garden"

I should get couple values for example for a name:

Garden Project

I tried that:

var myProject="garden";
ProjectNew.detectTemplate(myProject).choosenProject.name;

Im getting:

Unexpected exception 'ReferenceError: ProjectsNew is not defined

But it doesn't work. Is it possible what I described and would like to do in JS?

var ProjectNew = function() {

   function detectTemplate(project) {

      if (project=='garden'){
        var choosenProject = {
          name: "Garden Project",
          description: "sample description'",
          ansprechpartner: "Greg",
          branche: "shoping",
          partner: "'Stihl",
          technik: 'lawn mover selling'
          };
          return choosenProject;
       }
       }
        return {
               detectTemplate: detectTemplate
      }

}();


问:
How to auto-submit a Drupal webform?
I am using Drupal webform and wonder whether it's possible to auto-submit a Webform?

Since Webform comes with %get[key] to fill the form fields by default values from a FORM GET URL, and so I'd like to save the user a submit button click. Possible? Thanks!

答: You'll want to create a Drupal behavior in Javascript that applies some kind of logic to the check the form elements (i.e., submit once fields x, y, and z are filled in by the user).  Because Drupal uses the jQuery form plugin, you can background submit the form with ajaxSubmit or simply trigger the form's submit event.</p>

Title: How to auto-submit a Drupal webform?


问:
How can I stop the browser back button using JavaScript?
I am doing an online quiz application in PHP. I want to restrict the user from going back in an exam.

I have tried the following script, but it stops my timer.

What should I do?

The timer is stored in file cdtimer.js.

```

I have the exam timer which takes a duration for the exam from a MySQL value. The timer starts accordingly, but it stops when I put the code in for disabling the back button. What is my problem?

答:
Very simple and clean function to break the back arrow without interfering with the page afterward.

Benefits:

Loads instantaneously and restores original hash, so the user isn't distracted by URL visibly changing.

The user can still exit by pressing back 10 times (that's a good thing), but not accidentally

No user interference like other solutions using onbeforeunload

It only runs once and doesn't interfere with further hash manipulations in case you use that to track state

Restores original hash, so almost invisible.

Uses setInterval, so it doesn't break slow browsers and always works.

Pure JavaScript, does not require HTML5 history, works everywhere.

Unobtrusive, simple, and plays well with other code.

Does not use unbeforeunload which interrupts user with modal dialog.

It just works without fuss.

Note: some of the other solutions use onbeforeunload. Please do not use onbeforeunload for this purpose, which pops up a dialog whenever users try to close the window, hit backarrow, etc. Modals like onbeforeunload are usually only appropriate in rare circumstances, such as when they've actually made changes on screen and haven't saved them, not for this purpose.

How It Works

Executes on page load

Saves your original hash (if one is in the URL).

Sequentially appends #/noop/{1..10} to the hash

Restores the original hash

That's it. No further messing around, no background event monitoring, nothing else.

Use It In One Second

To deploy, just add this anywhere on your page or in your JavaScript code:

```

ContentLicense: CC BY-SA 4.0

Body:
I am doing an online quiz application in PHP. I want to restrict the user from going back in an exam.

I have tried the following script, but it stops my timer.

What should I do?

The timer is stored in file cdtimer.js.

I have the exam timer which takes a duration for the exam from a MySQL value. The timer starts accordingly, but it stops when I put the code in for disabling the back button. What is my problem?

Body:
Very simple and clean function to break the back arrow without interfering with the page afterward.

Benefits:

Loads instantaneously and restores original hash, so the user isn't distracted by URL visibly changing.

The user can still exit by pressing back 10 times (that's a good thing), but not accidentally

No user interference like other solutions using onbeforeunload

It only runs once and doesn't interfere with further hash manipulations in case you use that to track state

Restores original hash, so almost invisible.

Uses setInterval, so it doesn't break slow browsers and always works.

Pure JavaScript, does not require HTML5 history, works everywhere.

Unobtrusive, simple, and plays well with other code.

Does not use unbeforeunload which interrupts user with modal dialog.

It just works without fuss.

Note: some of the other solutions use onbeforeunload. Please do not use onbeforeunload for this purpose, which pops up a dialog whenever users try to close the window, hit backarrow, etc. Modals like onbeforeunload are usually only appropriate in rare circumstances, such as when they've actually made changes on screen and haven't saved them, not for this purpose.

How It Works

Executes on page load

Saves your original hash (if one is in the URL).

Sequentially appends #/noop/{1..10} to the hash

Restores the original hash

That's it. No further messing around, no background event monitoring, nothing else.

Use It In One Second

To deploy, just add this anywhere on your page or in your JavaScript code:

<script>
    /* Break back button */
    window.onload = function(){
      var i = 0;
      var previous_hash = window.location.hash;
      var x = setInterval(function(){
        i++;
        window.location.hash = "/noop/" + i;
        if (i==10){
          clearInterval(x);
          window.location.hash = previous_hash;
        }
      }, 10);
    }
</script>


问:
How can I hide FAB button while playing video fullscreen?
How to hide fab button while i play video in fullscreen? Show button until video goes fullscreen. I have a webview app with fab button.</p>

答: fab.setVisibility() (mentioned in another answer) works fine for making the button simply disappear, but if you want if you want the button to animate it would be better to use fab.hide() and fab.show() instead.


问:
SQLite.Interop unable to delete file on clean of solution
I'm using the Nuget package System.Data.SQLite in an MVC web application. There seems to be lock issue when I try to clean the solution and rebuild. The error message I get is:
Unable to delete file "bin\x64\SQLite.Interop.dll". Access to the path '\bin\x64\SQLite.Interop.dll' is denied.

I'm thinking that the database is either still open or that the .dll is still in use, but I can't find any documentation or any reference to the same problem. This question  seems like a similar issue but doesn't provide a resolution to my problem.

Here is a code snippet that I'm using to write to the SQLite database:

```<code>        var conn = new SQLiteConnection("Data Source=" + connectionString);
        conn.Open();

        var debugEntriesTableQuery = "CREATE TABLE ...";

        var cmd = conn.CreateCommand();

        cmd.CommandText = debugEntriesTableQuery;

        cmd.ExecuteNonQuery();

        conn.Close();
</code>```

Is there another step needed to properly close the connection to the database and inform the dll and the connection has closed?

I am using this code inside a data solution that I have added to a nuget package and am using in another solution. I am only having this problem when building/cleaning the solution that is using my nuget package.

答: Killing the IIS Express process solves this error for me as pointed out by the link Eric points to. I am using Visual Studio 2015 community. I exit the IIS Express process from the taskbar.

Body:
I'm using the Nuget package System.Data.SQLite in an MVC web application. There seems to be lock issue when I try to clean the solution and rebuild. The error message I get is:
Unable to delete file "bin\x64\SQLite.Interop.dll". Access to the path '\bin\x64\SQLite.Interop.dll' is denied.

I'm thinking that the database is either still open or that the .dll is still in use, but I can't find any documentation or any reference to the same problem. This question  seems like a similar issue but doesn't provide a resolution to my problem.

Here is a code snippet that I'm using to write to the SQLite database:

        var conn = new SQLiteConnection("Data Source=" + connectionString);
        conn.Open();

        var debugEntriesTableQuery = "CREATE TABLE ...";

        var cmd = conn.CreateCommand();

        cmd.CommandText = debugEntriesTableQuery;

        cmd.ExecuteNonQuery();

        conn.Close();

Is there another step needed to properly close the connection to the database and inform the dll and the connection has closed?

I am using this code inside a data solution that I have added to a nuget package and am using in another solution. I am only having this problem when building/cleaning the solution that is using my nuget package.


问:
JQuery UI Tabs - "Loading..." message
All,

I am using Jquery UI nested tabs. I was just wondering if there is any way to display an AJAX Spinner image next to the tab text, while the tab is loading. I do not want to change the tab text to "Loading..". Consider that when multiple tabs are loading at the same time or one after the other, the spinner image should be displayed next to each loading tab..

Any Suggestions?

Thanks

答:
In jQuery UI v1.12 you can use the beforeLoad Handler:</p>

```<code>$('#tabs').tabs({
beforeLoad: function(event, ui) {
    ui.panel.html('Loading')
}
});
</code>```

Title: JQuery UI Tabs - "Loading..." message

Body:
In jQuery UI v1.12 you can use the beforeLoad Handler:

$('#tabs').tabs({
beforeLoad: function(event, ui) {
    ui.panel.html('Loading')
}
});


问:
Can I get a celery task's arguments if all I have is the task ID?
If I have the original task I can get the arguments from task.request.args, but if I only have the task ID is there a way to get the arguments? It doesn't look like there is a way to get them from an AsyncResult object, and as far as I can tell there isn't a way to re-create the task.

I want to do this because I have a frontend that polls the backend for updates on tasks, and it would be useful if it could display the task arguments. Seeing as the arguments are stored with the broker, this should be possible, at least when the task is in pending state.

Naturally there are other ways to do this, but it would be a clean way to do things.

答:
If the task is in pending state or if it is executing currently, you can see the arguments of the task. The easiest way is to use celery inspect method.

```<code>from celery.task.control import inspect
i = inspect()
active_tasks = i.active()
reserved_tasks = i.reserved()
scheduled_tasks = i.scheduled()
</code>```

You can iterate over them and by using task id, you can get all the task details like this

```<code>{'acknowledged': True,
   'args': '(1000,)',
   'delivery_info': {'exchange': '',
    'priority': 0,
    'redelivered': None,
    'routing_key': 'celery'},
   'hostname': 'celery@pavilion',
   'id': '30d41ba2-3e71-49ce-8e7d-830ba1152256',
   'kwargs': '{}',
   'name': 't.wait',
   'time_start': 1007.945882783,
   'type': 't.wait',
   'worker_pid': 10560}
</code>```

Alterantively, you can also read data from broker, deseriaze it and you can get the task agruments.

Body:
If the task is in pending state or if it is executing currently, you can see the arguments of the task. The easiest way is to use celery inspect method.

from celery.task.control import inspect
i = inspect()
active_tasks = i.active()
reserved_tasks = i.reserved()
scheduled_tasks = i.scheduled()

You can iterate over them and by using task id, you can get all the task details like this

{'acknowledged': True,
   'args': '(1000,)',
   'delivery_info': {'exchange': '',
    'priority': 0,
    'redelivered': None,
    'routing_key': 'celery'},
   'hostname': 'celery@pavilion',
   'id': '30d41ba2-3e71-49ce-8e7d-830ba1152256',
   'kwargs': '{}',
   'name': 't.wait',
   'time_start': 1007.945882783,
   'type': 't.wait',
   'worker_pid': 10560}

Alterantively, you can also read data from broker, deseriaze it and you can get the task agruments.


问:
Json Nested Complex Array to Web Api 2.0 Controller Action
Ok gang. I am having what seems to be a very popular but very unsolved (at least for me) problem.  I have the following request body in Fiddler:

```<code>{
    "Type": "WQ",
    "Customer": "1600",
    "JobNbr": "1zAlpha - BLAHDYBLOO",
    "Delivery": 1,
    "Pickup": 1,
    "DelInst": "Location: Earth
    ",
    "StartDate": "2017-02-28",
    "StartTime": "1700",
    "EndDate": "2017-03-15",
    "EndTime": "1700",
    "CustTransactionId": "555",
"EquipmentItems": {
  "EquipmentItem":
 [
        {
          "Equipment": "0500006",
          "CatID": "050",
          "ClassID": "0006",
          "LineSeq": "1",
          "Quantity": "001"
        },
        {
          "Equipment": "0500007",
          "CatID": "050",
          "ClassID": "0007",
          "LineSeq": "2",
          "Quantity": "001"
        }
      ]},
    "CustomerFields": {
      "blah": "12345",
      "blah blah": "123",
      "blah blah blah": "WHATEVER"
    }
  }
</code>```

As you can see, I have a complex "Reservation" object that contains a nested array of "Equipment" objects as well as a complex list of key value pairs that a customer may send us which we call CustomerFields.

When I send this to my Controller's action through fiddler, the parent class comes in as expected, but the nested Equipments array and the CustomerFields objects come in null.

My headers look like this:

```<code>Content-Type: application/json; charset=utf-8
Accept: application/json, text/javascript, /; q=0.01
Host: localhost:51493
Content-Length: 1209
</code>```

My action signature looks like:

```<code>Post([FromBody]Reservation reservation)
</code>```

And each class is decorated with [JsonObjec] or [JsonProperty] respectively and I have tried removing the Json "names" from the json body as well.  What do I need to do to get my fully populated object inside my controller from fiddler?  Do I need to make json data adjustments?  Code adjustments?  Both?  I'm at a complete loss.  I have tried so many different permutations that listing them would be counterproductive at this point.

Thanks for your assistance in advance.

Reservation Class Definition:

```<code>[JsonObject]
    public partial class Reservation : IReservation
    {
        #region private fields
        private string companyField;
        private int? locationField;
        private ReservationType typeField;
        private string customerField;
        private string custTransactionIDField;
        private Guid sbrTransactionIDField;
        private string licenseField;
        private string dlStateField;
        private string jobNbrField;
        private bool deliveryField;
        private bool pickupField;
        private string deliveryInstructionsField;
        private DateTime startDateField;
        private DateTime endDateField;
        private string customerPOField;
        private string webUserField;
        private bool rPPFlagField;
        private bool fuelFlagField;
        private decimal deliveryChargeField;
        private decimal pickupChargeField;
        private CustomerDataList customerDataField;
        private EquipmentItems itemsField;
        #endregion

        #region Public properties
        /// <remarks/>
        public int? ReservationNo { get; set; }

        /// <remarks/>
        public string Company
        {
            get
            {
                return this.companyField;
            }
            set
            {
                this.companyField = value;
            }
        }

        /// <remarks/>
        public int? Location
        {
            get
            {
                return this.locationField;
            }
            set
            {
                this.locationField = (value != null) ?  value : -1;
            }
        }

        /// <remarks/>
        public ReservationType Type
        {
            get
            {
                return this.typeField;
            }
            set
            {
                this.typeField = value;
            }
        }

        /// <remarks/>
        public string Customer
        {
            get
            {
                return this.customerField;
            }
            set
            {
                this.customerField = value;
            }
        }

        /// <remarks/>
        public string CustTransactionID
        {
            get
            {
                return this.custTransactionIDField != null ? custTransactionIDField : string.Empty;
            }

            set
            {
                this.custTransactionIDField = value;
            }
        }

        /// <remarks/>
        public Guid SBRTransactionID
        {
            get
            {
                return this.sbrTransactionIDField;
            }

            set
            {
                this.sbrTransactionIDField = value;
            }
        }

        /// <remarks/>
        public string License
        {
            get
            {
                return this.licenseField;
            }
            set
            {
                this.licenseField = value;
            }
        }

        /// <remarks/>
        public string DlState
        {
            get
            {
                return this.dlStateField;
            }
            set
            {
                this.dlStateField = value;
            }
        }

        /// <remarks/>
        public string JobNbr
        {
            get
            {
                return this.jobNbrField;
            }
            set
            {
                this.jobNbrField = value;
            }
        }

        /// <remarks/>
        public bool Delivery
        {
            get
            {
                return this.deliveryField;
            }
            set
            {
                this.deliveryField = value;
            }
        }

        public bool Pickup
        {
            get
            {
                return this.pickupField;
            }
            set
            {
                this.pickupField = value;
            }
        }

        /// <remarks/>
        public string DeliveryInstructions
        {
            get
            {
                return this.deliveryInstructionsField;
            }
            set
            {
                this.deliveryInstructionsField = value;
            }
        }

        /// <remarks/>
        public System.DateTime StartDate
        {
            get
            {
                return this.startDateField;
            }
            set
            {
                this.startDateField = value;
            }
        }

        public string StartTime { get; set; }
        public string EndTime { get; set; }
        /// <remarks/>
        public System.DateTime EndDate
        {
            get
            {
                return this.endDateField;
            }
            set
            {
                this.endDateField = value;
            }
        }

        /// <remarks/>
        public string CustomerPO
        {
            get
            {
                return this.customerPOField;
            }
            set
            {
                this.customerPOField = value;
            }
        }

        /// <remarks/>
        public string WebUser
        {
            get
            {
                return this.webUserField;
            }
            set
            {
                this.webUserField = value;
            }
        }

        /// <remarks/>
        public bool RPPFlag
        {
            get
            {
                return this.rPPFlagField;
            }
            set
            {
                this.rPPFlagField = value;
            }
        }

        /// <remarks/>
        public bool FuelFlag
        {
            get
            {
                return this.fuelFlagField;
            }
            set
            {
                this.fuelFlagField = value;
            }
        }

        /// <remarks/>
        public decimal DeliveryCharge
        {
            get
            {
                return this.deliveryChargeField;
            }
            set
            {
                this.deliveryChargeField = value;
            }
        }

        /// <remarks/>
        public decimal PickupCharge
        {
            get
            {
                return this.pickupChargeField;
            }
            set
            {
                this.pickupChargeField = value;
            }
        }

        [System.Xml.Serialization.XmlArrayItemAttribute("EquipmentItems", IsNullable = false)]
        [JsonProperty]
        public EquipmentItems Items
        {
            get
            {
                return this.itemsField;
            }
            set
            {
                this.itemsField = value;
            }
        }

        /// <remarks/>
        public CustomerDataList CustomerData
        {
            get
            {
                return this.customerDataField;
            }
            set
            {
                this.customerDataField = value;
            }
        }

        List<IItemData> IReservation.Items
        {
            get
            {
                return this.itemsField.ToList<IItemData>();
            }

            set
            {
                SetItems(value);
            }
        }
        /// <remarks/>
        #endregion

        private void SetItems(List<IItemData> items)
        {

            this.itemsField = ((EquipmentItems)((IEnumerable<EquipmentItem>)items.Select(e => e.CatID == e.CatID)));

        }
    }
    #endregion
</code>```

EquipmentItems Definition:

```<code>[JsonObject]
public partial class EquipmentItems : List<EquipmentItem>
{ }

[JsonObject]

    public partial class EquipmentItem : IItemData
    {
        #region Private fields
        private string equipmentIDField;
        private string catIDField;
        private string classIDField;
        private string lineSequenceField;
        private string quantityField;
        private string toolFlexField;
        private string hourlyRateField;
        private string dailyRateField;
        private string weeklyRateField;
        private string monthlyRateField;
        private string minRateField;
        private bool daysOverField;
        private bool weeksOverField;
        private bool monthsOverField;
        #endregion

        #region Public properties
        /// <remarks/>
        public string Equipment
        {
            get
            {
                return this.equipmentIDField;
            }
            set
            {
                this.equipmentIDField = value;
            }
        }

        /// <remarks/>
        public string CatID
        {
            get
            {
                return this.catIDField;
            }
            set
            {
                this.catIDField = value;
            }
        }

        /// <remarks/>
        public string ClassID
        {
            get
            {
                return this.classIDField;
            }
            set
            {
                this.classIDField = value;
            }
        }

        /// <remarks/>
        public string LineSeq
        {
            get
            {
                return this.lineSequenceField;
            }
            set
            {
                this.lineSequenceField = value;
            }
        }

        /// <remarks/>
        public string Quantity
        {
            get
            {
                return this.quantityField;
            }
            set
            {
                this.quantityField = value;
            }
        }

        /// <remarks/>
        public string ToolFlex
        {
            get
            {
                return this.toolFlexField;
            }
            set
            {
                this.toolFlexField = value;
            }
        }

        /// <remarks/>
        public string HrRate
        {
            get
            {
                return this.hourlyRateField;
            }
            set
            {
                this.hourlyRateField = value;
            }
        }

        /// <remarks/>
        public string DayRate
        {
            get
            {
                return this.dailyRateField;
            }
            set
            {
                this.dailyRateField = value;
            }
        }

        /// <remarks/>
        public string WkRate
        {
            get
            {
                return this.weeklyRateField;
            }
            set
            {
                this.weeklyRateField = value;
            }
        }

        public string MinRate
        {
            get
            {
                return this.minRateField;
            }
            set
            {
                this.minRateField = value;
            }
        }
        /// <remarks/>
        public string MoRate
        {
            get
            {
                return this.monthlyRateField;
            }
            set
            {
                this.monthlyRateField = value;
            }
        }

        /// <remarks/>
        public bool DayOver
        {
            get
            {
                return this.daysOverField;
            }
            set
            {
                this.daysOverField = value;
            }
        }

        /// <remarks/>
        public bool WkOver
        {
            get
            {
                return this.weeksOverField;
            }
            set
            {
                this.weeksOverField = value;
            }
        }

        /// <remarks/>
        public bool MoOver
        {
            get
            {
                return this.monthsOverField;
            }
            set
            {
                this.monthsOverField = value;
            }
        }
        #endregion
    }
</code>```

There is almost 0% chance there is a delta between the json and the class defs as I used automation tools for both.  But if you can help me figure out just the EquipmentItems array, that will be enough.  Thanks again.

答:
I think your json isn't quite correct if you're expecting that class structure. I've removed the array under EquipmentItem and changed EquipmentItems into an array:

```<code>{
    "Type": "WQ",
    "Customer": "1600",
    "JobNbr": "1zAlpha - BLAHDYBLOO",
    "Delivery": 1,
    "Pickup": 1,
    "DelInst": "Location: Earth
            ",
    "StartDate": "2017-02-28",
    "StartTime": "1700",
    "EndDate": "2017-03-15",
    "EndTime": "1700",
    "CustTransactionId": "555",
    "EquipmentItems": [{
            "Equipment": "0500006",
            "CatID": "050",
            "ClassID": "0006",
            "LineSeq": "1",
            "Quantity": "001"
        }, {
            "Equipment": "0500007",
            "CatID": "050",
            "ClassID": "0007",
            "LineSeq": "2",
            "Quantity": "001"
        }
    ],
    "CustomerFields": {
        "blah": "12345",
        "blah blah": "123",
        "blah blah blah": "WHATEVER"
    }
}
</code>```

```<code>[JsonObject]
public partial class Reservation : IReservation
{
    #region private fields
    private string companyField;
    private int? locationField;
    private ReservationType typeField;
    private string customerField;
    private string custTransactionIDField;
    private Guid sbrTransactionIDField;
    private string licenseField;
    private string dlStateField;
    private string jobNbrField;
    private bool deliveryField;
    private bool pickupField;
    private string deliveryInstructionsField;
    private DateTime startDateField;
    private DateTime endDateField;
    private string customerPOField;
    private string webUserField;
    private bool rPPFlagField;
    private bool fuelFlagField;
    private decimal deliveryChargeField;
    private decimal pickupChargeField;
    private CustomerDataList customerDataField;
    private List<EquipmentItem> itemsField;
    #endregion

    #region Public properties
    /// <remarks/>
    public int? ReservationNo { get; set; }

    /// <remarks/>
    public string Company
    {
        get
        {
            return this.companyField;
        }
        set
        {
            this.companyField = value;
        }
    }

    /// <remarks/>
    public int? Location
    {
        get
        {
            return this.locationField;
        }
        set
        {
            this.locationField = (value != null) ?  value : -1;
        }
    }

    /// <remarks/>
    public ReservationType Type
    {
        get
        {
            return this.typeField;
        }
        set
        {
            this.typeField = value;
        }
    }

    /// <remarks/>
    public string Customer
    {
        get
        {
            return this.customerField;
        }
        set
        {
            this.customerField = value;
        }
    }

    /// <remarks/>
    public string CustTransactionID
    {
        get
        {
            return this.custTransactionIDField != null ? custTransactionIDField : string.Empty;
        }

        set
        {
            this.custTransactionIDField = value;
        }
    }

    /// <remarks/>
    public Guid SBRTransactionID
    {
        get
        {
            return this.sbrTransactionIDField;
        }

        set
        {
            this.sbrTransactionIDField = value;
        }
    }

    /// <remarks/>
    public string License
    {
        get
        {
            return this.licenseField;
        }
        set
        {
            this.licenseField = value;
        }
    }

    /// <remarks/>
    public string DlState
    {
        get
        {
            return this.dlStateField;
        }
        set
        {
            this.dlStateField = value;
        }
    }

    /// <remarks/>
    public string JobNbr
    {
        get
        {
            return this.jobNbrField;
        }
        set
        {
            this.jobNbrField = value;
        }
    }

    /// <remarks/>
    public bool Delivery
    {
        get
        {
            return this.deliveryField;
        }
        set
        {
            this.deliveryField = value;
        }
    }

    public bool Pickup
    {
        get
        {
            return this.pickupField;
        }
        set
        {
            this.pickupField = value;
        }
    }

    /// <remarks/>
    public string DeliveryInstructions
    {
        get
        {
            return this.deliveryInstructionsField;
        }
        set
        {
            this.deliveryInstructionsField = value;
        }
    }

    /// <remarks/>
    public System.DateTime StartDate
    {
        get
        {
            return this.startDateField;
        }
        set
        {
            this.startDateField = value;
        }
    }

    public string StartTime { get; set; }
    public string EndTime { get; set; }
    /// <remarks/>
    public System.DateTime EndDate
    {
        get
        {
            return this.endDateField;
        }
        set
        {
            this.endDateField = value;
        }
    }

    /// <remarks/>
    public string CustomerPO
    {
        get
        {
            return this.customerPOField;
        }
        set
        {
            this.customerPOField = value;
        }
    }

    /// <remarks/>
    public string WebUser
    {
        get
        {
            return this.webUserField;
        }
        set
        {
            this.webUserField = value;
        }
    }

    /// <remarks/>
    public bool RPPFlag
    {
        get
        {
            return this.rPPFlagField;
        }
        set
        {
            this.rPPFlagField = value;
        }
    }

    /// <remarks/>
    public bool FuelFlag
    {
        get
        {
            return this.fuelFlagField;
        }
        set
        {
            this.fuelFlagField = value;
        }
    }

    /// <remarks/>
    public decimal DeliveryCharge
    {
        get
        {
            return this.deliveryChargeField;
        }
        set
        {
            this.deliveryChargeField = value;
        }
    }

    /// <remarks/>
    public decimal PickupCharge
    {
        get
        {
            return this.pickupChargeField;
        }
        set
        {
            this.pickupChargeField = value;
        }
    }

    [System.Xml.Serialization.XmlArrayItemAttribute("EquipmentItems", IsNullable = false)]
    [JsonProperty(PropertyName = "EquipmentItems")]
    public List<EquipmentItem> Items
    {
        get
        {
            return this.itemsField;
        }
        set
        {
            this.itemsField = value;
        }
    }

    /// <remarks/>
    public CustomerDataList CustomerData
    {
        get
        {
            return this.customerDataField;
        }
        set
        {
            this.customerDataField = value;
        }
    }

    List<IItemData> IReservation.Items
    {
        get
        {
            return this.itemsField.ToList<IItemData>();
        }

        set
        {
            SetItems(value);
        }
    }
    /// <remarks/>
    #endregion

    private void SetItems(List<IItemData> items)
    {

        this.itemsField = ((List<EquipmentItem>)((IEnumerable<EquipmentItem>)items.Select(e => e.CatID == e.CatID)));

    }
}
#endregion

[JsonObject]

public partial class EquipmentItem : IItemData
{
    #region Private fields
    private string equipmentIDField;
    private string catIDField;
    private string classIDField;
    private string lineSequenceField;
    private string quantityField;
    private string toolFlexField;
    private string hourlyRateField;
    private string dailyRateField;
    private string weeklyRateField;
    private string monthlyRateField;
    private string minRateField;
    private bool daysOverField;
    private bool weeksOverField;
    private bool monthsOverField;
    #endregion

    #region Public properties
    /// <remarks/>
    public string Equipment
    {
        get
        {
            return this.equipmentIDField;
        }
        set
        {
            this.equipmentIDField = value;
        }
    }

    /// <remarks/>
    public string CatID
    {
        get
        {
            return this.catIDField;
        }
        set
        {
            this.catIDField = value;
        }
    }

    /// <remarks/>
    public string ClassID
    {
        get
        {
            return this.classIDField;
        }
        set
        {
            this.classIDField = value;
        }
    }

    /// <remarks/>
    public string LineSeq
    {
        get
        {
            return this.lineSequenceField;
        }
        set
        {
            this.lineSequenceField = value;
        }
    }

    /// <remarks/>
    public string Quantity
    {
        get
        {
            return this.quantityField;
        }
        set
        {
            this.quantityField = value;
        }
    }

    /// <remarks/>
    public string ToolFlex
    {
        get
        {
            return this.toolFlexField;
        }
        set
        {
            this.toolFlexField = value;
        }
    }

    /// <remarks/>
    public string HrRate
    {
        get
        {
            return this.hourlyRateField;
        }
        set
        {
            this.hourlyRateField = value;
        }
    }

    /// <remarks/>
    public string DayRate
    {
        get
        {
            return this.dailyRateField;
        }
        set
        {
            this.dailyRateField = value;
        }
    }

    /// <remarks/>
    public string WkRate
    {
        get
        {
            return this.weeklyRateField;
        }
        set
        {
            this.weeklyRateField = value;
        }
    }

    public string MinRate
    {
        get
        {
            return this.minRateField;
        }
        set
        {
            this.minRateField = value;
        }
    }
    /// <remarks/>
    public string MoRate
    {
        get
        {
            return this.monthlyRateField;
        }
        set
        {
            this.monthlyRateField = value;
        }
    }

    /// <remarks/>
    public bool DayOver
    {
        get
        {
            return this.daysOverField;
        }
        set
        {
            this.daysOverField = value;
        }
    }

    /// <remarks/>
    public bool WkOver
    {
        get
        {
            return this.weeksOverField;
        }
        set
        {
            this.weeksOverField = value;
        }
    }

    /// <remarks/>
    public bool MoOver
    {
        get
        {
            return this.monthsOverField;
        }
        set
        {
            this.monthsOverField = value;
        }
    }
    #endregion
}
</code>```

Body:
Ok gang. I am having what seems to be a very popular but very unsolved (at least for me) problem.  I have the following request body in Fiddler:

{
    "Type": "WQ",
    "Customer": "1600",
    "JobNbr": "1zAlpha - BLAHDYBLOO",
    "Delivery": 1,
    "Pickup": 1,
    "DelInst": "Location: Earth
    ",
    "StartDate": "2017-02-28",
    "StartTime": "1700",
    "EndDate": "2017-03-15",
    "EndTime": "1700",
    "CustTransactionId": "555",
"EquipmentItems": {
  "EquipmentItem":
 [
        {
          "Equipment": "0500006",
          "CatID": "050",
          "ClassID": "0006",
          "LineSeq": "1",
          "Quantity": "001"
        },
        {
          "Equipment": "0500007",
          "CatID": "050",
          "ClassID": "0007",
          "LineSeq": "2",
          "Quantity": "001"
        }
      ]},
    "CustomerFields": {
      "blah": "12345",
      "blah blah": "123",
      "blah blah blah": "WHATEVER"
    }
  }

As you can see, I have a complex "Reservation" object that contains a nested array of "Equipment" objects as well as a complex list of key value pairs that a customer may send us which we call CustomerFields.

When I send this to my Controller's action through fiddler, the parent class comes in as expected, but the nested Equipments array and the CustomerFields objects come in null.

My headers look like this:

Content-Type: application/json; charset=utf-8
Accept: application/json, text/javascript, /; q=0.01
Host: localhost:51493
Content-Length: 1209

My action signature looks like:

Post([FromBody]Reservation reservation)

And each class is decorated with [JsonObjec] or [JsonProperty] respectively and I have tried removing the Json "names" from the json body as well.  What do I need to do to get my fully populated object inside my controller from fiddler?  Do I need to make json data adjustments?  Code adjustments?  Both?  I'm at a complete loss.  I have tried so many different permutations that listing them would be counterproductive at this point.

Thanks for your assistance in advance.

Reservation Class Definition:

[JsonObject]
    public partial class Reservation : IReservation
    {
        #region private fields
        private string companyField;
        private int? locationField;
        private ReservationType typeField;
        private string customerField;
        private string custTransactionIDField;
        private Guid sbrTransactionIDField;
        private string licenseField;
        private string dlStateField;
        private string jobNbrField;
        private bool deliveryField;
        private bool pickupField;
        private string deliveryInstructionsField;
        private DateTime startDateField;
        private DateTime endDateField;
        private string customerPOField;
        private string webUserField;
        private bool rPPFlagField;
        private bool fuelFlagField;
        private decimal deliveryChargeField;
        private decimal pickupChargeField;
        private CustomerDataList customerDataField;
        private EquipmentItems itemsField;
        #endregion

        #region Public properties
        /// <remarks/>
        public int? ReservationNo { get; set; }

        /// <remarks/>
        public string Company
        {
            get
            {
                return this.companyField;
            }
            set
            {
                this.companyField = value;
            }
        }

        /// <remarks/>
        public int? Location
        {
            get
            {
                return this.locationField;
            }
            set
            {
                this.locationField = (value != null) ?  value : -1;
            }
        }

        /// <remarks/>
        public ReservationType Type
        {
            get
            {
                return this.typeField;
            }
            set
            {
                this.typeField = value;
            }
        }

        /// <remarks/>
        public string Customer
        {
            get
            {
                return this.customerField;
            }
            set
            {
                this.customerField = value;
            }
        }

        /// <remarks/>
        public string CustTransactionID
        {
            get
            {
                return this.custTransactionIDField != null ? custTransactionIDField : string.Empty;
            }

            set
            {
                this.custTransactionIDField = value;
            }
        }

        /// <remarks/>
        public Guid SBRTransactionID
        {
            get
            {
                return this.sbrTransactionIDField;
            }

            set
            {
                this.sbrTransactionIDField = value;
            }
        }

        /// <remarks/>
        public string License
        {
            get
            {
                return this.licenseField;
            }
            set
            {
                this.licenseField = value;
            }
        }

        /// <remarks/>
        public string DlState
        {
            get
            {
                return this.dlStateField;
            }
            set
            {
                this.dlStateField = value;
            }
        }

        /// <remarks/>
        public string JobNbr
        {
            get
            {
                return this.jobNbrField;
            }
            set
            {
                this.jobNbrField = value;
            }
        }

        /// <remarks/>
        public bool Delivery
        {
            get
            {
                return this.deliveryField;
            }
            set
            {
                this.deliveryField = value;
            }
        }

        public bool Pickup
        {
            get
            {
                return this.pickupField;
            }
            set
            {
                this.pickupField = value;
            }
        }

        /// <remarks/>
        public string DeliveryInstructions
        {
            get
            {
                return this.deliveryInstructionsField;
            }
            set
            {
                this.deliveryInstructionsField = value;
            }
        }

        /// <remarks/>
        public System.DateTime StartDate
        {
            get
            {
                return this.startDateField;
            }
            set
            {
                this.startDateField = value;
            }
        }

        public string StartTime { get; set; }
        public string EndTime { get; set; }
        /// <remarks/>
        public System.DateTime EndDate
        {
            get
            {
                return this.endDateField;
            }
            set
            {
                this.endDateField = value;
            }
        }

        /// <remarks/>
        public string CustomerPO
        {
            get
            {
                return this.customerPOField;
            }
            set
            {
                this.customerPOField = value;
            }
        }

        /// <remarks/>
        public string WebUser
        {
            get
            {
                return this.webUserField;
            }
            set
            {
                this.webUserField = value;
            }
        }

        /// <remarks/>
        public bool RPPFlag
        {
            get
            {
                return this.rPPFlagField;
            }
            set
            {
                this.rPPFlagField = value;
            }
        }

        /// <remarks/>
        public bool FuelFlag
        {
            get
            {
                return this.fuelFlagField;
            }
            set
            {
                this.fuelFlagField = value;
            }
        }

        /// <remarks/>
        public decimal DeliveryCharge
        {
            get
            {
                return this.deliveryChargeField;
            }
            set
            {
                this.deliveryChargeField = value;
            }
        }

        /// <remarks/>
        public decimal PickupCharge
        {
            get
            {
                return this.pickupChargeField;
            }
            set
            {
                this.pickupChargeField = value;
            }
        }

        [System.Xml.Serialization.XmlArrayItemAttribute("EquipmentItems", IsNullable = false)]
        [JsonProperty]
        public EquipmentItems Items
        {
            get
            {
                return this.itemsField;
            }
            set
            {
                this.itemsField = value;
            }
        }

        /// <remarks/>
        public CustomerDataList CustomerData
        {
            get
            {
                return this.customerDataField;
            }
            set
            {
                this.customerDataField = value;
            }
        }

        List<IItemData> IReservation.Items
        {
            get
            {
                return this.itemsField.ToList<IItemData>();
            }

            set
            {
                SetItems(value);
            }
        }
        /// <remarks/>
        #endregion

        private void SetItems(List<IItemData> items)
        {

            this.itemsField = ((EquipmentItems)((IEnumerable<EquipmentItem>)items.Select(e => e.CatID == e.CatID)));

        }
    }
    #endregion

EquipmentItems Definition:

[JsonObject]
public partial class EquipmentItems : List<EquipmentItem>
{ }

[JsonObject]

    public partial class EquipmentItem : IItemData
    {
        #region Private fields
        private string equipmentIDField;
        private string catIDField;
        private string classIDField;
        private string lineSequenceField;
        private string quantityField;
        private string toolFlexField;
        private string hourlyRateField;
        private string dailyRateField;
        private string weeklyRateField;
        private string monthlyRateField;
        private string minRateField;
        private bool daysOverField;
        private bool weeksOverField;
        private bool monthsOverField;
        #endregion

        #region Public properties
        /// <remarks/>
        public string Equipment
        {
            get
            {
                return this.equipmentIDField;
            }
            set
            {
                this.equipmentIDField = value;
            }
        }

        /// <remarks/>
        public string CatID
        {
            get
            {
                return this.catIDField;
            }
            set
            {
                this.catIDField = value;
            }
        }

        /// <remarks/>
        public string ClassID
        {
            get
            {
                return this.classIDField;
            }
            set
            {
                this.classIDField = value;
            }
        }

        /// <remarks/>
        public string LineSeq
        {
            get
            {
                return this.lineSequenceField;
            }
            set
            {
                this.lineSequenceField = value;
            }
        }

        /// <remarks/>
        public string Quantity
        {
            get
            {
                return this.quantityField;
            }
            set
            {
                this.quantityField = value;
            }
        }

        /// <remarks/>
        public string ToolFlex
        {
            get
            {
                return this.toolFlexField;
            }
            set
            {
                this.toolFlexField = value;
            }
        }

        /// <remarks/>
        public string HrRate
        {
            get
            {
                return this.hourlyRateField;
            }
            set
            {
                this.hourlyRateField = value;
            }
        }

        /// <remarks/>
        public string DayRate
        {
            get
            {
                return this.dailyRateField;
            }
            set
            {
                this.dailyRateField = value;
            }
        }

        /// <remarks/>
        public string WkRate
        {
            get
            {
                return this.weeklyRateField;
            }
            set
            {
                this.weeklyRateField = value;
            }
        }

        public string MinRate
        {
            get
            {
                return this.minRateField;
            }
            set
            {
                this.minRateField = value;
            }
        }
        /// <remarks/>
        public string MoRate
        {
            get
            {
                return this.monthlyRateField;
            }
            set
            {
                this.monthlyRateField = value;
            }
        }

        /// <remarks/>
        public bool DayOver
        {
            get
            {
                return this.daysOverField;
            }
            set
            {
                this.daysOverField = value;
            }
        }

        /// <remarks/>
        public bool WkOver
        {
            get
            {
                return this.weeksOverField;
            }
            set
            {
                this.weeksOverField = value;
            }
        }

        /// <remarks/>
        public bool MoOver
        {
            get
            {
                return this.monthsOverField;
            }
            set
            {
                this.monthsOverField = value;
            }
        }
        #endregion
    }

There is almost 0% chance there is a delta between the json and the class defs as I used automation tools for both.  But if you can help me figure out just the EquipmentItems array, that will be enough.  Thanks again.

Body:
I think your json isn't quite correct if you're expecting that class structure. I've removed the array under EquipmentItem and changed EquipmentItems into an array:

{
    "Type": "WQ",
    "Customer": "1600",
    "JobNbr": "1zAlpha - BLAHDYBLOO",
    "Delivery": 1,
    "Pickup": 1,
    "DelInst": "Location: Earth
            ",
    "StartDate": "2017-02-28",
    "StartTime": "1700",
    "EndDate": "2017-03-15",
    "EndTime": "1700",
    "CustTransactionId": "555",
    "EquipmentItems": [{
            "Equipment": "0500006",
            "CatID": "050",
            "ClassID": "0006",
            "LineSeq": "1",
            "Quantity": "001"
        }, {
            "Equipment": "0500007",
            "CatID": "050",
            "ClassID": "0007",
            "LineSeq": "2",
            "Quantity": "001"
        }
    ],
    "CustomerFields": {
        "blah": "12345",
        "blah blah": "123",
        "blah blah blah": "WHATEVER"
    }
}

[JsonObject]
public partial class Reservation : IReservation
{
    #region private fields
    private string companyField;
    private int? locationField;
    private ReservationType typeField;
    private string customerField;
    private string custTransactionIDField;
    private Guid sbrTransactionIDField;
    private string licenseField;
    private string dlStateField;
    private string jobNbrField;
    private bool deliveryField;
    private bool pickupField;
    private string deliveryInstructionsField;
    private DateTime startDateField;
    private DateTime endDateField;
    private string customerPOField;
    private string webUserField;
    private bool rPPFlagField;
    private bool fuelFlagField;
    private decimal deliveryChargeField;
    private decimal pickupChargeField;
    private CustomerDataList customerDataField;
    private List<EquipmentItem> itemsField;
    #endregion

    #region Public properties
    /// <remarks/>
    public int? ReservationNo { get; set; }

    /// <remarks/>
    public string Company
    {
        get
        {
            return this.companyField;
        }
        set
        {
            this.companyField = value;
        }
    }

    /// <remarks/>
    public int? Location
    {
        get
        {
            return this.locationField;
        }
        set
        {
            this.locationField = (value != null) ?  value : -1;
        }
    }

    /// <remarks/>
    public ReservationType Type
    {
        get
        {
            return this.typeField;
        }
        set
        {
            this.typeField = value;
        }
    }

    /// <remarks/>
    public string Customer
    {
        get
        {
            return this.customerField;
        }
        set
        {
            this.customerField = value;
        }
    }

    /// <remarks/>
    public string CustTransactionID
    {
        get
        {
            return this.custTransactionIDField != null ? custTransactionIDField : string.Empty;
        }

        set
        {
            this.custTransactionIDField = value;
        }
    }

    /// <remarks/>
    public Guid SBRTransactionID
    {
        get
        {
            return this.sbrTransactionIDField;
        }

        set
        {
            this.sbrTransactionIDField = value;
        }
    }

    /// <remarks/>
    public string License
    {
        get
        {
            return this.licenseField;
        }
        set
        {
            this.licenseField = value;
        }
    }

    /// <remarks/>
    public string DlState
    {
        get
        {
            return this.dlStateField;
        }
        set
        {
            this.dlStateField = value;
        }
    }

    /// <remarks/>
    public string JobNbr
    {
        get
        {
            return this.jobNbrField;
        }
        set
        {
            this.jobNbrField = value;
        }
    }

    /// <remarks/>
    public bool Delivery
    {
        get
        {
            return this.deliveryField;
        }
        set
        {
            this.deliveryField = value;
        }
    }

    public bool Pickup
    {
        get
        {
            return this.pickupField;
        }
        set
        {
            this.pickupField = value;
        }
    }

    /// <remarks/>
    public string DeliveryInstructions
    {
        get
        {
            return this.deliveryInstructionsField;
        }
        set
        {
            this.deliveryInstructionsField = value;
        }
    }

    /// <remarks/>
    public System.DateTime StartDate
    {
        get
        {
            return this.startDateField;
        }
        set
        {
            this.startDateField = value;
        }
    }

    public string StartTime { get; set; }
    public string EndTime { get; set; }
    /// <remarks/>
    public System.DateTime EndDate
    {
        get
        {
            return this.endDateField;
        }
        set
        {
            this.endDateField = value;
        }
    }

    /// <remarks/>
    public string CustomerPO
    {
        get
        {
            return this.customerPOField;
        }
        set
        {
            this.customerPOField = value;
        }
    }

    /// <remarks/>
    public string WebUser
    {
        get
        {
            return this.webUserField;
        }
        set
        {
            this.webUserField = value;
        }
    }

    /// <remarks/>
    public bool RPPFlag
    {
        get
        {
            return this.rPPFlagField;
        }
        set
        {
            this.rPPFlagField = value;
        }
    }

    /// <remarks/>
    public bool FuelFlag
    {
        get
        {
            return this.fuelFlagField;
        }
        set
        {
            this.fuelFlagField = value;
        }
    }

    /// <remarks/>
    public decimal DeliveryCharge
    {
        get
        {
            return this.deliveryChargeField;
        }
        set
        {
            this.deliveryChargeField = value;
        }
    }

    /// <remarks/>
    public decimal PickupCharge
    {
        get
        {
            return this.pickupChargeField;
        }
        set
        {
            this.pickupChargeField = value;
        }
    }

    [System.Xml.Serialization.XmlArrayItemAttribute("EquipmentItems", IsNullable = false)]
    [JsonProperty(PropertyName = "EquipmentItems")]
    public List<EquipmentItem> Items
    {
        get
        {
            return this.itemsField;
        }
        set
        {
            this.itemsField = value;
        }
    }

    /// <remarks/>
    public CustomerDataList CustomerData
    {
        get
        {
            return this.customerDataField;
        }
        set
        {
            this.customerDataField = value;
        }
    }

    List<IItemData> IReservation.Items
    {
        get
        {
            return this.itemsField.ToList<IItemData>();
        }

        set
        {
            SetItems(value);
        }
    }
    /// <remarks/>
    #endregion

    private void SetItems(List<IItemData> items)
    {

        this.itemsField = ((List<EquipmentItem>)((IEnumerable<EquipmentItem>)items.Select(e => e.CatID == e.CatID)));

    }
}
#endregion

[JsonObject]

public partial class EquipmentItem : IItemData
{
    #region Private fields
    private string equipmentIDField;
    private string catIDField;
    private string classIDField;
    private string lineSequenceField;
    private string quantityField;
    private string toolFlexField;
    private string hourlyRateField;
    private string dailyRateField;
    private string weeklyRateField;
    private string monthlyRateField;
    private string minRateField;
    private bool daysOverField;
    private bool weeksOverField;
    private bool monthsOverField;
    #endregion

    #region Public properties
    /// <remarks/>
    public string Equipment
    {
        get
        {
            return this.equipmentIDField;
        }
        set
        {
            this.equipmentIDField = value;
        }
    }

    /// <remarks/>
    public string CatID
    {
        get
        {
            return this.catIDField;
        }
        set
        {
            this.catIDField = value;
        }
    }

    /// <remarks/>
    public string ClassID
    {
        get
        {
            return this.classIDField;
        }
        set
        {
            this.classIDField = value;
        }
    }

    /// <remarks/>
    public string LineSeq
    {
        get
        {
            return this.lineSequenceField;
        }
        set
        {
            this.lineSequenceField = value;
        }
    }

    /// <remarks/>
    public string Quantity
    {
        get
        {
            return this.quantityField;
        }
        set
        {
            this.quantityField = value;
        }
    }

    /// <remarks/>
    public string ToolFlex
    {
        get
        {
            return this.toolFlexField;
        }
        set
        {
            this.toolFlexField = value;
        }
    }

    /// <remarks/>
    public string HrRate
    {
        get
        {
            return this.hourlyRateField;
        }
        set
        {
            this.hourlyRateField = value;
        }
    }

    /// <remarks/>
    public string DayRate
    {
        get
        {
            return this.dailyRateField;
        }
        set
        {
            this.dailyRateField = value;
        }
    }

    /// <remarks/>
    public string WkRate
    {
        get
        {
            return this.weeklyRateField;
        }
        set
        {
            this.weeklyRateField = value;
        }
    }

    public string MinRate
    {
        get
        {
            return this.minRateField;
        }
        set
        {
            this.minRateField = value;
        }
    }
    /// <remarks/>
    public string MoRate
    {
        get
        {
            return this.monthlyRateField;
        }
        set
        {
            this.monthlyRateField = value;
        }
    }

    /// <remarks/>
    public bool DayOver
    {
        get
        {
            return this.daysOverField;
        }
        set
        {
            this.daysOverField = value;
        }
    }

    /// <remarks/>
    public bool WkOver
    {
        get
        {
            return this.weeksOverField;
        }
        set
        {
            this.weeksOverField = value;
        }
    }

    /// <remarks/>
    public bool MoOver
    {
        get
        {
            return this.monthsOverField;
        }
        set
        {
            this.monthsOverField = value;
        }
    }
    #endregion
}


答:
You will have to use

```<code> where (select count(student_id) from orderX x where x.student_id=s.id)
</code>```

instead. In sql-server you cannot use aliases in where clauses.

Title: SQL Server where clause order count > 0

Body:
You will have to use

 where (select count(student_id) from orderX x where x.student_id=s.id)

instead. In sql-server you cannot use aliases in where clauses.


问:
Why does Microsoft SQL Server check columns but not tables in stored procs?
Microsoft SQL Server seems to check column name validity, but not table name validity when defining stored procedures.  If it detects that a referenced table name exists currently, it validates the column names in a statement against the columns in that table.  So, for example, this will run OK:

```<code>CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        Col1, Col2, Col3
    FROM
        NonExistentTable
END
GO
</code>```

... as will this:

```<code>CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        ExistentCol1, ExistentCol2, ExistentCol3
    FROM
        ExistentTable
END
GO
</code>```

... but this fails, with 'Invalid column name':

```<code>CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        NonExistentCol1, NonExistentCol2, NonExistentCol3
    FROM
        ExistentTable
END
GO
</code>```

Why does SQL Server check columns, but not tables, for existence?  Surely it's inconsistent; it should do both, or neither.  It's useful for us to be able to define SPs which may refer to tables AND/OR columns which don't exist in the schema yet, so is there a way to turn off SQL Server's checking of column existence in tables which currently exist?

答:
This article in MSDN should answer your question.

From the article:

When a stored procedure is executed for the first time, the query
  processor reads the text of the stored procedure from the
  sys.sql_modules catalog view and checks that the names of the objects
  used by the procedure are present. This process is called deferred
  name resolution because table objects referenced by the stored
  procedure need not exist when the stored procedure is created, but
  only when it is executed.

Body:
Microsoft SQL Server seems to check column name validity, but not table name validity when defining stored procedures.  If it detects that a referenced table name exists currently, it validates the column names in a statement against the columns in that table.  So, for example, this will run OK:

CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        Col1, Col2, Col3
    FROM
        NonExistentTable
END
GO

... as will this:

CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        ExistentCol1, ExistentCol2, ExistentCol3
    FROM
        ExistentTable
END
GO

... but this fails, with 'Invalid column name':

CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        NonExistentCol1, NonExistentCol2, NonExistentCol3
    FROM
        ExistentTable
END
GO

Why does SQL Server check columns, but not tables, for existence?  Surely it's inconsistent; it should do both, or neither.  It's useful for us to be able to define SPs which may refer to tables AND/OR columns which don't exist in the schema yet, so is there a way to turn off SQL Server's checking of column existence in tables which currently exist?


问:
AWK: print only lines with wildcard
I have the following file.txt:

```<code>string1 <TAB> A21332
string2 <TAB> A45221
string3 <TAB>
string4 <TAB> A92092
</code>```

and I want to use awk to print for lines where the column 2 begins with an 'A'

this is my code

awk -F$'\t' '$2 ~ "A" {print $0}' file.txt

but it does not work...

答:
Use Awk as below, use the regex construct ^ to indicate the string-start

```<code>awk -v FS=$'\t' '$2 ~ "^A"' file
string1 A21332
string2 A45221
string4 A92092
</code>```

removing the bash specific $'\t' syntax, you can use it as

```<code>awk -vFS="\t" '$2 ~ "^A"' file
</code>```

and removing the GNU Awk specific -vFS= syntax & initialising de-limiter as part of BEGIN clause

```<code>awk 'BEGIN{FS="\t"}$2 ~ "^A"' file
</code>```

and removing the dynamic regex and just using // de-limiter as

```<code>awk 'BEGIN{FS="\t"}$2 ~ /^A/' file
</code>```

Title: AWK: print only lines with wildcard

Body:
I have the following file.txt:

string1 <TAB> A21332
string2 <TAB> A45221
string3 <TAB>
string4 <TAB> A92092

and I want to use awk to print for lines where the column 2 begins with an 'A'

this is my code

awk -F$'\t' '$2 ~ "A" {print $0}' file.txt

but it does not work...

Body:
Use Awk as below, use the regex construct ^ to indicate the string-start

awk -v FS=$'\t' '$2 ~ "^A"' file
string1 A21332
string2 A45221
string4 A92092

removing the bash specific $'\t' syntax, you can use it as

awk -vFS="\t" '$2 ~ "^A"' file

and removing the GNU Awk specific -vFS= syntax & initialising de-limiter as part of BEGIN clause

awk 'BEGIN{FS="\t"}$2 ~ "^A"' file

and removing the dynamic regex and just using // de-limiter as

awk 'BEGIN{FS="\t"}$2 ~ /^A/' file


问:
Executing ssh commands on by one in shell using jsch ssh
I am trying to execute some tool in unix using the jsch ssh class (com.jcraft.jsch).
My tool have a selection menu.
I need to go to the folder where the tool is place, execute it and select the requested options.
After each command, (cd, execute, ...) I wish to examine the output and check the status code (0/1).
I have the following code that execute it as expected but in this code I couldn't find a way how to examine the output after each command.

```<code>Session session = _getConnectedSession();
Channel channel = session.openChannel("shell");
channel.connect();

InputStream is = channel.getInputStream();
BufferedReader dataIn = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());

// send ls command to the server
enter code here dataOut.writeBytes("cd tools; run tool\n");
dataOut.writeBytes("4\r\n");  // option 4 in the tool
dataOut.writeBytes("4\r\n");  // then, option 4 in the tool
dataOut.writeBytes("6\r\n");  // then, option 6 in the tool
dataOut.writeBytes("n\r\n");  // then, option n in the tool
dataOut.flush();
String line = dataIn.readLine();

while ((line = dataIn.readLine()) != null) {
    System.out.println(line);
}

if(channel.isClosed()){
    system.out.println("exit-status: "+channel.getExitStatus());
}

dataIn.close();
dataOut.close();
channel.disconnect();
session.disconnect();
</code>```

I couldn't find a way yet how can I separate the commands and print them one by one (in while loop) and not as I did above.

I have tried to split all commands to two bulks as following but it prints and execute only the first bulk of commands (before the first while loop):

```<code>// First bulk of commands
enter code here dataOut.writeBytes("cd tools; run tool\n");
dataOut.writeBytes("4\r\n");  // option 4 in the tool
dataOut.writeBytes("4\r\n");  // then, option 4 in the tool
dataOut.flush();

String line = dataIn.readLine();
while ((line = dataIn.readLine()) != null) {
    System.out.println(line);
}

// Second bulk of commands
dataOut.writeBytes("6\r\n");  // then, option 6 in the tool
dataOut.writeBytes("n\r\n");  // then, option n in the tool
dataOut.flush();
line = dataIn.readLine();
while ((line = dataIn.readLine()) != null) {
    System.out.println(line);
}

if(channel.isClosed()){
    system.out.println("exit-status: "+channel.getExitStatus());
}
</code>```

Am I doing something wrong?

答:
First of all you haven't set the output stream and to check the exit status of the last executed command you have to use

"$?" - if it is 0 last executed command is successful otherwise it is failure.

The below code snippet allows you to give commands and read the response code of that command.

```<code>                ss=new StringBuilder("ls | echo $?");
                ss.append("\n");
                FileWriter fw = new FileWriter("comm.txt");
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(ss.toString());
                bw.flush();
                fw.close();
                bw.close();
                InputStream is=new FileInputStream("comm.txt");
                OutputStream os=new FileOutputStream("outs.txt");
                channel.setInputStream(is);
                channel.setOutputStream(os);
                Thread.sleep(1000);
                channel.connect();
                System.out.println("connected");
                f.dispose();
                getApplication();
</code>```

In the above code I have used "comm.txt" as inputstream and "outs.txt" as output stream. You can change the content of stringBuilder object by using Scanner class.

ls | echo $?"

will produce 0 if ls is executed successfully otherwise non-zero value. This value can be checked in outs.txt file.

If the content of outs.txt file is 0 the command is executed correctly otherwise it is not executed properly. You have to write code to read contents from outs.txt file.

If you want the full code you can see my project

GITHUB

In that see "Cloud.java" file for full code.

Body:
I am trying to execute some tool in unix using the jsch ssh class (com.jcraft.jsch).
My tool have a selection menu.
I need to go to the folder where the tool is place, execute it and select the requested options.
After each command, (cd, execute, ...) I wish to examine the output and check the status code (0/1).
I have the following code that execute it as expected but in this code I couldn't find a way how to examine the output after each command.

Session session = _getConnectedSession();
Channel channel = session.openChannel("shell");
channel.connect();

InputStream is = channel.getInputStream();
BufferedReader dataIn = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());

// send ls command to the server
enter code here dataOut.writeBytes("cd tools; run tool\n");
dataOut.writeBytes("4\r\n");  // option 4 in the tool
dataOut.writeBytes("4\r\n");  // then, option 4 in the tool
dataOut.writeBytes("6\r\n");  // then, option 6 in the tool
dataOut.writeBytes("n\r\n");  // then, option n in the tool
dataOut.flush();
String line = dataIn.readLine();

while ((line = dataIn.readLine()) != null) {
    System.out.println(line);
}

if(channel.isClosed()){
    system.out.println("exit-status: "+channel.getExitStatus());
}

dataIn.close();
dataOut.close();
channel.disconnect();
session.disconnect();

I couldn't find a way yet how can I separate the commands and print them one by one (in while loop) and not as I did above.

I have tried to split all commands to two bulks as following but it prints and execute only the first bulk of commands (before the first while loop):

// First bulk of commands
enter code here dataOut.writeBytes("cd tools; run tool\n");
dataOut.writeBytes("4\r\n");  // option 4 in the tool
dataOut.writeBytes("4\r\n");  // then, option 4 in the tool
dataOut.flush();

String line = dataIn.readLine();
while ((line = dataIn.readLine()) != null) {
    System.out.println(line);
}

// Second bulk of commands
dataOut.writeBytes("6\r\n");  // then, option 6 in the tool
dataOut.writeBytes("n\r\n");  // then, option n in the tool
dataOut.flush();
line = dataIn.readLine();
while ((line = dataIn.readLine()) != null) {
    System.out.println(line);
}

if(channel.isClosed()){
    system.out.println("exit-status: "+channel.getExitStatus());
}

Am I doing something wrong?

Body:
First of all you haven't set the output stream and to check the exit status of the last executed command you have to use

"$?" - if it is 0 last executed command is successful otherwise it is failure.

The below code snippet allows you to give commands and read the response code of that command.

                ss=new StringBuilder("ls | echo $?");
                ss.append("\n");
                FileWriter fw = new FileWriter("comm.txt");
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(ss.toString());
                bw.flush();
                fw.close();
                bw.close();
                InputStream is=new FileInputStream("comm.txt");
                OutputStream os=new FileOutputStream("outs.txt");
                channel.setInputStream(is);
                channel.setOutputStream(os);
                Thread.sleep(1000);
                channel.connect();
                System.out.println("connected");
                f.dispose();
                getApplication();

In the above code I have used "comm.txt" as inputstream and "outs.txt" as output stream. You can change the content of stringBuilder object by using Scanner class.

ls | echo $?"

will produce 0 if ls is executed successfully otherwise non-zero value. This value can be checked in outs.txt file.

If the content of outs.txt file is 0 the command is executed correctly otherwise it is not executed properly. You have to write code to read contents from outs.txt file.

If you want the full code you can see my project

GITHUB

In that see "Cloud.java" file for full code.