问:
How to customize my UITabBar. White icons on gradient background
iOS 7.0.

I need to make your design UITabBar. The picture (this link) shows how it looks now and how it should look. The difference is that:

1) The images on the buttons of some dirty color, and should be white

2) The selected item is highlighted in a little darker background color. Now he does not highlighted at all.

Here's how I define design in AppDelegate.m in application:didFinishLaunchingWithOptions

    // Background image for TabBar
    UIImage *backgroundDownImage = [UIImage imageNamed:@"background_320_49.png"];
    // Mode UIImageResizingModeStretch
    backgroundDownImage = [backgroundDownImage resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeStretch];
    // Set background image for all UITabBar in application
    [[UITabBar appearance] setBackgroundImage:backgroundDownImage];
    // White color for TabBar buttons
    [[UITabBar appearance] setTintColor:[UIColor whiteColor]];

    // Special font for all UITabBarItem
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Xnjslkpqqovrwqxfnmropbgqtzp" size:0], UITextAttributeFont, nil] forState:UIControlStateNormal];
```

<p>I tried the 4 variants:</p>

<p><br>1) In the method - (id)initWithNibName old code setFinishedSelectedImage + withFinishedUnselectedImage
<br>2) In the method - (id)initWithNibName new code setImage + SetSelectedImage
<br>3) In the method - (void)viewDidLoad old code
<br>4) In the method - (void)viewDidLoad new code</p>

<pre class="lang-c prettyprint-override"><code>- (void)viewDidLoad
{
    [super viewDidLoad];
    // Variant 1
    [self.tabBarItem setImage:[[UIImage imageNamed:@"Live.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal]];
    [self.tabBarItem setSelectedImage:[[UIImage imageNamed:@"Live.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal]];

    // Variant 2
    //[self.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"Live.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"Live.png"]];

    [CommonUse showLiveVideoFromController:self];
}
</code>```

In all cases, icons will be displayed. Method initWithNibName (options 1 and 2) no action at all on the color icon has not. Method viewDidLoad work  both old and new code - but in a strange way. When you first run the application, only the first icon is white, and all the other gray. If you click on any other icon and then go back to the first, this icon becomes white (but only a picture! Text is still gray).
It turns out that the color of icons affects only method viewDidLoad but not entirely - something else is missing.

Maybe draw two sets of icons for Selected and NoSelected. That was in the icon and image and text description as graphic. But still remain two points: 1) When you first start the application, all the icons will be gray, and only the first will be white. 2) When you change the width of the screen, do not disperse if the buttons.

答:
To change a color for unselected items (icons) you can use UITabBar property unselectedItemTintColor

```<code>[UITabBar appearance].unselectedItemTintColor = [UIColor anyColor];
</code>```

Body:
iOS 7.0.

I need to make your design UITabBar. The picture (this link) shows how it looks now and how it should look. The difference is that:

1) The images on the buttons of some dirty color, and should be white

2) The selected item is highlighted in a little darker background color. Now he does not highlighted at all.

Here's how I define design in AppDelegate.m in application:didFinishLaunchingWithOptions

    // Background image for TabBar
    UIImage *backgroundDownImage = [UIImage imageNamed:@"background_320_49.png"];
    // Mode UIImageResizingModeStretch
    backgroundDownImage = [backgroundDownImage resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeStretch];
    // Set background image for all UITabBar in application
    [[UITabBar appearance] setBackgroundImage:backgroundDownImage];
    // White color for TabBar buttons
    [[UITabBar appearance] setTintColor:[UIColor whiteColor]];

    // Special font for all UITabBarItem
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Xnjslkpqqovrwqxfnmropbgqtzp" size:0], UITextAttributeFont, nil] forState:UIControlStateNormal];

I tried the 4 variants:

1) In the method - (id)initWithNibName old code setFinishedSelectedImage + withFinishedUnselectedImage

2) In the method - (id)initWithNibName new code setImage + SetSelectedImage

3) In the method - (void)viewDidLoad old code

4) In the method - (void)viewDidLoad new code

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Variant 1
    [self.tabBarItem setImage:[[UIImage imageNamed:@"Live.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal]];
    [self.tabBarItem setSelectedImage:[[UIImage imageNamed:@"Live.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal]];

    // Variant 2
    //[self.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"Live.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"Live.png"]];

    [CommonUse showLiveVideoFromController:self];
}

In all cases, icons will be displayed. Method initWithNibName (options 1 and 2) no action at all on the color icon has not. Method viewDidLoad work  both old and new code - but in a strange way. When you first run the application, only the first icon is white, and all the other gray. If you click on any other icon and then go back to the first, this icon becomes white (but only a picture! Text is still gray).
It turns out that the color of icons affects only method viewDidLoad but not entirely - something else is missing.

Maybe draw two sets of icons for Selected and NoSelected. That was in the icon and image and text description as graphic. But still remain two points: 1) When you first start the application, all the icons will be gray, and only the first will be white. 2) When you change the width of the screen, do not disperse if the buttons.

Body:
To change a color for unselected items (icons) you can use UITabBar property unselectedItemTintColor

[UITabBar appearance].unselectedItemTintColor = [UIColor anyColor];


来源: stackexchange

问:
Lightgbm OSError, Library not loaded
If I simply do:

```<code>import lightgbm as lgb
</code>```

I'm getting

```<code>python script.py
Traceback (most recent call last):
File "script.py", line 4, in <module>
import lightgbm as lgb
File "/usr/local/lib/python2.7/site-packages/lightgbm/__init__.py", line 8, in <module>
from .basic import Booster, Dataset
File "/usr/local/lib/python2.7/site-packages/lightgbm/basic.py", line 31, in <module>
_LIB = _load_lib()
File "/usr/local/lib/python2.7/site-packages/lightgbm/basic.py", line 26, in _load_lib
lib = ctypes.cdll.LoadLibrary(lib_path[0])
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 440, in LoadLibrary
return self._dlltype(name)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 362, in __init__
self._handle = _dlopen(self._name, mode)
OSError: dlopen(/usr/local/lib/python2.7/site-packages/lightgbm/lib_lightgbm.so, 6): Library not loaded: /usr/local/opt/gcc/lib/gcc/7/libgomp.1.dylib
Referenced from: /usr/local/lib/python2.7/site-packages/lightgbm/lib_lightgbm.so
Reason: image not found
</code>```

I seem to have everything installed correct:

```<code>python -m pip install lightgbm
Requirement already satisfied: lightgbm in /usr/local/lib/python2.7/site-packages
Requirement already satisfied: wheel in /usr/local/lib/python2.7/site-packages (from lightgbm)
Requirement already satisfied: scikit-learn in /usr/local/lib/python2.7/site-packages (from lightgbm)
Requirement already satisfied: scipy in /usr/local/lib/python2.7/site-packages (from lightgbm)
Requirement already satisfied: numpy in /usr/local/lib/python2.7/site-packages (from lightgbm)
</code>```

I do have a 6 folder in my GCC folder.  Should I need to install another version of GCC for this to work?

答:
I find a similar problem here LightGBM

The answer and comment may help you.

Build LightGBM in Mac:

brew install cmake
brew install gcc --without-multilib
git clone --recursive https://github.com/Microsoft/LightGBM ; cd LightGBM
mkdir build ; cd build
cmake ..
make -j
```

<p>Then install:</p>

<pre class="lang-bash prettyprint-override"><code>cd ../python-packages
sudo python setup.py install --precompile
</code>```

As stated by @ecodan, you might need to force Mac to use GCC and G++ instead of the default compiler. So instead of building with cmake .., try:

cmake -DCMAKE_C_COMPILER=/usr/local/Cellar/gcc/6.1.0/bin/gcc-6 -DCMAKE_CXX_COMPILER=/usr/local/Cellar/gcc/6.1.0/bin/g++-6 ..
```

ajusting the versions to match yours.

ContentLicense: CC BY-SA 3.0

Title: Lightgbm OSError, Library not loaded

Body:
If I simply do:

import lightgbm as lgb

I'm getting

python script.py
Traceback (most recent call last):
File "script.py", line 4, in <module>
import lightgbm as lgb
File "/usr/local/lib/python2.7/site-packages/lightgbm/__init__.py", line 8, in <module>
from .basic import Booster, Dataset
File "/usr/local/lib/python2.7/site-packages/lightgbm/basic.py", line 31, in <module>
_LIB = _load_lib()
File "/usr/local/lib/python2.7/site-packages/lightgbm/basic.py", line 26, in _load_lib
lib = ctypes.cdll.LoadLibrary(lib_path[0])
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 440, in LoadLibrary
return self._dlltype(name)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 362, in __init__
self._handle = _dlopen(self._name, mode)
OSError: dlopen(/usr/local/lib/python2.7/site-packages/lightgbm/lib_lightgbm.so, 6): Library not loaded: /usr/local/opt/gcc/lib/gcc/7/libgomp.1.dylib
Referenced from: /usr/local/lib/python2.7/site-packages/lightgbm/lib_lightgbm.so
Reason: image not found

I seem to have everything installed correct:

python -m pip install lightgbm
Requirement already satisfied: lightgbm in /usr/local/lib/python2.7/site-packages
Requirement already satisfied: wheel in /usr/local/lib/python2.7/site-packages (from lightgbm)
Requirement already satisfied: scikit-learn in /usr/local/lib/python2.7/site-packages (from lightgbm)
Requirement already satisfied: scipy in /usr/local/lib/python2.7/site-packages (from lightgbm)
Requirement already satisfied: numpy in /usr/local/lib/python2.7/site-packages (from lightgbm)

I do have a 6 folder in my GCC folder.  Should I need to install another version of GCC for this to work?

Body:
I find a similar problem here LightGBM

The answer and comment may help you.

Build LightGBM in Mac:

brew install cmake
brew install gcc --without-multilib
git clone --recursive https://github.com/Microsoft/LightGBM ; cd LightGBM
mkdir build ; cd build
cmake ..
make -j

Then install:

cd ../python-packages
sudo python setup.py install --precompile

As stated by @ecodan, you might need to force Mac to use GCC and G++ instead of the default compiler. So instead of building with cmake .., try:

cmake -DCMAKE_C_COMPILER=/usr/local/Cellar/gcc/6.1.0/bin/gcc-6 -DCMAKE_CXX_COMPILER=/usr/local/Cellar/gcc/6.1.0/bin/g++-6 ..

ajusting the versions to match yours.

ContentLicense: CC BY-SA 4.0


问:
How to trigger the scenario outlines with examples data mentioned in an external file- Cucumber JVM?
I would like to trigger my scenario outline with data from an excel document instead of mentioning the data in the feature file. Is there any way to modify the examples data at run-time ?</p>

答:
If you are using a scenario outline then there is no use of using excel. If you are using a excel then you have to reload the page for every record of test data whereas in scenario outline each record considered as different test case.
So my suggestion would be to specify data in feature file itself. </p>


问:
Azure table with Silverlight 4
I'm looking for a way to manage Azure table with Silverlight 4,
can someone tell me where can I find something useful?</p>

答:
The new RIA Services toolkit has a Table storage domainservice provider which would probably be what you need.
http://jeffhandley.com/archive/2010/12/02/ToolkitDecember2010.aspx

Alternatively heres another, slightly older example someone has put together:
http://www.codeproject.com/KB/silverlight/Azurelight.aspx

ContentLicense: CC BY-SA 2.5

Title: Azure table with Silverlight 4


问:
Rows are not binding when jqGrid is loaded with datatable
Hi I am loading a jqGrid dynamically on a button click, i am able to get a Column headers but rows are not being shown. Data is being sent but its not getting displayed. Please find below sample code for reference.

View:

```<code>@{
    ViewBag.Title = "JQGridExample";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>

<h2>JQGridExample</h2>

<div class="editor-label">
    @Html.Label("ConnectionString")
</div>
<div class="editor-field">
    @Html.TextBox("ConnectionString")
</div>

<div class="editor-label">
    @Html.Label("Query")
</div>
<div class="editor-field">
    @Html.TextArea("Query")
</div>

<button type="submit" id="btnGetData" name="Command" value="GetData" onclick="return GetData();" class="btn">Get Data</button>

<div id="dvJqGrid" class="dvjq">
    <table id="grid" class="scroll"></table>
    <div id="pager" class="scroll" style="text-align: center;"></div>
</div>

<script type="text/javascript">

function GetData() {
 setTimeout(function () { $('#dvLoader').show();},1);
 var ConnectionString = document.getElementById("ConnectionString").value;
 var Query = document.getElementById("Query").value;

 $("#dvJqGrid").empty();
 $("#dvJqGrid").append($("<table>").attr("id", "grid"));
 $("#dvJqGrid").append($("<div>").attr("id", "pager"));

 $.ajax(
 {
  type: "POST",
  url: "/MultiTemplate/JQGridGetDataWithColumn",
  data: { "ConnectionString": ConnectionString, "Query": Query },
  dataType: "json",
  success: function (result) {
      debugger;
   $("#Result").val(result.Msg);
   colD = result.colData;
   colN = JSON.parse(result.colNames);
   colM = JSON.parse(result.colModel);

   var SQL = ConnectionString;
   var Oracle = ConnectionString;
   $("#grid").jqGrid({
    jsonReader: {
     cell: "",
     id: "0"
    },
    url: '/MultiTemplate/JQGridGetData',
    postData: { ConnectionString: ConnectionString, Query: Query},
    datatype: 'json',
    mtype: 'POST',
    datastr: colD,
    colNames: colN,
    colModel: colM,
    pager: jQuery('#pager'),
    rowNum: 5,
    page: 1,
    rowList: [5, 10, 20, 50],
    viewrecords: true,
    loadonce: true
   });
   $('#dvLoader').hide();
  },
  error: function (x, e) {
   $('#dvLoader').hide();
  }
 });
 setTimeout(function () { $('#dvLoader').hide(); }, 1000);
 return false;
}
</script>
</code>```

Controller:

```<code>public ActionResult JQGridExample()
        {
            return View();
        }

        public string JQGridGetData(string sidx, string sord, int page, int rows, string ConnectionString, string Query)
        {
            try
            {
                try
                {
                    DataTable dt = new DataTable();
                    dt.Clear();
                    dt.Columns.Add("Name");
                    dt.Columns.Add("Marks");
                    dt.Columns.Add("Status");
                    DataRow _ravi = dt.NewRow();
                    _ravi["Name"] = "ravi";
                    _ravi["Marks"] = "500";
                    _ravi["Status"] = "Pass";
                    DataRow _ravi1 = dt.NewRow();
                    _ravi1["Name"] = "ravi1";
                    _ravi1["Marks"] = "5001";
                    _ravi1["Status"] = "Pass1";
                    DataRow _ravi2 = dt.NewRow();
                    _ravi2["Name"] = "ravi";
                    _ravi2["Marks"] = "500";
                    _ravi2["Status"] = "Pass";
                    DataRow _ravi3 = dt.NewRow();
                    _ravi3["Name"] = "ravi1";
                    _ravi3["Marks"] = "5001";
                    _ravi3["Status"] = "Pass1";
                    DataRow _ravi4 = dt.NewRow();
                    _ravi4["Name"] = "ravi";
                    _ravi4["Marks"] = "500";
                    _ravi4["Status"] = "Pass";
                    DataRow _ravi15 = dt.NewRow();
                    _ravi15["Name"] = "ravi1";
                    _ravi15["Marks"] = "5001";
                    _ravi15["Status"] = "Pass1";
                    DataRow _ravi6 = dt.NewRow();
                    _ravi6["Name"] = "ravi";
                    _ravi6["Marks"] = "500";
                    _ravi6["Status"] = "Pass";
                    DataRow _ravi17 = dt.NewRow();
                    _ravi17["Name"] = "ravi1";
                    _ravi17["Marks"] = "5001";
                    _ravi17["Status"] = "Pass1";
                    dt.Rows.Add(_ravi1);
                    dt.Rows.Add(_ravi);
                    dt.Rows.Add(_ravi2);
                    dt.Rows.Add(_ravi3);
                    dt.Rows.Add(_ravi4);
                    dt.Rows.Add(_ravi15);
                    dt.Rows.Add(_ravi6);
                    dt.Rows.Add(_ravi17);
                    if (dt.Rows.Count > 0)
                    {
                        string StringData = ConvertDataTabletoString(dt);

                        return StringData;
                    }
                    else
                    {
                        Exception exx = new Exception();
                        throw exx;
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Result = ex.Message;
                    return "";
                }
            }
            catch (Exception ex)
            {
                return "";
            }

        }

        public JsonResult JQGridGetDataWithColumn(string ConnectionString, string Query)
        {
            try
            {
                try
                {
                    DataTable dt = new DataTable();
                    dt.Clear();
                    dt.Columns.Add("Name");
                    dt.Columns.Add("Marks");
                    dt.Columns.Add("Status");
                    DataRow _ravi = dt.NewRow();
                    _ravi["Name"] = "ravi";
                    _ravi["Marks"] = "500";
                    _ravi["Status"] = "Pass";
                    DataRow _ravi1 = dt.NewRow();
                    _ravi1["Name"] = "ravi1";
                    _ravi1["Marks"] = "5001";
                    _ravi1["Status"] = "Pass1";
                    DataRow _ravi2 = dt.NewRow();
                    _ravi2["Name"] = "ravi";
                    _ravi2["Marks"] = "500";
                    _ravi2["Status"] = "Pass";
                    DataRow _ravi3 = dt.NewRow();
                    _ravi3["Name"] = "ravi1";
                    _ravi3["Marks"] = "5001";
                    _ravi3["Status"] = "Pass1";
                    DataRow _ravi4 = dt.NewRow();
                    _ravi4["Name"] = "ravi";
                    _ravi4["Marks"] = "500";
                    _ravi4["Status"] = "Pass";
                    DataRow _ravi15 = dt.NewRow();
                    _ravi15["Name"] = "ravi1";
                    _ravi15["Marks"] = "5001";
                    _ravi15["Status"] = "Pass1";
                    DataRow _ravi6 = dt.NewRow();
                    _ravi6["Name"] = "ravi";
                    _ravi6["Marks"] = "500";
                    _ravi6["Status"] = "Pass";
                    DataRow _ravi17 = dt.NewRow();
                    _ravi17["Name"] = "ravi1";
                    _ravi17["Marks"] = "5001";
                    _ravi17["Status"] = "Pass1";
                    dt.Rows.Add(_ravi1);
                    dt.Rows.Add(_ravi);
                    dt.Rows.Add(_ravi2);
                    dt.Rows.Add(_ravi3);
                    dt.Rows.Add(_ravi4);
                    dt.Rows.Add(_ravi15);
                    dt.Rows.Add(_ravi6);
                    dt.Rows.Add(_ravi17);
                    if (dt.Rows.Count > 0)
                    {
                        string StringData = ConvertDataTabletoString(dt);
                        string[] columns = dt.Columns.Cast<DataColumn>()
                           .Select(x => x.ColumnName)
                           .ToArray();
                        string columnNames = ConvertStringArrayToString(columns);
                        string columnModel = ConvertStringArrayToStringModel(columns);
                        return Json(new { colData = StringData, colNames = columnNames, colModel = columnModel, Msg = "Data Successfully Loaded" }, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        Exception exx = new Exception();
                        throw exx;
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Result = ex.Message;
                    return Json(new { Msg = ex.Message }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { Msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        public string ConvertDataTabletoString(DataTable dt)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<String, object>> rows = new List<Dictionary<String, object>>();
            Dictionary<String,object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<String, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return serializer.Serialize(rows);
        }

        static string ConvertStringArrayToString(string[] array)
        {
            string result = string.Join("\",\"", array);
            result = "[\"" + result + "\"]";
            return result;
        }

        public string ConvertStringArrayToStringModel(string[] array)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("[");
            foreach (string value in array)
            {
                builder.Append("{ \"name\":\"");
                builder.Append(value);
                builder.Append("\",\"index\":\"");
                builder.Append(value);
                builder.Append("\"},");
            }
            builder = builder.Remove(builder.Length - 1, 1);
            builder.Append("]");
            return builder.ToString();
        }
</code>```

答:
In fact, we can improve your code to a great extent. But, with minimal changes I have given you a solution. Just see the changes in view alone, you will be able get the grid data in browser for sure.

View

```<code>@{
    ViewBag.Title = "JQGridExample";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>

<h2>JQGridExample</h2>

<div class="editor-label">
    @Html.Label("ConnectionString")
</div>
<div class="editor-field">
    @Html.TextBox("ConnectionString")
</div>

<div class="editor-label">
    @Html.Label("Query")
</div>
<div class="editor-field">
    @Html.TextArea("Query")
</div>

<button type="submit" id="btnGetData" name="Command" value="GetData" onclick="return GetData();" class="btn">Get Data</button>

<div id="dvJqGrid" class="dvjq">
    <table id="grid" class="scroll"></table>
    <div id="pager" class="scroll" style="text-align: center;"></div>
</div>

<script type="text/javascript">

function GetData() {
 setTimeout(function () { $('#dvLoader').show();},1);
 var ConnectionString = document.getElementById("ConnectionString").value;
 var Query = document.getElementById("Query").value;

 $.ajax(
 {
  type: "POST",
  url: "/MultiTemplate/JQGridGetDataWithColumn",
  data: { "ConnectionString": ConnectionString, "Query": Query },
  dataType: "json",
  success: function (result) {
      debugger;
   $("#Result").val(result.Msg);
    colD = JSON.parse(result.colData);
    colN = JSON.parse(result.colNames);
    colM = JSON.parse(result.colModel);

    $("#grid").jqGrid({
        jsonReader: {
            repeatitems: false,
            root: function (obj) {
                return obj;
            },
            page: function (obj) {
                return 1;
            },
            total: function (obj) {
                return 1;
            },
            records: function (obj) {
                return obj.length;
            }
        },

        datatype: 'jsonstring',
        datastr: colD,

        colNames: colN,
        colModel: colM,
        pager: '#pager',
        rowNum: 1000,
        page: 1,
        rowList: [10, 15, 20, 25],
        viewrecords: true,
        loadonce: true
    });
   $('#dvLoader').hide();
  },
  error: function (x, e) {
   $('#dvLoader').hide();
  }
 });
 setTimeout(function () { $('#dvLoader').hide(); }, 1000);
 return false;
}
</script>
</code>```

Body:
Hi I am loading a jqGrid dynamically on a button click, i am able to get a Column headers but rows are not being shown. Data is being sent but its not getting displayed. Please find below sample code for reference.

View:

@{
    ViewBag.Title = "JQGridExample";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />

JQGridExample

    @Html.Label("ConnectionString")

    @Html.TextBox("ConnectionString")

    @Html.Label("Query")

    @Html.TextArea("Query")

<button type="submit" id="btnGetData" name="Command" value="GetData" onclick="return GetData();" class="btn">Get Data</button>

Controller:

public ActionResult JQGridExample()
        {
            return View();
        }

        public string JQGridGetData(string sidx, string sord, int page, int rows, string ConnectionString, string Query)
        {
            try
            {
                try
                {
                    DataTable dt = new DataTable();
                    dt.Clear();
                    dt.Columns.Add("Name");
                    dt.Columns.Add("Marks");
                    dt.Columns.Add("Status");
                    DataRow _ravi = dt.NewRow();
                    _ravi["Name"] = "ravi";
                    _ravi["Marks"] = "500";
                    _ravi["Status"] = "Pass";
                    DataRow _ravi1 = dt.NewRow();
                    _ravi1["Name"] = "ravi1";
                    _ravi1["Marks"] = "5001";
                    _ravi1["Status"] = "Pass1";
                    DataRow _ravi2 = dt.NewRow();
                    _ravi2["Name"] = "ravi";
                    _ravi2["Marks"] = "500";
                    _ravi2["Status"] = "Pass";
                    DataRow _ravi3 = dt.NewRow();
                    _ravi3["Name"] = "ravi1";
                    _ravi3["Marks"] = "5001";
                    _ravi3["Status"] = "Pass1";
                    DataRow _ravi4 = dt.NewRow();
                    _ravi4["Name"] = "ravi";
                    _ravi4["Marks"] = "500";
                    _ravi4["Status"] = "Pass";
                    DataRow _ravi15 = dt.NewRow();
                    _ravi15["Name"] = "ravi1";
                    _ravi15["Marks"] = "5001";
                    _ravi15["Status"] = "Pass1";
                    DataRow _ravi6 = dt.NewRow();
                    _ravi6["Name"] = "ravi";
                    _ravi6["Marks"] = "500";
                    _ravi6["Status"] = "Pass";
                    DataRow _ravi17 = dt.NewRow();
                    _ravi17["Name"] = "ravi1";
                    _ravi17["Marks"] = "5001";
                    _ravi17["Status"] = "Pass1";
                    dt.Rows.Add(_ravi1);
                    dt.Rows.Add(_ravi);
                    dt.Rows.Add(_ravi2);
                    dt.Rows.Add(_ravi3);
                    dt.Rows.Add(_ravi4);
                    dt.Rows.Add(_ravi15);
                    dt.Rows.Add(_ravi6);
                    dt.Rows.Add(_ravi17);
                    if (dt.Rows.Count > 0)
                    {
                        string StringData = ConvertDataTabletoString(dt);

                        return StringData;
                    }
                    else
                    {
                        Exception exx = new Exception();
                        throw exx;
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Result = ex.Message;
                    return "";
                }
            }
            catch (Exception ex)
            {
                return "";
            }

        }

        public JsonResult JQGridGetDataWithColumn(string ConnectionString, string Query)
        {
            try
            {
                try
                {
                    DataTable dt = new DataTable();
                    dt.Clear();
                    dt.Columns.Add("Name");
                    dt.Columns.Add("Marks");
                    dt.Columns.Add("Status");
                    DataRow _ravi = dt.NewRow();
                    _ravi["Name"] = "ravi";
                    _ravi["Marks"] = "500";
                    _ravi["Status"] = "Pass";
                    DataRow _ravi1 = dt.NewRow();
                    _ravi1["Name"] = "ravi1";
                    _ravi1["Marks"] = "5001";
                    _ravi1["Status"] = "Pass1";
                    DataRow _ravi2 = dt.NewRow();
                    _ravi2["Name"] = "ravi";
                    _ravi2["Marks"] = "500";
                    _ravi2["Status"] = "Pass";
                    DataRow _ravi3 = dt.NewRow();
                    _ravi3["Name"] = "ravi1";
                    _ravi3["Marks"] = "5001";
                    _ravi3["Status"] = "Pass1";
                    DataRow _ravi4 = dt.NewRow();
                    _ravi4["Name"] = "ravi";
                    _ravi4["Marks"] = "500";
                    _ravi4["Status"] = "Pass";
                    DataRow _ravi15 = dt.NewRow();
                    _ravi15["Name"] = "ravi1";
                    _ravi15["Marks"] = "5001";
                    _ravi15["Status"] = "Pass1";
                    DataRow _ravi6 = dt.NewRow();
                    _ravi6["Name"] = "ravi";
                    _ravi6["Marks"] = "500";
                    _ravi6["Status"] = "Pass";
                    DataRow _ravi17 = dt.NewRow();
                    _ravi17["Name"] = "ravi1";
                    _ravi17["Marks"] = "5001";
                    _ravi17["Status"] = "Pass1";
                    dt.Rows.Add(_ravi1);
                    dt.Rows.Add(_ravi);
                    dt.Rows.Add(_ravi2);
                    dt.Rows.Add(_ravi3);
                    dt.Rows.Add(_ravi4);
                    dt.Rows.Add(_ravi15);
                    dt.Rows.Add(_ravi6);
                    dt.Rows.Add(_ravi17);
                    if (dt.Rows.Count > 0)
                    {
                        string StringData = ConvertDataTabletoString(dt);
                        string[] columns = dt.Columns.Cast<DataColumn>()
                           .Select(x => x.ColumnName)
                           .ToArray();
                        string columnNames = ConvertStringArrayToString(columns);
                        string columnModel = ConvertStringArrayToStringModel(columns);
                        return Json(new { colData = StringData, colNames = columnNames, colModel = columnModel, Msg = "Data Successfully Loaded" }, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        Exception exx = new Exception();
                        throw exx;
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Result = ex.Message;
                    return Json(new { Msg = ex.Message }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { Msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        public string ConvertDataTabletoString(DataTable dt)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<String, object>> rows = new List<Dictionary<String, object>>();
            Dictionary<String,object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<String, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return serializer.Serialize(rows);
        }

        static string ConvertStringArrayToString(string[] array)
        {
            string result = string.Join("\",\"", array);
            result = "[\"" + result + "\"]";
            return result;
        }

        public string ConvertStringArrayToStringModel(string[] array)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("[");
            foreach (string value in array)
            {
                builder.Append("{ \"name\":\"");
                builder.Append(value);
                builder.Append("\",\"index\":\"");
                builder.Append(value);
                builder.Append("\"},");
            }
            builder = builder.Remove(builder.Length - 1, 1);
            builder.Append("]");
            return builder.ToString();
        }

Body:
In fact, we can improve your code to a great extent. But, with minimal changes I have given you a solution. Just see the changes in view alone, you will be able get the grid data in browser for sure.

View

@{
    ViewBag.Title = "JQGridExample";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>

<h2>JQGridExample</h2>

<div class="editor-label">
    @Html.Label("ConnectionString")
</div>
<div class="editor-field">
    @Html.TextBox("ConnectionString")
</div>

<div class="editor-label">
    @Html.Label("Query")
</div>
<div class="editor-field">
    @Html.TextArea("Query")
</div>

<button type="submit" id="btnGetData" name="Command" value="GetData" onclick="return GetData();" class="btn">Get Data</button>

<div id="dvJqGrid" class="dvjq">
    <table id="grid" class="scroll"></table>
    <div id="pager" class="scroll" style="text-align: center;"></div>
</div>

<script type="text/javascript">

function GetData() {
 setTimeout(function () { $('#dvLoader').show();},1);
 var ConnectionString = document.getElementById("ConnectionString").value;
 var Query = document.getElementById("Query").value;

 $.ajax(
 {
  type: "POST",
  url: "/MultiTemplate/JQGridGetDataWithColumn",
  data: { "ConnectionString": ConnectionString, "Query": Query },
  dataType: "json",
  success: function (result) {
      debugger;
   $("#Result").val(result.Msg);
    colD = JSON.parse(result.colData);
    colN = JSON.parse(result.colNames);
    colM = JSON.parse(result.colModel);

    $("#grid").jqGrid({
        jsonReader: {
            repeatitems: false,
            root: function (obj) {
                return obj;
            },
            page: function (obj) {
                return 1;
            },
            total: function (obj) {
                return 1;
            },
            records: function (obj) {
                return obj.length;
            }
        },

        datatype: 'jsonstring',
        datastr: colD,

        colNames: colN,
        colModel: colM,
        pager: '#pager',
        rowNum: 1000,
        page: 1,
        rowList: [10, 15, 20, 25],
        viewrecords: true,
        loadonce: true
    });
   $('#dvLoader').hide();
  },
  error: function (x, e) {
   $('#dvLoader').hide();
  }
 });
 setTimeout(function () { $('#dvLoader').hide(); }, 1000);
 return false;
}
</script>


问:
'cap deploy' doesn't restart puma but 'cap deploy:restart' does
After upgrading my ruby from 2.2.4 to 2.4.1 I starting facing this issue.

My server would be down after a cap deploy, but doing a cap deploy:restart just after works.

Capfile:

```<code>require 'capistrano/puma'
require 'capistrano/puma/jungle'
</code>```

deploy.rb:

```<code># ...

namespace :deploy do

  # after :restart, :clear_cache do
  #   on roles(:web), in: :groups, limit: 3, wait: 10 do
  #     # Here we can do anything such as:
  #     # within release_path do
  #     #   execute :rake, 'cache:clear'
  #     # end
  #   end
  # end

  desc 'Initial Deploy'
  task :initial do
    on roles(:app) do
      before 'deploy:restart', 'puma:start'
      invoke 'deploy'
    end
  end

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      invoke 'puma:restart'
    end
  end

  before :starting,     :check_revision
  # after  :finishing,    :compile_assets
  after  :finishing,    :cleanup
  after  :finishing,    :restart

  # https://github.com/airbrake/airbrake#capistrano
  after :finished, 'airbrake:deploy'
end
</code>```

Any help on how to diagnose the issue would be great as well.

答:
Add the capistrano-puma gem in gemfile(skip if already added):

```<code>gem 'capistrano3-puma' , group: :development
</code>```

Then, install the Capistrano::Puma plugin by adding the below line in Capfile:

```<code>install_plugin Capistrano::Puma
</code>```

This will include all necessary puma libraries.

And also, make you have set the puma config in deploy.rb file as below:

```<code>set :application,     'test-app'
...
...
set :puma_bind,       "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state,      "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"
</code>```

Now, try deploying your app.

Body:
After upgrading my ruby from 2.2.4 to 2.4.1 I starting facing this issue.

My server would be down after a cap deploy, but doing a cap deploy:restart just after works.

Capfile:

require 'capistrano/puma'
require 'capistrano/puma/jungle'

deploy.rb:

# ...

namespace :deploy do

  # after :restart, :clear_cache do
  #   on roles(:web), in: :groups, limit: 3, wait: 10 do
  #     # Here we can do anything such as:
  #     # within release_path do
  #     #   execute :rake, 'cache:clear'
  #     # end
  #   end
  # end

  desc 'Initial Deploy'
  task :initial do
    on roles(:app) do
      before 'deploy:restart', 'puma:start'
      invoke 'deploy'
    end
  end

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      invoke 'puma:restart'
    end
  end

  before :starting,     :check_revision
  # after  :finishing,    :compile_assets
  after  :finishing,    :cleanup
  after  :finishing,    :restart

  # https://github.com/airbrake/airbrake#capistrano
  after :finished, 'airbrake:deploy'
end

Any help on how to diagnose the issue would be great as well.

Body:
Add the capistrano-puma gem in gemfile(skip if already added):

gem 'capistrano3-puma' , group: :development

Then, install the Capistrano::Puma plugin by adding the below line in Capfile:

install_plugin Capistrano::Puma

This will include all necessary puma libraries.

And also, make you have set the puma config in deploy.rb file as below:

set :application,     'test-app'
...
...
set :puma_bind,       "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state,      "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"

Now, try deploying your app.


问:
Laravel And AJAX getting Intenal Server Error on model save method
Basically, I'm trying to send data that was sent from Ajax to Laravel controller. Problem is that I'm always getting AJAX error: error: Internal Server Error. I have googled a lot about this problem and found that I need to also send csrf token. So here's my ajax

```<code>$.ajax({
                url: '/customer/getAjax', // This is the url we gave in the route
                method: 'POST', // Type of response and matches what we said in the route
                beforeSend: function (xhr) {
                    var token = $('meta[name="csrf_token"]').attr('content');

                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }
                },
                data: obj, // a JSON object to send back
                success: function(response){ // What to do if we succeed
                    console.log("asds " + response);
                    $('#myModal').modal('toggle');
                },
                error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
                    console.log(JSON.stringify(jqXHR));
                    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                }
            });
</code>```

And here's my controller

```<code>class MainPage extends Controller
{

    public function store(Request $request)
    {
        $data = $request->all(); // This will get all the request data.

       // $this->validate($request, ['title' => 'required|max:100', 'body' => 'required|min:10']);

        $post = new Post;
        $post->user_id = $data['user_id'];
        $post->title = $data['title'];
        $post->body = $data['body'];
        $post->post_type = $data['post_type'];
        //$post->created_at = $data['created_at'];
        $post->user_name = $data['user_name'];
        $post->save(); // Here's where I get Error!!!

        return "Ok"
    }
</code>```

And also here's my route

```<code>Route::post('/customer/getAjax', 'MainPage@store');
</code>```

If I delete $post->save(); Everything is working and I even get response Ok, however data is not saved I also tried to include  <meta name="csrf-token" content="{{ csrf_token() }}"> in html head. However I get same issue.

答:
First add token to meta like here:

```<code><meta name="csrf-token" content="{{ csrf_token() }}">
</code>```

You should add in your ajax constructor next option

```<code>     method: 'POST',
     ....
     headers: {'X-CSRF-TOKEN': $('meta[name=csrf-token]').attr('content')},
     ....
</code>```

Body:
Basically, I'm trying to send data that was sent from Ajax to Laravel controller. Problem is that I'm always getting AJAX error: error: Internal Server Error. I have googled a lot about this problem and found that I need to also send csrf token. So here's my ajax

$.ajax({
                url: '/customer/getAjax', // This is the url we gave in the route
                method: 'POST', // Type of response and matches what we said in the route
                beforeSend: function (xhr) {
                    var token = $('meta[name="csrf_token"]').attr('content');

                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }
                },
                data: obj, // a JSON object to send back
                success: function(response){ // What to do if we succeed
                    console.log("asds " + response);
                    $('#myModal').modal('toggle');
                },
                error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
                    console.log(JSON.stringify(jqXHR));
                    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                }
            });

And here's my controller

class MainPage extends Controller
{

    public function store(Request $request)
    {
        $data = $request->all(); // This will get all the request data.

       // $this->validate($request, ['title' => 'required|max:100', 'body' => 'required|min:10']);

        $post = new Post;
        $post->user_id = $data['user_id'];
        $post->title = $data['title'];
        $post->body = $data['body'];
        $post->post_type = $data['post_type'];
        //$post->created_at = $data['created_at'];
        $post->user_name = $data['user_name'];
        $post->save(); // Here's where I get Error!!!

        return "Ok"
    }

And also here's my route

Route::post('/customer/getAjax', 'MainPage@store');

If I delete $post->save(); Everything is working and I even get response Ok, however data is not saved I also tried to include  <meta name="csrf-token" content="{{ csrf_token() }}"> in html head. However I get same issue.

Body:
First add token to meta like here:

<meta name="csrf-token" content="{{ csrf_token() }}">

You should add in your ajax constructor next option

     method: 'POST',
     ....
     headers: {'X-CSRF-TOKEN': $('meta[name=csrf-token]').attr('content')},
     ....


问:
Multiple-File Template Implementation
With normal functions, the declaration and definition are often separated across multiple files like so:

```<code>// Foo.h

namespace Foo
{
    void Bar();
}
</code>```

.

```<code>// Foo.cpp

#include "Foo.h"

void Foo::Bar()
{
    cout << "Inside function." << endl;
}
</code>```

It is my understanding that this cannot be done with templates.  The declaration and definition must not be separate because the appropriate form of the template is created "on-demand" when needed.

So, how and where are templates typically defined in a multiple-file project like this?  My intuition is that it would be in Foo.cpp because that's where the "meat" of functions normally is, but on the other hand it's the header file that's going to be included.

答:
I'm disappointed that no answers mentioned that the C++ standard permits you to separate the definition from the declaration. It goes like this:

```<code>// Foo.h
export template<class T> T f();
</code>```

```<code>// Foo.cpp
#include "Foo.h"

export template<class T> T f()
{
    // blah blah
}
</code>```

Unfortunately, almost no compilers support export. Comeau is one that does.

However, export is removed from C++ in C++0x.

Title: Multiple-File Template Implementation

Body:
With normal functions, the declaration and definition are often separated across multiple files like so:

// Foo.h

namespace Foo
{
    void Bar();
}

.

// Foo.cpp

#include "Foo.h"

void Foo::Bar()
{
    cout << "Inside function." << endl;
}

It is my understanding that this cannot be done with templates.  The declaration and definition must not be separate because the appropriate form of the template is created "on-demand" when needed.

So, how and where are templates typically defined in a multiple-file project like this?  My intuition is that it would be in Foo.cpp because that's where the "meat" of functions normally is, but on the other hand it's the header file that's going to be included.

Body:
I'm disappointed that no answers mentioned that the C++ standard permits you to separate the definition from the declaration. It goes like this:

// Foo.h
export template<class T> T f();

// Foo.cpp
#include "Foo.h"

export template<class T> T f()
{
    // blah blah
}

Unfortunately, almost no compilers support export. Comeau is one that does.

However, export is removed from C++ in C++0x.


问:
Check if a pointer points to a valid structure
I have N statically allocated structures.

```<code>struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */
</code>```

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.

答:
There is no language method but in some circumstances you can try to have some known values at the certain points of the structure. If the pointed memory location has those values you can assume it as valid - but of course you do not have any guarantee. But you need to write your own functions when you create the structure, and when you destroy it (by filling with zeros before freeing the memory). It is a very week workaround - but if you connect with another measures and accept the overhead it makes the probability of the incorrect program behaviour lower.

Sometimes it is called a security cookie.

it is possible of course to make it more complicated - at certain positions you have only offsets to those cookies. It makes less probable that the random position in the memory will have such a chain of data :)

Body:
I have N statically allocated structures.

struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.


问:
Is any JavaScript code a valid TypeScript code?
Currently I've started to learn TypeScript. From the documents I've studied for TypeScript, I saw some samples that pure JavaScript code could be compiled as TypeScript code.

My question is: Is TypeScript language designed in a way that any JavaScript code will be a valid TypeScript code?

i.e. is any .js file a valid .ts file?

答:
Let's assume valid code means : is syntactically correct with respect to the language specifications.

Then the answer is YES.

It is written down in the TypeScript Specifications (second paragraph) :

TypeScript is a syntactic sugar for JavaScript.
  TypeScript syntax is a superset of ECMAScript 2015 (ES2015)syntax.
  Every JavaScript program is also a TypeScript program.

(emphasis mine)

Now, most often you don't want basic JavaScript to be used "uncontrolled". After all, that was one of the reasons to create the TypeScript language in the first place !

Nevertheless, a valid JavaScript program is technically valid TypeScript. This is in the specifications probably by need of "backward compatibility", or, better formulated, by need of supersedence to ECMAScript

To take the example of another answer, the Typescript code

```<code>var testVar = 4;
testVar = "asdf";
</code>```

will be transpiled into exactly the same JavaScript code (with all default compiler options)

Demonstration here on Typescriptlang.org playground

even though there is a TypeScript error, this doesn't prevent a valid javascript to be output from there. It "compiles with error". (I wish this was called a warning instead of error, but anyway).

See also : https://basarat.gitbooks.io/typescript/content/docs/why-typescript.html

Your JavaScript is TypeScript

TypeScript provides compile time type
  safety for your JavaScript code. This is no surprise given its name.
  The great thing is that the types are completely optional. Your
  JavaScript code .js file can be renamed to a .ts file and TypeScript
  will still give you back valid .js equivalent to the original
  JavaScript file. TypeScript is intentionally and strictly a superset
  of JavaScript with optional Type checking.

The simplest option that can deactivate this behavior (output js even though there are Type errors) is --noEmitOnError

Body:
Let's assume valid code means : is syntactically correct with respect to the language specifications.

Then the answer is YES.

It is written down in the TypeScript Specifications (second paragraph) :

TypeScript is a syntactic sugar for JavaScript.
  TypeScript syntax is a superset of ECMAScript 2015 (ES2015)syntax.
  Every JavaScript program is also a TypeScript program.

(emphasis mine)

Now, most often you don't want basic JavaScript to be used "uncontrolled". After all, that was one of the reasons to create the TypeScript language in the first place !

Nevertheless, a valid JavaScript program is technically valid TypeScript. This is in the specifications probably by need of "backward compatibility", or, better formulated, by need of supersedence to ECMAScript

To take the example of another answer, the Typescript code

var testVar = 4;
testVar = "asdf";

will be transpiled into exactly the same JavaScript code (with all default compiler options)

Demonstration here on Typescriptlang.org playground

even though there is a TypeScript error, this doesn't prevent a valid javascript to be output from there. It "compiles with error". (I wish this was called a warning instead of error, but anyway).

See also : https://basarat.gitbooks.io/typescript/content/docs/why-typescript.html

Your JavaScript is TypeScript

TypeScript provides compile time type
  safety for your JavaScript code. This is no surprise given its name.
  The great thing is that the types are completely optional. Your
  JavaScript code .js file can be renamed to a .ts file and TypeScript
  will still give you back valid .js equivalent to the original
  JavaScript file. TypeScript is intentionally and strictly a superset
  of JavaScript with optional Type checking.

The simplest option that can deactivate this behavior (output js even though there are Type errors) is --noEmitOnError


问:
How does Quartz store job details between restarts (regarding last successful run, misfires etc.)?
A task is scheduled in the Quartz-scheduler for every hour, starting at 9 AM.
Application stops at 10 AM and is restarted at 12 PM. In that case two executions at 10 AM and 11 AM will be missed.

In that case when Scheduler starts again, how many misfires will be considered?

As job was executed at 9AM, it should consider two misfires from 10 AM and 11 AM. If it is so, then how can Quartz identify the last successful schedule as application is already restarted?

答:
You are asking two questions:

How many misfires will be considered?

As you guessed, two misfires (10 AM and 11 AM) will be detected.

However, Quartz may or may not consider all of them: depending on the misfire instruction configured in each trigger, Quartz may decide to just consider the last misfire, or ignore them all.

How does Quartz store job details between restarts?

Depending on your configuration, Quartz will store job data in a database via its JDBCJobStore (Java) / AdoJobStore (.NET), or in RAM via its RAMJobStore.

When using a database store, Quartz will persist all job details to it as they are scheduled, run, finished etc.; and retrieve said details from it upon restart.

When using a RAM store, job information will not be persisted between Scheduler runs. If the Scheduler gets stopped and then restarted, all jobs will need to be scheduled again; also, no misfires will be detected.

All of this is explained in Quartz's official documentation, I suggest that you take a look around over there for more detailed info.


问:
409 conflict error when i try mvn appengine:update
After i perform mvn appengine:devserver,
i set my project key using:
gcloud config set project {my-key}
 and i run mvn appengine:update, i receive this error ::::

com.google.appengine.tools.admin.HttpIoException: Error posting to URL: https://appengine.google.com/api/appversion/create?module=apol-web&app_id=apol-145566&version=1&
409 Conflict
Another transaction by user arokoyuolalekan is already in progress for app: e~apol-145566, version: 1. That user can undo the transaction with "appcfg rollback".

Please what do i do to solve it.

答:
I just solve the problem by rolling back the ongoing transaction using this maven command on the command prompt:</p>

```<code>mvn appengine:rollback
</code>```

Body:
I just solve the problem by rolling back the ongoing transaction using this maven command on the command prompt:

mvn appengine:rollback


问:
Pause or stop the video when close icon is clicked
i want to pause/stop the video when close(X) icon is pressed.
Now when i click the X button video keeps playing in the background.
 Also i want that the close icon should come on the player itseld not outside the player.

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('hideStr').click(function(){
  $(".playvideo").pause();       // Tag name used as a selector
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}</code>```

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>

```

答:
They problem's are:

Selector Was wrong in your dom

And hideStr id not in your html.and also its not correct selector of the close button

pause()' its dom object not jquery so try withelemnt[0]`

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('#hideStr').click(function(){
  $("#playvideo")[0].pause();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}</code>```

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close" id="hideStr">X</button>

```

Body:
i want to pause/stop the video when close(X) icon is pressed.
Now when i click the X button video keeps playing in the background.
 Also i want that the close icon should come on the player itseld not outside the player.

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('hideStr').click(function(){
  $(".playvideo").pause();       // Tag name used as a selector
});

div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>

Body:
They problem's are:

Selector Was wrong in your dom

And hideStr id not in your html.and also its not correct selector of the close button

pause()' its dom object not jquery so try withelemnt[0]`

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('#hideStr').click(function(){
  $("#playvideo")[0].pause();
});

div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close" id="hideStr">X</button>
 </div>


问:
How to call web service Asynchronously in Tibco BW?
I am able to call web service synchronously in tibco BW using SOAP Request Reply but unable to call asynchronously.
Can anyone please help me how to call web service asynchronously in tibco.

答:
In Asynchronously communication client or request input will do it's work without waiting for response  instantaneously after sending the message.
We can use SOAP over JMS to accomplish Asynchronous web service calls. A SOAP/JMS binding must be stated in the WSDL and the web service provider must be listening on the related queue or topic. We can utilize the SOAP Request Reply activity to call a web service over JMS.
If you utilizing JMS transport, it will give loosely coupling in time, that means, the point in time when an action is requested does not have to be the same as when the server process the action. If you are planning to utilize the service under heavy load, JMS transport is preferred as it is non-blocking, and use of hardware resources is more predictable.</p>


问:
Generating DXL documentation using Doxygen : if is shown as a function
I am trying to generate some DXL documentation usings Doxygen , but the results are often not correct , DXL is used as a scripting language and that has a C/C++ like syntax with some changes , like for example i can ignor using the Semicolons , What should i do to correct this problem ?
which creates some problems while generating the documentation, here is an example of my dxl code database :

```<code>string replace (string sSource, string sSearch, string sReplace) {
int iLen = length sSource
if (iLen == 0) return ""

int iLenSearch = length(sSearch)

if (iLenSearch == 0) {

    return ""
}
char firstChar = sSearch[0]

Buffer s = create()
int pos = 0, d1,d2;
int i

while (pos < iLen) {
    char ch = sSource[pos];
    bool found = true

    if (ch != firstChar) {pos ++; s+= ch; continue}
    for (i = 1; i < iLenSearch; i++) {
       if (sSource[pos+i] != sSearch[i]) { found = false; break }
    }
    if (!found) {pos++; s+= ch; continue}
    s += sReplace
    pos += iLenSearch
}

string result = stringOf s
delete s
return result   }
</code>```

as i said the main difference with C and that may cause doxygen to interpret this code incorrectly is that in DXL , we dont have to use ";" .

thanks in advance

答:
You must do three things to apply Doxygen successfully on DXL scripts:

1.) In Doxygen-GUI, 'Wizard' tab, section 'Mode' choose 'Optimize for C or PHP'

2.) The DXL code must be C-confom, i.e. each statement ends with a semicolon ';'

3.) In tab 'Expert' set language mapping for DXL and INC files in section 'Project' under 'EXTENSION_MAPPING':

      dxl=C

      inc=C

This all tells Doxygen to treat DXL scripts as C code.

Body:
I am trying to generate some DXL documentation usings Doxygen , but the results are often not correct , DXL is used as a scripting language and that has a C/C++ like syntax with some changes , like for example i can ignor using the Semicolons , What should i do to correct this problem ?
which creates some problems while generating the documentation, here is an example of my dxl code database :

string replace (string sSource, string sSearch, string sReplace) {
int iLen = length sSource
if (iLen == 0) return ""

int iLenSearch = length(sSearch)

if (iLenSearch == 0) {

    return ""
}
char firstChar = sSearch[0]

Buffer s = create()
int pos = 0, d1,d2;
int i

while (pos < iLen) {
    char ch = sSource[pos];
    bool found = true

    if (ch != firstChar) {pos ++; s+= ch; continue}
    for (i = 1; i < iLenSearch; i++) {
       if (sSource[pos+i] != sSearch[i]) { found = false; break }
    }
    if (!found) {pos++; s+= ch; continue}
    s += sReplace
    pos += iLenSearch
}

string result = stringOf s
delete s
return result   }

as i said the main difference with C and that may cause doxygen to interpret this code incorrectly is that in DXL , we dont have to use ";" .

thanks in advance


问:
Reverse M2M query in Django-template
I would like to fetch the names of the speakers in the template. I marked it with xxxx. How can I do this? Thank you so much for helping out. My files:

models.py

```<code>class City(models.Model):
    name = models.CharField(max_length=100)

class Speaker(models.Model):
    name = models.CharField(max_length=100)
    url = models.URLField(max_length=100)
    city = models.ManyToManyField(City, blank=True)
</code>```

views.py

```<code>def home(request):
    cities = City.objects.all().exclude(speaker__isnull=True)
    return render(request, "index.html", {"cities":cities})
</code>```

index.html

```<code>{% for i in cities %}
{{ i.name }},xxx{{ i.speaker.name }}xxx<br>
{% endfor %}
</code>```

答:
You can access the speakers for each city as speaker_set:

```<code>{% for cit in cities %}
   {{ cit.name }}
   {% for spkr in cit.speaker_set.all %}
      {{ spkr.name }}
   <br>
   {% endfor %}
{% endfor %}
</code>```

Title: Reverse M2M query in Django-template

Body:
I would like to fetch the names of the speakers in the template. I marked it with xxxx. How can I do this? Thank you so much for helping out. My files:

models.py

class City(models.Model):
    name = models.CharField(max_length=100)

class Speaker(models.Model):
    name = models.CharField(max_length=100)
    url = models.URLField(max_length=100)
    city = models.ManyToManyField(City, blank=True)

views.py

def home(request):
    cities = City.objects.all().exclude(speaker__isnull=True)
    return render(request, "index.html", {"cities":cities})

index.html

{% for i in cities %}
{{ i.name }},xxx{{ i.speaker.name }}xxx

{% endfor %}

Body:
You can access the speakers for each city as speaker_set:

{% for cit in cities %}
   {{ cit.name }}
   {% for spkr in cit.speaker_set.all %}
      {{ spkr.name }}
   <br>
   {% endfor %}
{% endfor %}


问:
Accessing totalResults property from google contacts returned xml
I'm trying to access 'totalResults' from following xml which was returned by google(contacts)

 <generator version="1.0" uri="http://www.google.com/m8/feeds">Contacts</generator>
 <openSearch:totalResults>29</openSearch:totalResults>
 <openSearch:startIndex>1</openSearch:startIndex>
 <openSearch:itemsPerPage>25</openSearch:itemsPerPage>```

答:
Try this PHP tutorial from the PHP docs on how to access attributes in XML:

```<code><?php
$string = <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?>
</code>```

The above example will output:

```<code>name="one"
game="lonely"
</code>```

Check this SO post for additional reference.

Body:
Try this PHP tutorial from the PHP docs on how to access attributes in XML:

<?php
$string = <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?>

The above example will output:

name="one"
game="lonely"

Check this SO post for additional reference.


问:
function returning a string of zeros in c
i trying to create a function that return an array of zeros us a char array
and print this array in a file text but when i return a string an addition char was returned

this the text file string the program wrote

this my fuction :

```<code> char *zeros_maker (int kj,int kj1)
{
     char *zeros;
    zeros = (char *) malloc(sizeof(char)*(kj-kj1));
    int i;
    for(i =0;i<kj-kj1;i++)
        zeros[i]='0';
    printf("%s\n",zeros);
    return zeros;
}
</code>```

the instruction i used when i printed in the file

```<code>fprintf(pFile,"%c%s%c &",34,zeros_maker(added_zeros,0),34);
</code>```

Thanks in advance

答:
Read about how string in C are meant to be terminated.

Each string terminates with the null char '\0' (the NULL symbol ASCII value 0, not to be confused with the char '0' that has ASCII value 48). It identifies the end of the string.

```<code>zeros[kj-kj1]='\0';
</code>```

Plus check always if you are accessing an element out of bound. In this case it happens if kj1> kj

Body:
i trying to create a function that return an array of zeros us a char array
and print this array in a file text but when i return a string an addition char was returned

this the text file string the program wrote

this my fuction :

 char *zeros_maker (int kj,int kj1)
{
     char *zeros;
    zeros = (char *) malloc(sizeof(char)*(kj-kj1));
    int i;
    for(i =0;i<kj-kj1;i++)
        zeros[i]='0';
    printf("%s\n",zeros);
    return zeros;
}

the instruction i used when i printed in the file

fprintf(pFile,"%c%s%c &",34,zeros_maker(added_zeros,0),34);

Thanks in advance

Body:
Read about how string in C are meant to be terminated.

Each string terminates with the null char '\0' (the NULL symbol ASCII value 0, not to be confused with the char '0' that has ASCII value 48). It identifies the end of the string.

zeros[kj-kj1]='\0';

Plus check always if you are accessing an element out of bound. In this case it happens if kj1> kj


问:
ReferenceError: Can't find variable: require node.js
I have tried the related solutions for this problem (eg. add the dependencies through 'package.json' and run npm install) but unfortunately they didn't solve it. Problem is when I run the code from the accepted answer from the following discussion:
Node.js, Ajax sending and receiving Json

everything works fine. the Ajax-call works and I get the result with the data. But in the console I get the error.

```<code>'ReferenceError: Can't find variable: require' (Globale code — requesthandle.js:2ReferenceError: Can't find variable: require)
</code>```

Any ideas which could be the problem here? Thank you!

This is the code I am using:

requesthandle.js (server side, by executing node requesthandle.js) ==>

http://i67.tinypic.com/24zbyma.png

and

list.html (by visiting mydomain/list.html)

http://i65.tinypic.com/mwp3md.png

答: Found the solution.. overlooked the fact I included the requesthandle.js in my list.html / client-side code. Thank you for your help Arpit Solanki! Seems your first remark included the solution: I was using it frontend by mistake.. </p>

Body:
I have tried the related solutions for this problem (eg. add the dependencies through 'package.json' and run npm install) but unfortunately they didn't solve it. Problem is when I run the code from the accepted answer from the following discussion:
Node.js, Ajax sending and receiving Json

everything works fine. the Ajax-call works and I get the result with the data. But in the console I get the error.

'ReferenceError: Can't find variable: require' (Globale code — requesthandle.js:2ReferenceError: Can't find variable: require)

Any ideas which could be the problem here? Thank you!

This is the code I am using:

requesthandle.js (server side, by executing node requesthandle.js) ==>

http://i67.tinypic.com/24zbyma.png

and

list.html (by visiting mydomain/list.html)

http://i65.tinypic.com/mwp3md.png


问:
Nothing Happens after Clicking the Submit Button
With the generated code, one of my entities can not be saved. On the 8080 port, the form remains the same and nothing shows up on the console after I click the submit button. On the 9000 port, however, a log message shows fetching for related entities from the database after I click the button. There isn't an error message on any console, including the browser's console. In the dialog.html file, the first line is as follows:

```<code>    <form name="editForm" role="form" novalidate ng-submit="vm.save()"
 show-validation>
</code>```

so I insert the log in the first line of the Javascript function of the dialog.controller.js:

```<code>function save () {
    console.log("Saving ...");
...
</code>```

How should I resolve it?

The structure of the controller is the followings:

```<code>(function() {
'use strict';

angular
    .module('myApp')
    .controller('MyDialogController', MyDialogController);

SkuSDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'DataUtils', 'entity', 'MyEntity', 'MyRelatedEntity'];

function SkuSDialogController ($timeout, $scope, $stateParams, $uibModalInstance, DataUtils, entity, MyEntity, MyRelatedEntity) {
    var vm = this;

    ...
    vm.clear = clear;
    vm.datePickerOpenStatus = {};
    vm.openCalendar = openCalendar;
    vm.byteSize = DataUtils.byteSize;
    vm.openFile = DataUtils.openFile;
    vm.save = save;
    ...

    $timeout(function (){
        angular.element('.form-group:eq(1)>input').focus();
    });

    function clear () {
        $uibModalInstance.dismiss('cancel');
    }

    function save () {
    console.log("Saving ...");
        vm.isSaving = true;
        if (vm.myEntity.id !== null) {
            MyEntity.update(vm.myEntity, onSaveSuccess, onSaveError);
        } else {
            MyEntity.save(vm.myEntity, onSaveSuccess, onSaveError);
        }
    }

    function onSaveSuccess (result) {
        $scope.$emit('myApp:myEntityUpdate', result);
        $uibModalInstance.close(result);
        vm.isSaving = false;
    }

    function onSaveError () {
        vm.isSaving = false;
    }

    vm.datePickerOpenStatus.activeStartDate = false;
    vm.datePickerOpenStatus.activeEndDate = false;

    function openCalendar (date) {
        vm.datePickerOpenStatus[date] = true;
    }
  }
})();
</code>```

答: You might be missing submit button? <button type="submit">Submit</button> or <input type="submit" value="Submit">

Body:
With the generated code, one of my entities can not be saved. On the 8080 port, the form remains the same and nothing shows up on the console after I click the submit button. On the 9000 port, however, a log message shows fetching for related entities from the database after I click the button. There isn't an error message on any console, including the browser's console. In the dialog.html file, the first line is as follows:

    <form name="editForm" role="form" novalidate ng-submit="vm.save()"
 show-validation>

so I insert the log in the first line of the Javascript function of the dialog.controller.js:

function save () {
    console.log("Saving ...");
...

How should I resolve it?

The structure of the controller is the followings:

(function() {
'use strict';

angular
    .module('myApp')
    .controller('MyDialogController', MyDialogController);

SkuSDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'DataUtils', 'entity', 'MyEntity', 'MyRelatedEntity'];

function SkuSDialogController ($timeout, $scope, $stateParams, $uibModalInstance, DataUtils, entity, MyEntity, MyRelatedEntity) {
    var vm = this;

    ...
    vm.clear = clear;
    vm.datePickerOpenStatus = {};
    vm.openCalendar = openCalendar;
    vm.byteSize = DataUtils.byteSize;
    vm.openFile = DataUtils.openFile;
    vm.save = save;
    ...

    $timeout(function (){
        angular.element('.form-group:eq(1)>input').focus();
    });

    function clear () {
        $uibModalInstance.dismiss('cancel');
    }

    function save () {
    console.log("Saving ...");
        vm.isSaving = true;
        if (vm.myEntity.id !== null) {
            MyEntity.update(vm.myEntity, onSaveSuccess, onSaveError);
        } else {
            MyEntity.save(vm.myEntity, onSaveSuccess, onSaveError);
        }
    }

    function onSaveSuccess (result) {
        $scope.$emit('myApp:myEntityUpdate', result);
        $uibModalInstance.close(result);
        vm.isSaving = false;
    }

    function onSaveError () {
        vm.isSaving = false;
    }

    vm.datePickerOpenStatus.activeStartDate = false;
    vm.datePickerOpenStatus.activeEndDate = false;

    function openCalendar (date) {
        vm.datePickerOpenStatus[date] = true;
    }
  }
})();


问:
Remove all elements within a ng-repeat in Angular
I'm working with Angular and part of my page utilizes ng-repeat to display some bug tracker tickets. As part of the site, I also want to provide the ability to search tickets. I'm able to get that part working as I want, and if I'm just appending new tickets they show up fine.

However I would like to be able to, if a user searches, delete all of the  currently visible ticket divs and replace them with the search results.

My initial thinking, since I have the ng-repeat set as item in tickets track by item.id, was to just set $scope.tickets equal to the new data. However, this didn't cause Angular to update the DOM.

So, I tried setting $scope.tickets equal to an empty array and then setting it equal to the new data:

```<code>$scope.$apply(function() {
    $scope.tickets = [];

    $scope.tickets = data;
});
</code>```

Still no update to the DOM, even though console.log($scope.tickets) shows the correct objects.

I'm aware of the method of

```<code>$scope.$apply(function() {
    array.splice(index, 1);
});
</code>```

to remove individual elements, but I'm not sure how I would apply that removing all of the elements.

I'll try and get a Plunkr or JSBin added to the Q soon.

What would be the proper way for me to make Angular replace all of the current elements with the new elements created from the data?

答:
Did you test $watch?

```<code>$scope.$watch('tickets', function() {
   // update data HERE
});
</code>```

Body:
I'm working with Angular and part of my page utilizes ng-repeat to display some bug tracker tickets. As part of the site, I also want to provide the ability to search tickets. I'm able to get that part working as I want, and if I'm just appending new tickets they show up fine.

However I would like to be able to, if a user searches, delete all of the  currently visible ticket divs and replace them with the search results.

My initial thinking, since I have the ng-repeat set as item in tickets track by item.id, was to just set $scope.tickets equal to the new data. However, this didn't cause Angular to update the DOM.

So, I tried setting $scope.tickets equal to an empty array and then setting it equal to the new data:

$scope.$apply(function() {
    $scope.tickets = [];

    $scope.tickets = data;
});

Still no update to the DOM, even though console.log($scope.tickets) shows the correct objects.

I'm aware of the method of

$scope.$apply(function() {
    array.splice(index, 1);
});

to remove individual elements, but I'm not sure how I would apply that removing all of the elements.

I'll try and get a Plunkr or JSBin added to the Q soon.

What would be the proper way for me to make Angular replace all of the current elements with the new elements created from the data?

Body:
Did you test $watch?

$scope.$watch('tickets', function() {
   // update data HERE
});


问:
Visual Studio 2010 says Build failed with no errors after I change a source file
I have a Visual Studio 2010 solution with a few projects. I can successfully build with Build -> Build Solution or Build -> Build MyCompany.MyProduct.MyProject. After building I press CTRL+F5 and successfully run the start up project. This works as expected.

After I change a source file, save it and then again build (with either Build -> Build Solution or Build -> Build MyCompany.MyProduct.MyProject) it builds successfully. I am still able to press CTRL+F5 and run the startup project. This again works as expected.

The problem is in the following scenario:
After I change a source file, save it and directly press CTRL+F5 then Visual Studio 2010 says BUILD FAILED and there are no errors. And it doesn't start my startup project (of course).

Am I missing something?

答: Another thing to check is that if any of your source files are open it will not be able to build. I had to restart my computer.</p>


问:
Cannot read property 'get' of undefined in Node.js
I know some JS but I'm new to Node.js. I know this is a very common error but I couldn't find the source of the error since I lack debugging skills in Node.js.
Here is my app.js :

```<code>var index = require('./routes/index');
var users = require('./routes/userlist');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/userlist', users);
</code>```

Here is my userlist.js :

```<code>var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;
</code>```

Here is my index.js:

```<code>var express = require('express');
var router = express.Router();

router.get('/userlist', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    console.log(collection);
    collection.find({},{},function(e,docs){
        res.render('userlist', {
            "userlist" : docs
        });
    });
});
</code>```

Here is userlist view :

```<code>extends layout

block content
    h1.
        User List
    ul
        each user, i in userlist
            li
                a(href="mailto:#{user.email}")= user.username
</code>```

I appreciate if you tell me where the problem is or tell me how I can detect the problem. Thanks in advance.

EDIT:

In console I get this :

```<code>GET /userlist 500 296.280 ms - 1501
</code>```

EDIT 2:
It gives me the error at this line :

```<code>var collection = db.get('usercollection');
</code>```

EDIT 3:
In index.js, I see that

```<code>router.get('/userlist', function(req, res) {
    var db = req.db;
</code>```

req.db is undefined. Why is it undefined? Do you have any idea?

答:
Change your code accordingly:

userlist.js

```<code>var express = require('express').Router();
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;
</code>```

index.js

```<code>var express = require('express').Router();
var router = express.Router();

router.get('/userlist', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    console.log(collection);
    collection.find({},{},function(e,docs){
        res.render('userlist', {
            "userlist" : docs
        });
    });
});
</code>```

You should use var router = require('express').Router(); instead of var router = require('express');

Body:
I know some JS but I'm new to Node.js. I know this is a very common error but I couldn't find the source of the error since I lack debugging skills in Node.js.
Here is my app.js :

var index = require('./routes/index');
var users = require('./routes/userlist');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/userlist', users);

Here is my userlist.js :

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

Here is my index.js:

var express = require('express');
var router = express.Router();

router.get('/userlist', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    console.log(collection);
    collection.find({},{},function(e,docs){
        res.render('userlist', {
            "userlist" : docs
        });
    });
});

Here is userlist view :

extends layout

block content
    h1.
        User List
    ul
        each user, i in userlist
            li
                a(href="mailto:#{user.email}")= user.username

I appreciate if you tell me where the problem is or tell me how I can detect the problem. Thanks in advance.

EDIT:

In console I get this :

GET /userlist 500 296.280 ms - 1501

EDIT 2:
It gives me the error at this line :

var collection = db.get('usercollection');

EDIT 3:
In index.js, I see that

router.get('/userlist', function(req, res) {
    var db = req.db;

req.db is undefined. Why is it undefined? Do you have any idea?

Body:
Change your code accordingly:

userlist.js

var express = require('express').Router();
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

index.js

var express = require('express').Router();
var router = express.Router();

router.get('/userlist', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    console.log(collection);
    collection.find({},{},function(e,docs){
        res.render('userlist', {
            "userlist" : docs
        });
    });
});

You should use var router = require('express').Router(); instead of var router = require('express');


问:
Table Sorting in HTML in reference to Date and Time
I have a table that i wish to put in order (referencing the date and time). I currently have

```<code><HTML>
<HEAD>
    <TITLE>Contents of /media/Audio/Backup Recordings/</TITLE>
    <style type="text/css">filelist { visibility: hidden; }</style>
</HEAD>
<BODY>
    <B>Contents of /media/Audio/Backup Recordings/</B>
    <P />
    <TABLE>
        <TR>
            <TD>Type</TD>
            <TD>Name</TD>
            <TD>Size</TD>
            <TD>Time</TD>
            <TD>Hash</TD>
        </TR>
        <TR>
            <TD>File</TD>
            <TD>
                <A HREF="XXXXXXXXX">Backup_Test_2017-03-14_11-22-27.mp3</A>
            </TD>
            <TD>646272</TD>
            <TD>Tue Mar 14 11:23:07 2017</TD>
            <TD>---</TD>
        </TR>
        <TR>
            <TD>File</TD>
            <TD>
                <A HREF="XXXXXXXXX">Backup_Test_2_2017-03-13_09-15-00.mp3</A>
            </TD>
            <TD>14402304</TD>
            <TD>Tue Mar 13 09:30:00 2017</TD>
            <TD>---</TD>
        </TR>
    </TABLE>
    <P />
    Up to
    <A HREF="YYYYYYYYY">parent directory</A>
    <P />
    <filelist bytes_available="2485193728">
        <directory read_only="true">
            <name>..</name>
            <media_path>Audio</media_path>
        </directory>
        <file hidden="false">
            <name>Backup_Test_2017-03-14_11-22-27.mp3</name>
            <size>646272</size>
            <time>Tue Mar 14 11:23:07 2017</time>
            <hash></hash>
            <media_path>Audio/Backup Recordings/Backup_Test_2017-03-14_11-22-27.mp3</media_path>
        </file>
        <file hidden="false">
            <name>Backup_Test_2_2017-03-13_09-15-00.mp3</name>
            <size>14402304</size>
            <time>Tue Mar 13 09:30:00 2017</time>
            <hash></hash>
            <media_path>Audio/Backup Recordings/Backup_Test_2_2017-03-13_09-15-00.mp3</media_path>
        </file>
    </filelist>
</BODY>
</code>```

Is there a way to order the table so that the March 13 entry (Backup test) appears before March 14 (Backup Test 2)? I wish to add hundreds of recordings and automatically sort depending on date and time.

答:
You can find this

Requirements: jquery

```<code>var rows = $('TABLE TR:nth-child(n+2)')
rows.sort(function(a,b){
var a =new Date($(a).find("td:nth-child(4)").text())
var b =new Date($(b).find("td:nth-child(4)").text())

if (a>b)
{
    return 1
}else
{
    return -1
}

})
$('TABLE TR:nth-child(n+2)').remove()
$('TABLE').append(rows)
</code>```

As I found that your first row is header. so the retrieve, sorting and appending are after the first row.

Body:
I have a table that i wish to put in order (referencing the date and time). I currently have

    <TITLE>Contents of /media/Audio/Backup Recordings/</TITLE>

    Contents of /media/Audio/Backup Recordings/

            Type
            Name
            Size
            Time
            Hash

            File

                Backup_Test_2017-03-14_11-22-27.mp3

            646272
            Tue Mar 14 11:23:07 2017
            ---

            File

                Backup_Test_2_2017-03-13_09-15-00.mp3

            14402304
            Tue Mar 13 09:30:00 2017
            ---

    Up to
    parent directory

    <filelist bytes_available="2485193728">
        <directory read_only="true">
            <name>..</name>
            <media_path>Audio</media_path>
        </directory>
        <file hidden="false">
            <name>Backup_Test_2017-03-14_11-22-27.mp3</name>
            <size>646272</size>
            <time>Tue Mar 14 11:23:07 2017</time>
            <hash></hash>
            <media_path>Audio/Backup Recordings/Backup_Test_2017-03-14_11-22-27.mp3</media_path>
        </file>
        <file hidden="false">
            <name>Backup_Test_2_2017-03-13_09-15-00.mp3</name>
            <size>14402304</size>
            <time>Tue Mar 13 09:30:00 2017</time>
            <hash></hash>
            <media_path>Audio/Backup Recordings/Backup_Test_2_2017-03-13_09-15-00.mp3</media_path>
        </file>
    </filelist>

Is there a way to order the table so that the March 13 entry (Backup test) appears before March 14 (Backup Test 2)? I wish to add hundreds of recordings and automatically sort depending on date and time.

Body:
You can find this

Requirements: jquery

var rows = $('TABLE TR:nth-child(n+2)')
rows.sort(function(a,b){
var a =new Date($(a).find("td:nth-child(4)").text())
var b =new Date($(b).find("td:nth-child(4)").text())

if (a>b)
{
    return 1
}else
{
    return -1
}

})
$('TABLE TR:nth-child(n+2)').remove()
$('TABLE').append(rows)

As I found that your first row is header. so the retrieve, sorting and appending are after the first row.


问:
How do I animate bottom AND opacity attribute in GSAP and ScrollMagic?
With the following code I am able to stagger animate the position and fade the text in. But what I'd like to accomplish is to move, fade in, and then fade all copy back to 0 by end of scroll. So moving is working fine. I  just want the same
 tags to fade in then back out by end of scroll.

```<code>// init controller to hold all commands/animations
const controller = new ScrollMagic.Controller({ addIndicators: true });

const tween1 = TweenMax
  .staggerTo('#parallax p', 1, {
    bottom: $('#parallax').height(),
    opacity: 1,
  }, 0.06);

// All commands/animations live in a scene
new ScrollMagic.Scene({
  // Element to watch
  triggerElement: '#parallax',
  // Point at which animation starts, default is center of screen
  triggerHook: 0, // 1 onEnter, .5 onCenter (Defualt), 0 onLeave
})
.setPin('#parallax')
.setTween(tween1)
.duration('100%') // Percentage of full screen or hard-wired number of pixels
.addIndicators({ name: 'FADES' }) // Indicators marked on screen
.addTo(controller); // Add this scene to controller
</code>```

Side question: If the animation is keyed to scroll through ScrollMagic, what is the 1 for in the following line: .staggerTo('#parallax p', 1, {?

Edit: More appropriate CodePen added

答:
Something more like this? https://codepen.io/motionimaging/pen/155bf1892710fb95dcc81ddb7201adb0/</p>

```<code>// init controller to hold all commands/animations
const controller = new ScrollMagic.Controller({ addIndicators: true });

var timeline = new TimelineMax();
var tween1 = TweenMax.staggerFromTo("#two p", 1, {bottom: 0},{bottom: $('#two').height()}, 0.1);

var tween2a = TweenMax.staggerTo("#two p", 0.5,{ opacity: 1 }, 0.1);

var tween2b = TweenMax.staggerTo("#two p", 0.35,{ opacity: 0 }, 0.1);

timeline.add(tween1, 0)
    .add(tween2a, 0)
    .add(tween2b, 0.5);

new ScrollMagic.Scene({
   triggerElement: "#two",
  triggerHook: 0,
})
.setTween(timeline)
.setPin("#two")
.duration("200%")
.addIndicators({ name: "FADES" })
.addTo(controller);
</code>```

Body:
With the following code I am able to stagger animate the position and fade the text in. But what I'd like to accomplish is to move, fade in, and then fade all copy back to 0 by end of scroll. So moving is working fine. I  just want the same
 tags to fade in then back out by end of scroll.

// init controller to hold all commands/animations
const controller = new ScrollMagic.Controller({ addIndicators: true });

const tween1 = TweenMax
  .staggerTo('#parallax p', 1, {
    bottom: $('#parallax').height(),
    opacity: 1,
  }, 0.06);

// All commands/animations live in a scene
new ScrollMagic.Scene({
  // Element to watch
  triggerElement: '#parallax',
  // Point at which animation starts, default is center of screen
  triggerHook: 0, // 1 onEnter, .5 onCenter (Defualt), 0 onLeave
})
.setPin('#parallax')
.setTween(tween1)
.duration('100%') // Percentage of full screen or hard-wired number of pixels
.addIndicators({ name: 'FADES' }) // Indicators marked on screen
.addTo(controller); // Add this scene to controller

Side question: If the animation is keyed to scroll through ScrollMagic, what is the 1 for in the following line: .staggerTo('#parallax p', 1, {?

Edit: More appropriate CodePen added

Body:
Something more like this? https://codepen.io/motionimaging/pen/155bf1892710fb95dcc81ddb7201adb0/

// init controller to hold all commands/animations
const controller = new ScrollMagic.Controller({ addIndicators: true });

var timeline = new TimelineMax();
var tween1 = TweenMax.staggerFromTo("#two p", 1, {bottom: 0},{bottom: $('#two').height()}, 0.1);

var tween2a = TweenMax.staggerTo("#two p", 0.5,{ opacity: 1 }, 0.1);

var tween2b = TweenMax.staggerTo("#two p", 0.35,{ opacity: 0 }, 0.1);

timeline.add(tween1, 0)
    .add(tween2a, 0)
    .add(tween2b, 0.5);

new ScrollMagic.Scene({
   triggerElement: "#two",
  triggerHook: 0,
})
.setTween(timeline)
.setPin("#two")
.duration("200%")
.addIndicators({ name: "FADES" })
.addTo(controller);


问:
RxJava wait for the response to be retrieved before moving on
```<code>        getRemarks(licensePlate)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe(response -> {
                Store.remarks(response);
            }, throwable -> {
                Timber.e("Error", throwable);
            });

    public static Observable<List<Remark>> getRemarks(String number) {
        return getApiService().getRemarks(number);
    }
</code>```

<p>So, for now this is my code but I need to wait until this method get the response before moving on with the code. As I saw I need .toBlocking (but it blocked my code indefinitely) and I read somewhere that I need .forEach method but don't know how to use it. </p>

答:
if getRemarks() is using retrofit then you can do something like following which will execute synchronously (you will need to be running in non-UI thread if you do this to avoid NetworkOnMainThreadException)

```<code>getApiService().getRemarks(number).execute()
</code>```

Body:
        getRemarks(licensePlate)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe(response -> {
                Store.remarks(response);
            }, throwable -> {
                Timber.e("Error", throwable);
            });

    public static Observable<List<Remark>> getRemarks(String number) {
        return getApiService().getRemarks(number);
    }

So, for now this is my code but I need to wait until this method get the response before moving on with the code. As I saw I need .toBlocking (but it blocked my code indefinitely) and I read somewhere that I need .forEach method but don't know how to use it.

Body:
if getRemarks() is using retrofit then you can do something like following which will execute synchronously (you will need to be running in non-UI thread if you do this to avoid NetworkOnMainThreadException)

getApiService().getRemarks(number).execute()