问:
onclick in php echo with error invalid unexpected token
I'm trying to add the onclick funtion when user checked the check box, and then the total price will be shown.

All the information including price is retrieve from database (no problem with retrieving data, the data display correctly).

Here is how's the code looks like.

//calculate price
function total() {
  var cal = document.getElementsByName('event');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
}
var checks = document.getElementsByName(event);
for (var i = 0; i < checks.length; i++) checks[i].onclick = total;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="bookingForm" action="javascript:alert('form submitted');" method="get">
  <section id="selectEvent">
   <h2>Select Events</h2>
    <div class ="item">
    <span class="chosen">
   event1 <input type= checkbox name= event data-price = "1" value=eventId1/>
    event2 <input type= checkbox name= event data-price = "2" value=eventId2/>
   </span>
   </div>
  </section>

  <section id="checkCost">
   <h2>Total cost</h2>
   Total <input type="text" name="total"  size="10" readonly />
  </section>

 </form></code>```

here is the java script code,just focus on funtion total()

```<code>window.addEventListener('load', initialise);

    function initialise () {
        'use strict';
        //calculate price
        function total(){
        var cal= document.getElementsByName('event[]');
        var total = 0;
        for (var i = 0; i<cal.length; i++){
            if(cal[i].checked){
                total += parseFloat(cal[i].data-price);
            }
        }
    document.getElementByName("total").value = "$" + total.toFixed(2);
    }
</code>```

here is the link for my reference

[1]: Display total price when checkbox clicked in JS

i also tried but it doesn't work

total += parseFloat(cal[i].getAttribute("data-price")

答:
Why would you use so much '\' ? and what the asterisks '*' after total() for?
I have tried following snippet and it seems to works well.
(only changing the echo line in your php code)

```<code>echo "\t<div class='item'>
            <span class='eventTitle'>".filter_var($event['eventTitle'], FILTER_SANITIZE_SPECIAL_CHARS)."</span>
            <span class='eventStartDate'>{$event['eventStartDate']}</span>
            <span class='eventEndDate'>{$event['eventEndDate']}</span>
            <span class='catDesc'>{$event['catDesc']}</span>
            <span class='venueName'>{$event['venueName']}</span>
            <span class='eventPrice'>{$event['eventPrice']}</span>
            <span class='chosen'><input type='checkbox' name='event[]' value='{$event['eventID']}' data-price='{$event['eventPrice']}' onclick='total()*'/></span>
      </div>\n";
</code>```

Body:
I'm trying to add the onclick funtion when user checked the check box, and then the total price will be shown.

All the information including price is retrieve from database (no problem with retrieving data, the data display correctly).

Here is how's the code looks like.

//calculate price
function total() {
  var cal = document.getElementsByName('event');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
}
var checks = document.getElementsByName(event);
for (var i = 0; i < checks.length; i++) checks[i].onclick = total;

<form id="bookingForm" action="javascript:alert('form submitted');" method="get">

Select Events

   event1 <input type= checkbox name= event data-price = "1" value=eventId1/>
    event2 <input type= checkbox name= event data-price = "2" value=eventId2/>

Total cost

   Total <input type="text" name="total"  size="10" readonly />

 </form>

here is the java script code,just focus on funtion total()

window.addEventListener('load', initialise);

    function initialise () {
        'use strict';
        //calculate price
        function total(){
        var cal= document.getElementsByName('event[]');
        var total = 0;
        for (var i = 0; i<cal.length; i++){
            if(cal[i].checked){
                total += parseFloat(cal[i].data-price);
            }
        }
    document.getElementByName("total").value = "$" + total.toFixed(2);
    }

here is the link for my reference

[1]: Display total price when checkbox clicked in JS

i also tried but it doesn't work

total += parseFloat(cal[i].getAttribute("data-price")

Body:
Why would you use so much '\' ? and what the asterisks '*' after total() for?
I have tried following snippet and it seems to works well.
(only changing the echo line in your php code)

echo "\t<div class='item'>
            <span class='eventTitle'>".filter_var($event['eventTitle'], FILTER_SANITIZE_SPECIAL_CHARS)."</span>
            <span class='eventStartDate'>{$event['eventStartDate']}</span>
            <span class='eventEndDate'>{$event['eventEndDate']}</span>
            <span class='catDesc'>{$event['catDesc']}</span>
            <span class='venueName'>{$event['venueName']}</span>
            <span class='eventPrice'>{$event['eventPrice']}</span>
            <span class='chosen'><input type='checkbox' name='event[]' value='{$event['eventID']}' data-price='{$event['eventPrice']}' onclick='total()*'/></span>
      </div>\n";


来源: stackexchange

问:
Android Studio - ADB or Virtual Device without admin rights
Due to my business trips, I would use my professional laptop for improving my skills in Android development. I don't have administrator rights, so I installed Android Studio. Sadly, I have 2 kinds of errors :

Please ensure Intel HAXM is properly installed and usable. Intel HAXM is available at
...\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager but I'm
not allowed to launch intelhaxm-android.exe due to non-admin rights.

My Android device is not recognized by Android Studio but well
recognized by my laptop. It seems ADB.exe couldn't be installed
without admin rights.

How can I fix these issues, at least one of them ?

Thanks in advance for your help !

Fred

答:
You can install ADB without administrator rights!There's a trick which I used and it bypasses need to login using administrator account.

Open notepad and paste the following text in that file:

```<code>cmd /min /C "set __COMPAT_LAYER=RUNASINVOKER && start "" "%1""
</code>```

Save as a batch file.

Drag the executable you want to launch without admin and drop it onto the batch file.

Installation will start and won't ask for logging in as administrator!

P.S: I have tested this on Windows 10 (Build 10240) by installing ADB drivers and it ridiculously works! However note that, if your setup produces more exes (internally) then this may not work.

ContentLicense: CC BY-SA 3.0

Body:
You can install ADB without administrator rights!There's a trick which I used and it bypasses need to login using administrator account.

Open notepad and paste the following text in that file:

cmd /min /C "set __COMPAT_LAYER=RUNASINVOKER && start "" "%1""

Save as a batch file.

Drag the executable you want to launch without admin and drop it onto the batch file.

Installation will start and won't ask for logging in as administrator!

P.S: I have tested this on Windows 10 (Build 10240) by installing ADB drivers and it ridiculously works! However note that, if your setup produces more exes (internally) then this may not work.


问:
Test the error code of a custom exception with JUnit 4
I would like to test the return code of an exception. Here is my production code:

```<code>class A {
  try {
    something...
  }
  catch (Exception e)
  {
    throw new MyExceptionClass(INTERNAL_ERROR_CODE, e);
  }
}
</code>```

And the corresponding exception:

```<code>class MyExceptionClass extends ... {
  private errorCode;

  public MyExceptionClass(int errorCode){
    this.errorCode = errorCode;
  }

  public getErrorCode(){
    return this.errorCode;
  }
}
</code>```

My unit test:

```<code>public class AUnitTests{
  @Rule
  public ExpectedException thrown= ExpectedException.none();

  @Test (expected = MyExceptionClass.class,
  public void whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode() throws Exception {
      thrown.expect(MyExceptionClass.class);
      ??? expected return code INTERNAL_ERROR_CODE ???

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

答:
You can check for it using hamcres matchers as long as thrown.expect is overload to receive Matcher

```<code>thrown.expect(CombinableMatcher.both(
           CoreMatchers.is(CoreMatchers.instanceOf(MyExceptionClass.class)))
           .and(Matchers.hasProperty("errorCode", CoreMatchers.is(123))));
</code>```

Note that you will need to add hamcrest matcher to your dependencies. Core matched that are included in JUnit is not enough.

Or if you don't want to use CombinableMatcher:

```<code>thrown.expect(CoreMatchers.instanceOf(MyExceptionClass.class));
thrown.expect(Matchers.hasProperty("errorCode", CoreMatchers.is(123));
</code>```

Also, you don't need (expected = MyExceptionClass.class) declaration for @Test annotation

Body:
I would like to test the return code of an exception. Here is my production code:

class A {
  try {
    something...
  }
  catch (Exception e)
  {
    throw new MyExceptionClass(INTERNAL_ERROR_CODE, e);
  }
}

And the corresponding exception:

class MyExceptionClass extends ... {
  private errorCode;

  public MyExceptionClass(int errorCode){
    this.errorCode = errorCode;
  }

  public getErrorCode(){
    return this.errorCode;
  }
}

My unit test:

public class AUnitTests{
  @Rule
  public ExpectedException thrown= ExpectedException.none();

  @Test (expected = MyExceptionClass.class,
  public void whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode() throws Exception {
      thrown.expect(MyExceptionClass.class);
      ??? expected return code INTERNAL_ERROR_CODE ???

      something();
  }
}

Body:
You can check for it using hamcres matchers as long as thrown.expect is overload to receive Matcher

thrown.expect(CombinableMatcher.both(
           CoreMatchers.is(CoreMatchers.instanceOf(MyExceptionClass.class)))
           .and(Matchers.hasProperty("errorCode", CoreMatchers.is(123))));

Note that you will need to add hamcrest matcher to your dependencies. Core matched that are included in JUnit is not enough.

Or if you don't want to use CombinableMatcher:

thrown.expect(CoreMatchers.instanceOf(MyExceptionClass.class));
thrown.expect(Matchers.hasProperty("errorCode", CoreMatchers.is(123));

Also, you don't need (expected = MyExceptionClass.class) declaration for @Test annotation


问:
Determining bitmap size to hold text string
What I am trying to do is use the DrawString() method to draw a string to a bitmap. To do this, I need to create a bitmap and get a Graphics object from the bitmap, then call DrawString() on that Graphics object.

The problem is, how do I know, in advance, when I create my initial bitmap, how many pixels wide and long to make my bitmap?

I know this has something to do with MeasureString(), but in order to use MeasureString(), I need to get the Graphics object from the bitmap. I can't get that till I create the bitmap, which I can't do till I know the size. It seems like a circular paradox!

Someone please help me out on this?

答:
You can create a small static Bitmap to measure on

```<code>private static Bitmap measureBmp = new Bitmap(1, 1);
</code>```

Then you measure as usual

```<code>using (var measureGraphics = Graphics.FromImage(measureBmp))
{
    var stringSize = measureGraphics.MeasureString("measureString", this.Font);
}
</code>```

The size of the image does not affect the measurement

ContentLicense: CC BY-SA 2.5

Body:
You can create a small static Bitmap to measure on

private static Bitmap measureBmp = new Bitmap(1, 1);

Then you measure as usual

using (var measureGraphics = Graphics.FromImage(measureBmp))
{
    var stringSize = measureGraphics.MeasureString("measureString", this.Font);
}

The size of the image does not affect the measurement


问:
Ionic - Error when trying to build an android project
I'm currently learning Ionic and I am facing an issue when I try to build my project on an android platform.

When I run ionic build android I get the following error :

I tried to add a gradle.properties file with proxy configuration but that didn't solve my problem.

Removing and recreating the Android platform didn't resolve the problem either.

How can I resolve this problem?

答:
seems it is similar to this problem on ionic framework forum,

So it is recommended to  changed in the platforms\android\cordova\lib\builders\GradleBuilder.js file the distributionUrl like the following:
var distributionUrl = 'https://services.gradle.org/distributions/gradle-2.14.1-all.zip';
(which was before)
var distributionUrl = 'http\://services.gradle.org/distributions/gradle-2.14.1-all.zip';

removing one '\' and changing from http to https solved the problem for me and it starts with donwloading


问:
Not loading json data in jqgrid
Why json data not loading in jqgrid ?

I am using ASP.net with C# with JQGrid using javascript & AJAX

Here is my code below :

```<code>  public string Alarm_Main()
{
    SqlConnection con = new SqlConnection(ConnString);
    DataTable dt = new DataTable();
    con.Open();
    string query = "select * from MST_ALARM_TYPE";
    SqlDataAdapter da = new SqlDataAdapter(query, con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();
    return JsonConvert.SerializeObject(ds.Tables[0]);
}
</code>```

In file : DataService.aspx the code is given below :

```<code><script>
    $(function () {
        $("#list").jqGrid({
            url: 'DataService.asmx/Alarm_Main',
            datatype: 'json',
            mtype: 'POST',
            serializeGridData: function (postData) {
                alert(JSON.stringify(postData));
                return JSON.stringify(postData);
            },
            ajaxGridOptions: { contentType: "application/json;charset=utf-8;" },
            loadonce: true,
            jsonReader: {
                page: function (obj) { return 1; },
                total: function (obj) { return 1; },
                records: function (obj) { return obj.d.length; },
                root: function (obj) { return obj.d; },
                repeatitems: false,
                id: "0"
            },
            colNames: ['', '알람코드', '등록날짜', '알람명', '등록자', ''],
            colModel: [
                { name: 'myradio', width: 30, search: false, fixed: true, align: 'center', resizable: false, sortable: false, frozen: true, formatter: function (cellValue, option) { return '<input type="radio" name="radio_' + option.gid + '"/>'; }, frozen: true },
                { name: 'alarm_type_code', index: 'alarm_type_code', align: 'center', width: 200, frozen: true, sorttype: 'number' },
                { name: 'regist_date', index: 'regist_date', width: 200, editable: true, frozen: true, align: 'center', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "Y-m-d", newformat: "Y-m-d" } },
                { name: 'alarm_type_name', index: 'alarm_type_name', width: 200, frozen: true },
                { name: 'regist_name', index: 'regist_name', width: 200, frozen: true },
                { name: 'myac', width: 50, search: false, fixed: true, sortable: false, resizable: false, fommatter: 'action', formatoptions: {keys:true}}
            ],
            rowNum: 10,
            rowList: [5, 10, 20, 50],
            width: '100%',
            pager: '#pager',
            gridview: true,
            rownumbers: false,
            sortable: true,
            multiselect: true,
            scrollOffset: 0,
            cellEdit: true,
            sortorder: 'desc',
            caption: '그리드 제목',
            height: '100%',
            shrinkToFit: true,
            loadonce: true
        });
        jQuery("#list").jqGrid('setFrozenColumns');
        jQuery("#list").trigger('reloadGrid');
        jQuery("#list").jqGrid('navGrid', '#pager', { excel: true, add: true, edit: true, view: true, del: true, search: true, refresh: true },
            { closeAfterAdd: true, reloadAfterSubmit: false, closeOnEscape: true },
            { closeAfterAdd: true, reloadAfterSubmit: false, closeOnEscape: true },
            { reloadAfterSubmit: false, closeOnEscape: true },
            { multipleSearch: true, multipleGroup: true, showQuery: true, closeOnEscape: true, onSearch: function () { } }, { closeOnEscape: true });
        jQuery("#list").jqGrid('bindKeys', { "onEnter": function (rowid) { alert("You enter a row with id:" + rowid) } });
        jQuery("#list").jqGrid('navButtonAdd', '#pager', { caption: "Excel", onClickButton: function () { jquery("#list").jqGrid('excelExport', { url: 'D:\\' }); } });
        jQuery("#list").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "cn" });
    });
</script>
</code>```

I can't see anything on my screen.

What can be the issue ?

答:
Below is example , how to use ado.net with jqgrid, i hope this will help you.

Controller"

```<code> public ActionResult GetCustomer(int rows, string sidx, string sord, int page)
        {
            List<Customer> _customerList = new List<Customer>();

            DataTable dt = new DataTable();
            string strConString = @"Data Source=gen5win10;Initial Catalog=AsifDb;Integrated Security=True";

            using (SqlConnection con = new SqlConnection(strConString))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("Select * from Customer", con);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.SelectCommand = cmd;
                DataSet ds = new DataSet();
                da.Fill(ds);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Customer cobj = new Customer();
                    cobj.CustomerId = Convert.ToInt32(ds.Tables[0].Rows[i]["CustomerId"].ToString());
                    cobj.ID = Convert.ToInt32(ds.Tables[0].Rows[i]["CustomerId"].ToString());
                    cobj.Name = ds.Tables[0].Rows[i]["Name"].ToString();
                    cobj.Phone = ds.Tables[0].Rows[i]["Phone"].ToString();
                    cobj.Address = ds.Tables[0].Rows[i]["Address"].ToString();
                    cobj.Date = Convert.ToDateTime(ds.Tables[0].Rows[i]["Date"].ToString());

                    _customerList.Add(cobj);
                }

            }

                int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;

            var Results = _customerList.Select(
                    a => new
                    {
                        a.ID,
                        a.Name,
                        a.Phone,
                        a.Address,
                        a.Date,
                    });

            int totalRecords = Results.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            if (sord.ToUpper() == "DESC")
            {
                Results = Results.OrderByDescending(s => s.ID);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            else
            {
                Results = Results.OrderBy(s => s.ID);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = Results
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);

}
</code>```

HTML:

```<code><link href="~/Scripts/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.css" rel="stylesheet" />
<link href="~/Scripts/Guriddo_jqGrid_JS_5.2.0/css/ui.jqgrid.css" rel="stylesheet" />

<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/jquery-1.11.0.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.js"></script>

<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/jquery.jqGrid.min.js"></script>

<h2>Customers</h2>

<br>

<script type="text/javascript">
    $(document).ready(function () {

        $('#sample').jqGrid({
            datatype: 'Json',
            url: '/Customer/GetCustomer',
            type: 'POST',
            colNames: ['ID', 'Name', 'Phone', 'Address', 'Date'],
            colModel:
            [
                {key:true , name: 'ID', index: 'ID', editable: false },
                {name: 'Name', index: 'Name', editable: true ,editoptions: {maxlength: 15 },editrules:{ required: true,  }, },
                {  name: 'Phone', index: 'Phone', editable: true,  editoptions: {   maxlength: 15, },editrules: { required: true, },},
                {name: 'Address', index: 'Address', editable: true, editoptions: { maxlength: 30,}, editrules: {required: true,},},
                { name: 'Date', index: 'Date', editable: false, formatter: "date" },
            ],
            pager: jQuery('#pager'),
            jsonReader: {
                root: "rows",
                page: "page",
                total: "total",
                records: "record",
                repeatitems: false,
                Id: "0"
            },
            caption: 'Sample JqGrid Table',
            viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 30, 40],
            height: '100%',
           // multiselect: true

        }).navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true },
             {
                 // edit options
                 url: '/Customer/EditCustomer',
                 closeOnEscape: true,
                 closeAfterEdit: true,
                 recreateForm: true,
                 afterComplete: function (response)
                 {
                     if (response.responseText) {
                         alert(response.responseText);
                     }
                 }

             },

           {
               //add
               url: '/Customer/AddCustomer',
               closeOnEscape: true,
               closeAfterAdd: true,
               afterComplete: function (response) {
                   if (response.responseText) {
                       alert(response.responseText);
                   }
               }
           },
             { //Options for Delete
                 url:'/Customer/DeleteCustomer',
                 closeOnEscape: true,
                 closeAfterAdd: true,
                 afterComplete: function (response)
                 {
                     if (response.responseText) {
                         alert(response.responseText);
                     }
                 }

             }
             );

    });

</script>

<table id="sample"></table>
<div id="pager"> </div>
</code>```

Title: Not loading json data in jqgrid

Body:
Why json data not loading in jqgrid ?

I am using ASP.net with C# with JQGrid using javascript & AJAX

Here is my code below :

  public string Alarm_Main()
{
    SqlConnection con = new SqlConnection(ConnString);
    DataTable dt = new DataTable();
    con.Open();
    string query = "select * from MST_ALARM_TYPE";
    SqlDataAdapter da = new SqlDataAdapter(query, con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();
    return JsonConvert.SerializeObject(ds.Tables[0]);
}

In file : DataService.aspx the code is given below :

I can't see anything on my screen.

What can be the issue ?

Body:
Below is example , how to use ado.net with jqgrid, i hope this will help you.

Controller"

 public ActionResult GetCustomer(int rows, string sidx, string sord, int page)
        {
            List<Customer> _customerList = new List<Customer>();

            DataTable dt = new DataTable();
            string strConString = @"Data Source=gen5win10;Initial Catalog=AsifDb;Integrated Security=True";

            using (SqlConnection con = new SqlConnection(strConString))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("Select * from Customer", con);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.SelectCommand = cmd;
                DataSet ds = new DataSet();
                da.Fill(ds);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Customer cobj = new Customer();
                    cobj.CustomerId = Convert.ToInt32(ds.Tables[0].Rows[i]["CustomerId"].ToString());
                    cobj.ID = Convert.ToInt32(ds.Tables[0].Rows[i]["CustomerId"].ToString());
                    cobj.Name = ds.Tables[0].Rows[i]["Name"].ToString();
                    cobj.Phone = ds.Tables[0].Rows[i]["Phone"].ToString();
                    cobj.Address = ds.Tables[0].Rows[i]["Address"].ToString();
                    cobj.Date = Convert.ToDateTime(ds.Tables[0].Rows[i]["Date"].ToString());

                    _customerList.Add(cobj);
                }

            }

                int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;

            var Results = _customerList.Select(
                    a => new
                    {
                        a.ID,
                        a.Name,
                        a.Phone,
                        a.Address,
                        a.Date,
                    });

            int totalRecords = Results.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            if (sord.ToUpper() == "DESC")
            {
                Results = Results.OrderByDescending(s => s.ID);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            else
            {
                Results = Results.OrderBy(s => s.ID);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = Results
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);

}

HTML:

<link href="~/Scripts/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.css" rel="stylesheet" />
<link href="~/Scripts/Guriddo_jqGrid_JS_5.2.0/css/ui.jqgrid.css" rel="stylesheet" />

<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/jquery-1.11.0.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.js"></script>

<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/jquery.jqGrid.min.js"></script>

<h2>Customers</h2>

<br>

<script type="text/javascript">
    $(document).ready(function () {

        $('#sample').jqGrid({
            datatype: 'Json',
            url: '/Customer/GetCustomer',
            type: 'POST',
            colNames: ['ID', 'Name', 'Phone', 'Address', 'Date'],
            colModel:
            [
                {key:true , name: 'ID', index: 'ID', editable: false },
                {name: 'Name', index: 'Name', editable: true ,editoptions: {maxlength: 15 },editrules:{ required: true,  }, },
                {  name: 'Phone', index: 'Phone', editable: true,  editoptions: {   maxlength: 15, },editrules: { required: true, },},
                {name: 'Address', index: 'Address', editable: true, editoptions: { maxlength: 30,}, editrules: {required: true,},},
                { name: 'Date', index: 'Date', editable: false, formatter: "date" },
            ],
            pager: jQuery('#pager'),
            jsonReader: {
                root: "rows",
                page: "page",
                total: "total",
                records: "record",
                repeatitems: false,
                Id: "0"
            },
            caption: 'Sample JqGrid Table',
            viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 30, 40],
            height: '100%',
           // multiselect: true

        }).navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true },
             {
                 // edit options
                 url: '/Customer/EditCustomer',
                 closeOnEscape: true,
                 closeAfterEdit: true,
                 recreateForm: true,
                 afterComplete: function (response)
                 {
                     if (response.responseText) {
                         alert(response.responseText);
                     }
                 }

             },

           {
               //add
               url: '/Customer/AddCustomer',
               closeOnEscape: true,
               closeAfterAdd: true,
               afterComplete: function (response) {
                   if (response.responseText) {
                       alert(response.responseText);
                   }
               }
           },
             { //Options for Delete
                 url:'/Customer/DeleteCustomer',
                 closeOnEscape: true,
                 closeAfterAdd: true,
                 afterComplete: function (response)
                 {
                     if (response.responseText) {
                         alert(response.responseText);
                     }
                 }

             }
             );

    });

</script>

<table id="sample"></table>
<div id="pager"> </div>


问:
Convert algorithm from pascal to c#
I am trying to convert this thing (Shannon-Fano algorithm) from pascal to c#:

```<code>program ShennonFano;
uses crt;
const
  a :array[1..6] of char = ('a','b','c','d','e','f');
  af:array[1..6] of integer = (10, 8, 6, 5, 4, 3);

procedure SearchTree(branch:char; full_branch:string; start_pos:integer; end_pos:integer);
var
  dS:real;
  i, m, S:integer;
  c_branch:string;
begin

  if (a<>' ') then c_branch := full_branch + branch
  else c_branch := '';

  if (start_pos = end_pos) then
  begin
    WriteLn(a[start_pos], ' = ', c_branch);
    exit;
  end;

  dS := 0;
  for i:=start_pos to end_pos do dS:= dS + af[i];
  dS := dS/2;

  S := 0;
  i := start_pos;
  m := i;
  while ((S+af[i]<dS) and (i<end_pos)) do
  begin
    S := S + af[i];
    inc(i); inc(m);
  end;

  SearchTree('1', c_branch, start_pos, m);

  SearchTree('0', c_branch, m+1, end_pos);

end;

begin
  WriteLn('Press <enter> to show');
  ReadLn;
  ClrScr;

  SearchTree(' ',' ', 1, 6);
  ReadLn;
end;
</code>```

And here is my code in c#:

```<code>namespace Shannon_Fano_Alg
{
    class Program
    {
        static char[] a = { 'a', 'b', 'c', 'd', 'e', 'f' };
        static int[] af = { 10, 8, 6, 5, 4, 3 };
        static bool first = true;

        static void Search(char branch, string full_branch, int startPos, int endPos)
        {
            double dS;
            int m, i, S;
            string c_branch;
            if (first)
            {
                c_branch = "";
                first = false;
            }
            else
            {
                c_branch = full_branch + branch;
            }

            if (startPos == endPos)
            {
                Console.WriteLine(a[startPos] + " = " + c_branch);
            }

            dS = 0;
            for (i = startPos; i<endPos; i++)
            {
                dS += af[i];
            }

            dS /= 2;

            S = 0;
            i = startPos;
            m = i;
            while (S + af[i] < dS && i<endPos)
            {
                S += af[i];
                i++;
            }

            Search('1', c_branch, startPos, m);
            Search('0', c_branch, m + 1, endPos);

        }

        static void Main(string[] args)
        {
            Program.Search(' ', " ", 0, 5);
            Console.ReadKey();
        }

    }
}
</code>```

But, unfortunately my code loops endlessly, and i get smth like that:

This algorithm works fine in pascal, so i think that i have translated it incorrectly. Please help me to understand where is my mistake. Thanks in advance.

答:
In addition to BugFinder's answer.

Pascal has this :

```<code>while ((S+af[i]<dS) and (i<end_pos)) do
begin
  S := S + af[i];
  inc(i); inc(m);
end;
</code>```

Your C# has this :

```<code>while (S + af[i] < dS && i<endPos)
{
   S += af[i];
   i++;
}
</code>```

You do not increment m, so add m++; after i++;

Title: Convert algorithm from pascal to c#

Body:
I am trying to convert this thing (Shannon-Fano algorithm) from pascal to c#:

program ShennonFano;
uses crt;
const
  a :array[1..6] of char = ('a','b','c','d','e','f');
  af:array[1..6] of integer = (10, 8, 6, 5, 4, 3);

procedure SearchTree(branch:char; full_branch:string; start_pos:integer; end_pos:integer);
var
  dS:real;
  i, m, S:integer;
  c_branch:string;
begin

  if (a<>' ') then c_branch := full_branch + branch
  else c_branch := '';

  if (start_pos = end_pos) then
  begin
    WriteLn(a[start_pos], ' = ', c_branch);
    exit;
  end;

  dS := 0;
  for i:=start_pos to end_pos do dS:= dS + af[i];
  dS := dS/2;

  S := 0;
  i := start_pos;
  m := i;
  while ((S+af[i]<dS) and (i<end_pos)) do
  begin
    S := S + af[i];
    inc(i); inc(m);
  end;

  SearchTree('1', c_branch, start_pos, m);

  SearchTree('0', c_branch, m+1, end_pos);

end;

begin
  WriteLn('Press <enter> to show');
  ReadLn;
  ClrScr;

  SearchTree(' ',' ', 1, 6);
  ReadLn;
end;

And here is my code in c#:

namespace Shannon_Fano_Alg
{
    class Program
    {
        static char[] a = { 'a', 'b', 'c', 'd', 'e', 'f' };
        static int[] af = { 10, 8, 6, 5, 4, 3 };
        static bool first = true;

        static void Search(char branch, string full_branch, int startPos, int endPos)
        {
            double dS;
            int m, i, S;
            string c_branch;
            if (first)
            {
                c_branch = "";
                first = false;
            }
            else
            {
                c_branch = full_branch + branch;
            }

            if (startPos == endPos)
            {
                Console.WriteLine(a[startPos] + " = " + c_branch);
            }

            dS = 0;
            for (i = startPos; i<endPos; i++)
            {
                dS += af[i];
            }

            dS /= 2;

            S = 0;
            i = startPos;
            m = i;
            while (S + af[i] < dS && i<endPos)
            {
                S += af[i];
                i++;
            }

            Search('1', c_branch, startPos, m);
            Search('0', c_branch, m + 1, endPos);

        }

        static void Main(string[] args)
        {
            Program.Search(' ', " ", 0, 5);
            Console.ReadKey();
        }

    }
}

But, unfortunately my code loops endlessly, and i get smth like that:

This algorithm works fine in pascal, so i think that i have translated it incorrectly. Please help me to understand where is my mistake. Thanks in advance.

Body:
In addition to BugFinder's answer.

Pascal has this :

while ((S+af[i]<dS) and (i<end_pos)) do
begin
  S := S + af[i];
  inc(i); inc(m);
end;

Your C# has this :

while (S + af[i] < dS && i<endPos)
{
   S += af[i];
   i++;
}

You do not increment m, so add m++; after i++;


问:
C# 7 local function not working as expected and no errors being displayed
I have an Asp.Net MVC App running with framework version .NET 4.5 and I'm using VS2017 pro version. Users can upload attachments including but not limited to:

Excel

Word

PowerPoint

pdf

jpeg

png

So I have a private function which is as follows:

```<code>private string ImageExtension(string path)
{
  string noImagePath = HttpContext.Current.Server.MapPath("~/Content/images/Template/No-Image-Available-100x100.jpg");
  string fileExtension = System.IO.Path.GetExtension(path);
  switch (fileExtension)
  {
    case ".jpg":
    case ".jpeg":
    case ".gif":
    case ".png":
       return path;
    default:
       return noImagePath;
   }
}
</code>```

As you can see it's very simple and does not do anything fancy. As I'm only using this in one place I thought about making the use of new C# 7 feature of local function. So I've gone ahead and created my main function as follows and added ImageExtension(string path) inside it.

```<code>public void BugInfo(HttpPostedFileBase file)
{
  if(file != null && file.ContentLength > 0)
  {
    string fileName = file.FileName;
    string directoryPath = "directory path";

     //save path of
     string savePath = System.IO.Path.Combine(directoryPath, fileName);
     string testString = ImageExtension(savePath);

     string ImageExtension(string path)
     {
        string noImagePath = HttpContext.Current.Server.MapPath("~/Content/images/Template/No-Image-Available-100x100.jpg");
        string fileExtension = System.IO.Path.GetExtension(path);
        switch (fileExtension)
        {
          case ".jpg":
          case ".jpeg":
          case ".gif":
          case ".png":
             return path;
          default:
             return noImagePath;
         }
      }
    }
  //save values to db here
 }
</code>```

With the above code my project builds without any errors. As soon as I hit F5 or Ctrl + F5 I get the following error screen

If I check in the ErrorList to see if there are any errors I get none at all as you can see below.

Can someone tell me where I'm going wrong please. Do I have to change any settings or need to include any additional DLLs to make use of C# 7 features.

Looking at this answer it seems like all of the C# 7 features should work on .NET 4.5

答:
You need to update nuget package named "Microsoft.Net.Compilers" to the latest version. Most likely you have version 1.3.2 installed in your project but you need 2.0.1 to use C# 7 features. Alternatively - you can remove this package at all (together with packages that depend on it) - then it will also work, because it will use your installed compiler, but I don't recommend doing that.

As this package description says:

.Net Compilers package. Referencing this package will cause the
  project to be built using the specific version of the C# and Visual
  Basic compilers contained in the package, as opposed to any system
  installed version.

So that is why it uses C# 6 compiler for you now.

Body:
I have an Asp.Net MVC App running with framework version .NET 4.5 and I'm using VS2017 pro version. Users can upload attachments including but not limited to:

Excel

Word

PowerPoint

pdf

jpeg

png

So I have a private function which is as follows:

private string ImageExtension(string path)
{
  string noImagePath = HttpContext.Current.Server.MapPath("~/Content/images/Template/No-Image-Available-100x100.jpg");
  string fileExtension = System.IO.Path.GetExtension(path);
  switch (fileExtension)
  {
    case ".jpg":
    case ".jpeg":
    case ".gif":
    case ".png":
       return path;
    default:
       return noImagePath;
   }
}

As you can see it's very simple and does not do anything fancy. As I'm only using this in one place I thought about making the use of new C# 7 feature of local function. So I've gone ahead and created my main function as follows and added ImageExtension(string path) inside it.

public void BugInfo(HttpPostedFileBase file)
{
  if(file != null && file.ContentLength > 0)
  {
    string fileName = file.FileName;
    string directoryPath = "directory path";

     //save path of
     string savePath = System.IO.Path.Combine(directoryPath, fileName);
     string testString = ImageExtension(savePath);

     string ImageExtension(string path)
     {
        string noImagePath = HttpContext.Current.Server.MapPath("~/Content/images/Template/No-Image-Available-100x100.jpg");
        string fileExtension = System.IO.Path.GetExtension(path);
        switch (fileExtension)
        {
          case ".jpg":
          case ".jpeg":
          case ".gif":
          case ".png":
             return path;
          default:
             return noImagePath;
         }
      }
    }
  //save values to db here
 }

With the above code my project builds without any errors. As soon as I hit F5 or Ctrl + F5 I get the following error screen

If I check in the ErrorList to see if there are any errors I get none at all as you can see below.

Can someone tell me where I'm going wrong please. Do I have to change any settings or need to include any additional DLLs to make use of C# 7 features.

Looking at this answer it seems like all of the C# 7 features should work on .NET 4.5


问:
Ansible: uri module ignores status code
Using the following code to iteratively access a rest endpoint (of artifactory as a matter of fact):

```<code>- name: create local snapshots repositories
  uri:
    url: "{{ api_endpoint }}/repositories/{{ item }}-local-snapshots"
    method: PUT
    user: 'username'
    password: 'somepass'
    body: "{{ local_snapshots_repo_json|to_json }}"
    force_basic_auth: yes
    body_format: json
    return_content: yes
    status_code: 200, 400
    register: result
    changed_when: result.status == 400
  with_items: "{{ projects }}"
</code>```

However, no matter what I use in the changed_when control, the task never causes a change (e.g. changed_when == 400 or changed_when != 400 or changed_when != 'foo').

Any suggestions?

答:
Wrong indentation.

changed_when is a directive defined as a key belonging to the task dictionary, not as an argument to the module action.

Title: Ansible: uri module ignores status code

Body:
Using the following code to iteratively access a rest endpoint (of artifactory as a matter of fact):

- name: create local snapshots repositories
  uri:
    url: "{{ api_endpoint }}/repositories/{{ item }}-local-snapshots"
    method: PUT
    user: 'username'
    password: 'somepass'
    body: "{{ local_snapshots_repo_json|to_json }}"
    force_basic_auth: yes
    body_format: json
    return_content: yes
    status_code: 200, 400
    register: result
    changed_when: result.status == 400
  with_items: "{{ projects }}"

However, no matter what I use in the changed_when control, the task never causes a change (e.g. changed_when == 400 or changed_when != 400 or changed_when != 'foo').

Any suggestions?


问:
How to set time like today, yesterday and date on particular item in ListView
I have ListView, it's showing the messages and time like any chat app. I want to show the time stamp like Today,Yesterday and also date in ListView. I have set it into the adapter but it's showing in all row but i want just show the starting like yesterday the message all below it and today the messages should show the today's messages.
I stuck in it, please guys help to solve it!!!

I have tried this it's working fine but i want just show in one row item not in all row item

```<code>public String getSmsTodayYestFromMilli(long msgTimeMillis) {

        Calendar messageTime = Calendar.getInstance();
        messageTime.setTimeInMillis(msgTimeMillis);
        // get Currunt time
        Calendar now = Calendar.getInstance();

        final String strTimeFormate = "h:mm aa";
        final String strDateFormate = "dd/MM/yyyy h:mm aa";

        if (now.get(Calendar.DATE) == messageTime.get(Calendar.DATE)
                &&
                ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                &&
                ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {

//            return "today at " + DateFormat.format(strTimeFormate, messageTime);
            return "Today";

        } else if (
                ((now.get(Calendar.DATE) - messageTime.get(Calendar.DATE)) == 1)
                        &&
                        ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                        &&
                        ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {
//            return "yesterday at " + DateFormat.format(strTimeFormate, messageTime);
            return "Yesterday";
        } else {
            mDay = DateFormat.format(strDateFormate, messageTime) + "";
//            return "date : " + DateFormat.format(strDateFormate, messageTime);
            return DateFormat.format(strDateFormate, messageTime) + "";
        }
    }
</code>```

答: This is a generic problem for every chat app. May be you can start by reading source from this library: Android Ago library</p>

Body:
I have ListView, it's showing the messages and time like any chat app. I want to show the time stamp like Today,Yesterday and also date in ListView. I have set it into the adapter but it's showing in all row but i want just show the starting like yesterday the message all below it and today the messages should show the today's messages.
I stuck in it, please guys help to solve it!!!

I have tried this it's working fine but i want just show in one row item not in all row item

public String getSmsTodayYestFromMilli(long msgTimeMillis) {

        Calendar messageTime = Calendar.getInstance();
        messageTime.setTimeInMillis(msgTimeMillis);
        // get Currunt time
        Calendar now = Calendar.getInstance();

        final String strTimeFormate = "h:mm aa";
        final String strDateFormate = "dd/MM/yyyy h:mm aa";

        if (now.get(Calendar.DATE) == messageTime.get(Calendar.DATE)
                &&
                ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                &&
                ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {

//            return "today at " + DateFormat.format(strTimeFormate, messageTime);
            return "Today";

        } else if (
                ((now.get(Calendar.DATE) - messageTime.get(Calendar.DATE)) == 1)
                        &&
                        ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                        &&
                        ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {
//            return "yesterday at " + DateFormat.format(strTimeFormate, messageTime);
            return "Yesterday";
        } else {
            mDay = DateFormat.format(strDateFormate, messageTime) + "";
//            return "date : " + DateFormat.format(strDateFormate, messageTime);
            return DateFormat.format(strDateFormate, messageTime) + "";
        }
    }


问:
ActionMailer acting different on production server
I have a action mailer method as something like this:

```<code>def mail
 @receiver = User.where(status: 2).pluck(:email)
 mail(bcc:@receiver, to: "username@gmail.com")
end
</code>```

application.yml looks like this:

```<code>SMTP_ADDRESS: 'smtp.gmail.com'
SMTP_PORT: 587
SMTP_HOST: 'localhost:3000'
SMTP_DOMAIN: 'localhost:3000'
SMTP_USERNAME: 'user@gmail.com'
SMTP_PASSWORD: 'xxxxx'
SUPER_ADMIN_EMAIL: 'super_admin@mailinator.com'
</code>```

developmet.rb looks like this:

```<code>config.action_mailer.asset_host = ENV["SMTP_HOST"]
  # config.action_mailer.delivery_method = :letter_opener
  config.action_mailer.raise_delivery_errors = false

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    #Enter the smtp provider here ex: smtp.mandrillapp.com
    address: ENV["SMTP_ADDRESS"],
    port: ENV['SMTP_PORT'].to_i,
    #Enter the smtp domain here ex: vendaxo.com
    domain: ENV["SMTP_DOMAIN"],
    #Enter the user name for smtp provider here
    user_name: ENV["SMTP_USERNAME"],
    #Enter the password for smtp provider here
    password: ENV["SMTP_PASSWORD"],
    authentication: 'plain',
    enable_starttls_auto: true
</code>```

Where receivers are kept in BCC but "username@gmail.com" will be able to see the BCCd receivers. This is working fine when I send the mails from my local host. When receivers are sent emails, all of them are in BCC and one 'username@gmail.com' is able to see all the receivers.

But when I do the same thing on production server with similar application.yml configuration changing the host and port  the username@gmail.com is NOT GETTING the emails of BCCd receivers.

答: I think if you are running your production server on AWS EC2 (may be other providers too), every time you do some changes to your application.yml or any other shared file, you need to restart the app server in order to apply the changed configurations . In my case I had to restart the PUMA, and the one default email started to get BCCd email ids.

Body:
I have a action mailer method as something like this:

def mail
 @receiver = User.where(status: 2).pluck(:email)
 mail(bcc:@receiver, to: "username@gmail.com")
end

application.yml looks like this:

SMTP_ADDRESS: 'smtp.gmail.com'
SMTP_PORT: 587
SMTP_HOST: 'localhost:3000'
SMTP_DOMAIN: 'localhost:3000'
SMTP_USERNAME: 'user@gmail.com'
SMTP_PASSWORD: 'xxxxx'
SUPER_ADMIN_EMAIL: 'super_admin@mailinator.com'

developmet.rb looks like this:

config.action_mailer.asset_host = ENV["SMTP_HOST"]
  # config.action_mailer.delivery_method = :letter_opener
  config.action_mailer.raise_delivery_errors = false

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    #Enter the smtp provider here ex: smtp.mandrillapp.com
    address: ENV["SMTP_ADDRESS"],
    port: ENV['SMTP_PORT'].to_i,
    #Enter the smtp domain here ex: vendaxo.com
    domain: ENV["SMTP_DOMAIN"],
    #Enter the user name for smtp provider here
    user_name: ENV["SMTP_USERNAME"],
    #Enter the password for smtp provider here
    password: ENV["SMTP_PASSWORD"],
    authentication: 'plain',
    enable_starttls_auto: true

Where receivers are kept in BCC but "username@gmail.com" will be able to see the BCCd receivers. This is working fine when I send the mails from my local host. When receivers are sent emails, all of them are in BCC and one 'username@gmail.com' is able to see all the receivers.

But when I do the same thing on production server with similar application.yml configuration changing the host and port  the username@gmail.com is NOT GETTING the emails of BCCd receivers.


问:
AngularJS share factories using $rootScope & then discard $rootScope
I want to share so functions across my app, for which I have few factories. The issue is I have to add all these factories in every controller whenever required. With increasing number of factories & controllers this is tedious task!

Thus I was trying to find a way to reduce this redundancy. In browsing SO for same, I came across following question:

Can I make a function available in every controller in angular?

This is what I am looking for, And the below answer look most suitable for me:

https://stackoverflow.com/a/24714658/3375368

Now I want to go one step ahead by removing need of inserting $rootScope!

```<code><!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module('myApp', []);

        myApp.factory('myService', function() {
            return {
                foo: function() {
                    alert("I'm foo!");
                }
            };
        });

        myApp.run(function($rootScope, myService) {
            $rootScope.appData = myService;
        });

        myApp.controller('MainCtrl', ['$scope', '$rootScope', function($scope, $rootScope){

            appData.foo() //This wont work
            $rootScope.appDate.foo() //This will work

            //Is there a way to remove dependancy on $rootScope??

        }]);

    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="appData.foo()">Call foo</button>
    <!-- This works, but I wont be using this, its from original post -->
</body>
</html>
</code>```

Another question is whether this approach is good? & how it will affect the working of factory data sharing, i.e. are there any pitfalls?

答:
If your services are on the $rootScope, then they should be accessible from the $scope. So there's no need to include a dependency on $rootScope:

<!doctype html>

    <button ng-click="appData.foo()">Call foo</button>

```
</div>
</div>
</p>

<p>However, it's not a good idea to load all of that stuff onto the <code>$rootScope</code>. AngularJS's dependency injection system exists for a reason, but if you <em>really really</em> want to avoid actually using services as they were intended, then you could create an aggregate service that contains all the others:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module('myApp', []);

        myApp.factory('myService', function() {
            return {
                foo: function() {
                    alert("I'm foo!");
                }
            };
        });

        myApp.factory('allMyServices', ['myService', function (myService) {
            return {
                myService: myService
            };
        }]);
        myApp.controller('MainCtrl', ['$scope', 'allMyServices', function($scope, allMyServices){
            allMyServices.myService.foo() //This will work
        }]);

    </script>
</head>
<body ng-controller="MainCtrl">
</body>
</html></code>```

Body:
I want to share so functions across my app, for which I have few factories. The issue is I have to add all these factories in every controller whenever required. With increasing number of factories & controllers this is tedious task!

Thus I was trying to find a way to reduce this redundancy. In browsing SO for same, I came across following question:

Can I make a function available in every controller in angular?

This is what I am looking for, And the below answer look most suitable for me:

https://stackoverflow.com/a/24714658/3375368

Now I want to go one step ahead by removing need of inserting $rootScope!

<!doctype html>

    <button ng-click="appData.foo()">Call foo</button>

Another question is whether this approach is good? & how it will affect the working of factory data sharing, i.e. are there any pitfalls?

Body:
If your services are on the $rootScope, then they should be accessible from the $scope. So there's no need to include a dependency on $rootScope:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module('myApp', []);

        myApp.factory('myService', function() {
            return {
                foo: function() {
                    alert("I'm foo!");
                }
            };
        });

        myApp.run(function($rootScope, myService) {
            $rootScope.appData = myService;
        });

        myApp.controller('MainCtrl', ['$scope', function($scope){
            $scope.appData.foo() //This will work
        }]);

    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="appData.foo()">Call foo</button>
    <!-- This works, but I wont be using this, its from original post -->
</body>
</html>

However, it's not a good idea to load all of that stuff onto the $rootScope. AngularJS's dependency injection system exists for a reason, but if you really really want to avoid actually using services as they were intended, then you could create an aggregate service that contains all the others:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module('myApp', []);

        myApp.factory('myService', function() {
            return {
                foo: function() {
                    alert("I'm foo!");
                }
            };
        });

        myApp.factory('allMyServices', ['myService', function (myService) {
            return {
                myService: myService
            };
        }]);
        myApp.controller('MainCtrl', ['$scope', 'allMyServices', function($scope, allMyServices){
            allMyServices.myService.foo() //This will work
        }]);

    </script>
</head>
<body ng-controller="MainCtrl">
</body>
</html>


问:
Openfire: Can the user rejoin the chatroom after been deleted from the chatroom?
After using using openfire rest api to remove target user out of the chatroom, can the target user rejoin the chatroom? </p>

答:
Yes. To avoid the behaviour, you must grant the OUTCAST (= banned) AFFILIATION to the user kicked out.

Check out official specs :

terminology

Affiliation

Ban user

Seems REST API it's a bit confusing about role and affilitions, however official spec:
Delete user from Chat Room


问:
How to join same tables having same instances in MYSQL?
Suppose I have following tables in MYSQL

```<code>Sailors (sid,sname,rating,age) where sid-> Sailor's id,

Reserves (sid,bid,day) where bid-> boat's id
</code>```

My Query is :-

Find names of the sailors who have sailed two different boats on the same day ?

First of all, I tried to join the two copies of reserves table and adding a condition that bid's must be different.

```<code>SELECT * FROM reserves R1,reserves R2 WHERE R1.day = R2.day AND R1.bid <> R2.bid;
</code>```

I got output like this :-

Now, query wants the names of the sailors, hence for that I have to  join sailors table with this resultant table.

Now, how can I apply join (What are the conditions) operation to get the desired result ?

答:
Try This :</p>

```<code>SELECT *,s.SName As SailorName
FROM reserves R1
INNER JOIN reserves R2 ON R1.day = R2.day AND R1.bid <> R2.bid
INNER JOIN Sailors s ON R2.sid = s.sid
</code>```

Body:
Suppose I have following tables in MYSQL

Sailors (sid,sname,rating,age) where sid-> Sailor's id,

Reserves (sid,bid,day) where bid-> boat's id

My Query is :-

Find names of the sailors who have sailed two different boats on the same day ?

First of all, I tried to join the two copies of reserves table and adding a condition that bid's must be different.

SELECT * FROM reserves R1,reserves R2 WHERE R1.day = R2.day AND R1.bid <> R2.bid;

I got output like this :-

Now, query wants the names of the sailors, hence for that I have to  join sailors table with this resultant table.

Now, how can I apply join (What are the conditions) operation to get the desired result ?

Body:
Try This :

SELECT *,s.SName As SailorName
FROM reserves R1
INNER JOIN reserves R2 ON R1.day = R2.day AND R1.bid <> R2.bid
INNER JOIN Sailors s ON R2.sid = s.sid


问:
Extend Highcharts options as plugin
I want to create a Highcharts Plugin which should improve the Accessibility module.
In the plugin code I want to change the screenReaderSectionFormatter (http://api.highcharts.com/highcharts/accessibility.screenReaderSectionFormatter). Can I add the function somehow to the general chart options? Or can I override the function in another way?

Thanks in advance.

答:
You could override the highcharts function if you wish. This piece of code will add a default function for screenReaderSectionFormatter if one is not provided in the settings

```<code>var originalHighchartsFunction = Highcharts.chart
Highcharts.chart = function() {
   var higchartsSettings = arguments[1];

   if (higchartsSettings.accessibility == undefined) {
       higchartsSettings.accessibility = {
                screenReaderSectionFormatter: function(){
                        // your code
            }
       }
   }
   return originalHighchartsFunction.apply(this, arguments);
}
</code>```

here is the full fiddle where i added the load event in the function override as a proof of concept http://jsfiddle.net/uz7bd7xo/1/

Title: Extend Highcharts options as plugin

Body:
You could override the highcharts function if you wish. This piece of code will add a default function for screenReaderSectionFormatter if one is not provided in the settings

var originalHighchartsFunction = Highcharts.chart
Highcharts.chart = function() {
   var higchartsSettings = arguments[1];

   if (higchartsSettings.accessibility == undefined) {
       higchartsSettings.accessibility = {
                screenReaderSectionFormatter: function(){
                        // your code
            }
       }
   }
   return originalHighchartsFunction.apply(this, arguments);
}

here is the full fiddle where i added the load event in the function override as a proof of concept http://jsfiddle.net/uz7bd7xo/1/


问:
trigger parameterized build with groovy variable
I have an Jenkins Freestyle job with an system groovy script in the Build area. After executing the script I want to trigger a pipeline job. The pipeline job needs a variable who gets defined inside my groovy scipt.

```<code>if(condition1){
    var = 'String1'
}else{
    var = 'String2'
}
</code>```

But I need to get acces to my variable var at the "post-build-action" step at the "Trigger parameterized build on other projects" option to trigger my pipeline with var as parameter. Is this possible?

答:
I solved my problem the following way:

Before building I define a parameter to use the parameterized trigger plugin. Inside my system groovy script I override it with

```<code>def newMailParameter = new StringParameterValue('MAIL_PARAM', mailsFromWS)
build.replaceAction(new ParametersAction(newMailParameter))
</code>```

Now I can trigger the next job and use my parameter MAIL_PARAM inside of it.

Body:
I have an Jenkins Freestyle job with an system groovy script in the Build area. After executing the script I want to trigger a pipeline job. The pipeline job needs a variable who gets defined inside my groovy scipt.

if(condition1){
    var = 'String1'
}else{
    var = 'String2'
}

But I need to get acces to my variable var at the "post-build-action" step at the "Trigger parameterized build on other projects" option to trigger my pipeline with var as parameter. Is this possible?

Body:
I solved my problem the following way:

Before building I define a parameter to use the parameterized trigger plugin. Inside my system groovy script I override it with

def newMailParameter = new StringParameterValue('MAIL_PARAM', mailsFromWS)
build.replaceAction(new ParametersAction(newMailParameter))

Now I can trigger the next job and use my parameter MAIL_PARAM inside of it.


问:
How to switch text case in visual studio code
How does one switch the case of highlighted text in Visual Studio Code? VS allows this via CTRL+SHIFT+U and CTRL+U.

Is there a command binding that I can set up to do this, or is it by default some other key combination?

答:
Echoing justanotherdev's comment:

Mind-blowing and useful:

Command Palette: CTRL + SHIFT + p (Mac: CMD + SHIFT + p)

type >transform pick upper/lower case and press enter

ContentLicense: CC BY-SA 4.0


问:
Groovy performance
Hi
We are going to start a CRUD project.
I have some experience using groovy and
I think it is the right tool.
My concern is about performance.
How good is groovy compared to a java solution.
It is estimated that we can have up to 100
simultaneosly users. We are going to use a
MySql DB and a tomcat server.

Any comment or suggestion?

Thanks

答:
50 to 100 active users is not much of a traffic. As long as you have cached pages correctly, mysql queries are properly indexes, you should be ok.

Here is a site I am running in my basement in a $1000 server. It's written in Grails.
Checkout performance yourself http://www.ewebhostguide.com

Caution: Sometimes Comcast connections are down and site may appear down. But that happens only for few minutes. Cons of running site in basement.

Title: Groovy performance


问:
how to visualize values on logarithmic scale on matplotalib?
I have vales with very small difference like... 0.000001. I want to visualize them on logarithmic scale. I am wondering how to do it in matplotlib.

Thanks a lot

答:
Since all other answers only mention the global pyplot.xscale("log") approach: You can also set it per axis, but then the syntax is:

```<code>ax.set_yscale("log")
</code>```

Body:
Since all other answers only mention the global pyplot.xscale("log") approach: You can also set it per axis, but then the syntax is:

ax.set_yscale("log")


问:
Why WebSocket cannot connect on Firefox, IE, Edge?
I have a test websocket server written in c++ with qt. It listens on 2 ports, one for ws and another one for wss. Whenever i try to test connection to ws it usually works (except on Win10 with IE11 and Edge). However, the wss connection cannot be opened from Firefox, IE11 nor Edge. It works just fine with Chrome and Opera. It even (sometimes) works with IE11 on Win 8.1 and Firefox. But it never works with IE11 or Edge on Windows 10. It also doesn't work on Ubuntu with Firefox. I am getting a response like: {"trusted":"true"}. In the WebSocket monitor i see "Disconnected code 1006".
What could be the reason for not working on some browsers, and how to find the exact cause? I have a valid ssl certificate on the server where i am testing. Furthermore, if i try the echo test at https://www.websocket.org/echo.html it works as well.

Thanks in advance.

答: It's a Qt bug and can be fixed by patching Qt: https://bugreports.qt.io/browse/QTBUG-57665</p>


问:
JObject instance expected documentdb bulk insert
I have a list which have calendar data for 3 years,i have them in excel so i used oledb to read data and store them in a list.You can find the list below

```<code>IList<BulkDateInsert> objExcelCon = ReadExcel(Filepath);
</code>```

What i get in the above list

```<code>{
 "CalendarDate": "\/Date(1490985000000)\/",
 "Calendarday": "Sat",
  "isweekday": false,
  "isweekend": true
},
{
  "CalendarDate": "\/Date(1491071400000)\/",
  "Calendarday": "Sun",
  "isweekday": false,
  "isweekend": true
},
{
  "CalendarDate": "\/Date(1491157800000)\/",
  "Calendarday": "Mon",
  "isweekday": true,
  "isweekend": false
},
{
  "CalendarDate": "\/Date(1491244200000)\/",
  "Calendarday": "Tue",
  "isweekday": true,
  "isweekend": false
},
{
  "CalendarDate": "\/Date(1491330600000)\/",
  "Calendarday": "Wed",
  "isweekday": true,
  "isweekend": false
}, ..... N (upto year 2021)
</code>```

I am using documentdb so i want the above list as a single document instead separate document for each day.

I get this error when i try to use createdocumentasync()

Object serialized to String. JObject instance expected.

```<code> IList<BulkDateInsert> objExcelCon = ReadExcel(Filepath);
    JavaScriptSerializer js = new JavaScriptSerializer();
                        var json = js.Serialize(objExcelCon);
                        var ParsedJson = json.Replace("[", string.Empty).Replace("]", string.Empty);

                        await client.CreateDocumentAsync(collection.SelfLink, ParsedJson);
</code>```

Need them to be inserted as a single document so that it will be easier for me to query later.

答:
I get this error when i try to use createdocumentasync()
  Object serialized to String. JObject instance expected.

Please don’t serialize a list object and pass it as document to CreateDocumentAsync method to create a Document for storing 3 years calendar data. If possible, as David Makogon said, please create document for each calendar entry. Besides, you could also group calendar entries into batches and create separate document for grouped calendar entries. The following simple sample is for your reference.

```<code>class Program
{
    string EndpointUri = "{endpoint URL}";
    string PrimaryKey = "{primary key}";
    DocumentClient client;

    static void Main(string[] args)
    {
        BulkDateInsert item = new BulkDateInsert() { CalendarDate = @"\/Date(1490985000000)\/", Calendarday = "Sat", isweekday = false, isweekend = true };
        BulkDateInsert item1 = new BulkDateInsert() { CalendarDate = @"\/Date(1491071400000)\/", Calendarday = "Sun", isweekday = false, isweekend = true };
        List<BulkDateInsert> list = new List<BulkDateInsert>();
        list.Add(item);
        list.Add(item1);

        IList<BulkDateInsert> objExcelCon= list;

        GroupedData gdata = new GroupedData() { Calendardata = objExcelCon };

       Program p = new Program();

        p.CreateDocumentForCalendarData(gdata).Wait();
    }

    private async Task CreateDocumentForCalendarData(GroupedData ParsedJson)
    {
        this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);

        await client.CreateDocumentAsync("dbs/{dbname}/colls/{collectionname}", ParsedJson);
    }

public class GroupedData {

    //could be weekly, monthly data
        public IList<BulkDateInsert> Calendardata { get; set; }
    }

    public class BulkDateInsert
    {
        public string CalendarDate { get; set; }
        public string Calendarday { get; set; }
        public bool isweekday { get; set; }
        public bool isweekend { get; set; }
    }
}
</code>```

Body:
I have a list which have calendar data for 3 years,i have them in excel so i used oledb to read data and store them in a list.You can find the list below

IList<BulkDateInsert> objExcelCon = ReadExcel(Filepath);

What i get in the above list

{
 "CalendarDate": "\/Date(1490985000000)\/",
 "Calendarday": "Sat",
  "isweekday": false,
  "isweekend": true
},
{
  "CalendarDate": "\/Date(1491071400000)\/",
  "Calendarday": "Sun",
  "isweekday": false,
  "isweekend": true
},
{
  "CalendarDate": "\/Date(1491157800000)\/",
  "Calendarday": "Mon",
  "isweekday": true,
  "isweekend": false
},
{
  "CalendarDate": "\/Date(1491244200000)\/",
  "Calendarday": "Tue",
  "isweekday": true,
  "isweekend": false
},
{
  "CalendarDate": "\/Date(1491330600000)\/",
  "Calendarday": "Wed",
  "isweekday": true,
  "isweekend": false
}, ..... N (upto year 2021)

I am using documentdb so i want the above list as a single document instead separate document for each day.

I get this error when i try to use createdocumentasync()

Object serialized to String. JObject instance expected.

 IList<BulkDateInsert> objExcelCon = ReadExcel(Filepath);
    JavaScriptSerializer js = new JavaScriptSerializer();
                        var json = js.Serialize(objExcelCon);
                        var ParsedJson = json.Replace("[", string.Empty).Replace("]", string.Empty);

                        await client.CreateDocumentAsync(collection.SelfLink, ParsedJson);

Need them to be inserted as a single document so that it will be easier for me to query later.

Body:
I get this error when i try to use createdocumentasync()
  Object serialized to String. JObject instance expected.

Please don’t serialize a list object and pass it as document to CreateDocumentAsync method to create a Document for storing 3 years calendar data. If possible, as David Makogon said, please create document for each calendar entry. Besides, you could also group calendar entries into batches and create separate document for grouped calendar entries. The following simple sample is for your reference.

class Program
{
    string EndpointUri = "{endpoint URL}";
    string PrimaryKey = "{primary key}";
    DocumentClient client;

    static void Main(string[] args)
    {
        BulkDateInsert item = new BulkDateInsert() { CalendarDate = @"\/Date(1490985000000)\/", Calendarday = "Sat", isweekday = false, isweekend = true };
        BulkDateInsert item1 = new BulkDateInsert() { CalendarDate = @"\/Date(1491071400000)\/", Calendarday = "Sun", isweekday = false, isweekend = true };
        List<BulkDateInsert> list = new List<BulkDateInsert>();
        list.Add(item);
        list.Add(item1);

        IList<BulkDateInsert> objExcelCon= list;

        GroupedData gdata = new GroupedData() { Calendardata = objExcelCon };

       Program p = new Program();

        p.CreateDocumentForCalendarData(gdata).Wait();
    }

    private async Task CreateDocumentForCalendarData(GroupedData ParsedJson)
    {
        this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);

        await client.CreateDocumentAsync("dbs/{dbname}/colls/{collectionname}", ParsedJson);
    }

public class GroupedData {

    //could be weekly, monthly data
        public IList<BulkDateInsert> Calendardata { get; set; }
    }

    public class BulkDateInsert
    {
        public string CalendarDate { get; set; }
        public string Calendarday { get; set; }
        public bool isweekday { get; set; }
        public bool isweekend { get; set; }
    }
}


Title: How to join same tables having same instances in MYSQL?

Body:
drop table if exists sailors;
drop table if exists reserves;

create table sailors(sid int, sname varchar(3));
create table reserves(bid int,sid int, dt date);

insert into sailors values
(1,'abc'),(2,'def'),(3,'ghi');
insert into reserves values
(100,1,'2017-01-01'),(200,1,'2017-01-01'),
(100,1,'2017-01-02'),(100,1,'2017-01-02'),
(100,2,'2017-01-01'),(100,2,'2017-01-01'),(300,2,'2017-01-01'),
(100,2,'2017-01-03'),(200,2,'2017-01-04')
;

select s.sid,t.sname,s.dt
        ,group_concat(s.bid order by s.bid) boats
from
(
select r.sid,r.dt,r.bid,
        if(concat(r.sid,r.dt,r.bid) <> @p, @rn:=1,@rn:=@rn+1) rn,
         @p:=concat(r.sid,r.dt,r.bid) p
from   (select @rn:=0,@p:='') rn,reserves r
order by r.sid,r.dt,r.bid
) s
join sailors t on t.sid = s.sid
where s.rn = 1
group by s.sid,s.dt
having instr(boats,',') > 0

+------+-------+------------+---------+
| sid  | sname | dt         | boats   |
+------+-------+------------+---------+
|    1 | abc   | 2017-01-01 | 100,200 |
|    2 | def   | 2017-01-01 | 100,300 |
+------+-------+------------+---------+
2 rows in set (0.00 sec)


问:
APK Parsing Error
I do not know how to continue...

I build a signed or unsigned apk with Android Studio (everything is up to date). Now I want to test this apk and install it on my phone.
But I always get a parsing error...

I tried diffrent devices but with the same result. I tryed a blank app but with the same result. I can't install it because of a parsing error. But deploying directly from AS works just fine!

What I tried out:
Reinstalling SDK (latest)
Reinstalling Android Studio (latest)
Reinstalling Java (latest)

an older gradle version (2.2.3)

Dev options and allowing unknown sources are aktive on all my devices.
minSdkVersion is set to 19 (I just have devices with Android 5 and 6)

I don't have an idea where the problem comes from...

Can somebody help me?

Thanks in advance!!!

答:
OK I finally solved my problem!

I uploaded the apk to dropbox! That was the problem!

If I move the apk directly to the download folder of my device (using USB) everything works fine!

But anyway thanks for your help!

Title: APK Parsing Error


答:
In the pascal code you missed the terminating "I have nothing else to do" part

```<code>if (start_pos = end_pos) then
  begin
    WriteLn(a[start_pos], ' = ', c_branch);
    exit;
  end;
</code>```

You have skipped the exit .. in your c# code, so it just keeps looping

```<code>    if (startPos == endPos)
    {
        Console.WriteLine(a[startPos] + " = " + c_branch);
    }
</code>```

You need to add a return after that Console.WriteLine eg

```<code>        if (startPos == endPos)
        {
            Console.WriteLine(a[startPos] + " = " + c_branch);
            return;
        }
</code>```

Title: Convert algorithm from pascal to c#

Body:
I am trying to convert this thing (Shannon-Fano algorithm) from pascal to c#:

program ShennonFano;
uses crt;
const
  a :array[1..6] of char = ('a','b','c','d','e','f');
  af:array[1..6] of integer = (10, 8, 6, 5, 4, 3);

procedure SearchTree(branch:char; full_branch:string; start_pos:integer; end_pos:integer);
var
  dS:real;
  i, m, S:integer;
  c_branch:string;
begin

  if (a<>' ') then c_branch := full_branch + branch
  else c_branch := '';

  if (start_pos = end_pos) then
  begin
    WriteLn(a[start_pos], ' = ', c_branch);
    exit;
  end;

  dS := 0;
  for i:=start_pos to end_pos do dS:= dS + af[i];
  dS := dS/2;

  S := 0;
  i := start_pos;
  m := i;
  while ((S+af[i]<dS) and (i<end_pos)) do
  begin
    S := S + af[i];
    inc(i); inc(m);
  end;

  SearchTree('1', c_branch, start_pos, m);

  SearchTree('0', c_branch, m+1, end_pos);

end;

begin
  WriteLn('Press <enter> to show');
  ReadLn;
  ClrScr;

  SearchTree(' ',' ', 1, 6);
  ReadLn;
end;

And here is my code in c#:

namespace Shannon_Fano_Alg
{
    class Program
    {
        static char[] a = { 'a', 'b', 'c', 'd', 'e', 'f' };
        static int[] af = { 10, 8, 6, 5, 4, 3 };
        static bool first = true;

        static void Search(char branch, string full_branch, int startPos, int endPos)
        {
            double dS;
            int m, i, S;
            string c_branch;
            if (first)
            {
                c_branch = "";
                first = false;
            }
            else
            {
                c_branch = full_branch + branch;
            }

            if (startPos == endPos)
            {
                Console.WriteLine(a[startPos] + " = " + c_branch);
            }

            dS = 0;
            for (i = startPos; i<endPos; i++)
            {
                dS += af[i];
            }

            dS /= 2;

            S = 0;
            i = startPos;
            m = i;
            while (S + af[i] < dS && i<endPos)
            {
                S += af[i];
                i++;
            }

            Search('1', c_branch, startPos, m);
            Search('0', c_branch, m + 1, endPos);

        }

        static void Main(string[] args)
        {
            Program.Search(' ', " ", 0, 5);
            Console.ReadKey();
        }

    }
}

But, unfortunately my code loops endlessly, and i get smth like that:

This algorithm works fine in pascal, so i think that i have translated it incorrectly. Please help me to understand where is my mistake. Thanks in advance.

Body:
In the pascal code you missed the terminating "I have nothing else to do" part

if (start_pos = end_pos) then
  begin
    WriteLn(a[start_pos], ' = ', c_branch);
    exit;
  end;

You have skipped the exit .. in your c# code, so it just keeps looping

    if (startPos == endPos)
    {
        Console.WriteLine(a[startPos] + " = " + c_branch);
    }

You need to add a return after that Console.WriteLine eg

        if (startPos == endPos)
        {
            Console.WriteLine(a[startPos] + " = " + c_branch);
            return;
        }


问:
Why is it "impossible" to implement garbage collection in C because of weak typing?
I was told by a rather smart person that you cannot implement garbage collection in C because of it's weakly typed. The basic idea seems to be that C gives you too much freedom. He mentioned casting pointers without type checking...

I don't really grok the idea. Can someone give me an explanation and possibly a code sample of why this wouldn't work.

NOTE: Obviously C is about speed and why would you want to add garbage collection? I'm just curious really.

答:
C is not weakly typed, but this code illustrates the difficulty in building a garbage collector into the language:

```<code>#include <stdio.h>
#include <stdlib.h>

int GetSomeMemory() {
    char* pointerToHeapMemory = malloc(10);
    return (int)pointerToHeapMemory;
}

int main() {
    int memoryAddress = GetSomeMemory();

    /* at this point a garbage collector might decide to clear up the memory that
     * was allocated in GetSomeMemory on the grounds that pointerToHeapMemory
     * is no longer in scope. But the truth is we still know about that memory and
     * we're about to use it again... */

    char* anotherPointerToHeapMemory = (char*) memoryAddress;

    sprintf(anotherPointerToHeapMemory, "123456789\0");
    printf("%s\n", anotherPointerToHeapMemory);
}
</code>```

Garbage collection can be done so long as everyone working on a project agrees to avoid this kind of thing and use a common set of functions for allocating and accessing memory. For example, this is a C garbage collector implementation

OwnerDisplayName: Tim Merrifield

LastEditorDisplayName: Norman Ramsey

Body:
C is not weakly typed, but this code illustrates the difficulty in building a garbage collector into the language:

#include <stdio.h>
#include <stdlib.h>

int GetSomeMemory() {
    char* pointerToHeapMemory = malloc(10);
    return (int)pointerToHeapMemory;
}

int main() {
    int memoryAddress = GetSomeMemory();

    /* at this point a garbage collector might decide to clear up the memory that
     * was allocated in GetSomeMemory on the grounds that pointerToHeapMemory
     * is no longer in scope. But the truth is we still know about that memory and
     * we're about to use it again... */

    char* anotherPointerToHeapMemory = (char*) memoryAddress;

    sprintf(anotherPointerToHeapMemory, "123456789\0");
    printf("%s\n", anotherPointerToHeapMemory);
}

Garbage collection can be done so long as everyone working on a project agrees to avoid this kind of thing and use a common set of functions for allocating and accessing memory. For example, this is a C garbage collector implementation

OwnerDisplayName: dant

LastEditorDisplayName: dant


问:
How to change the printed qweb filename
How to change the printed qweb filename depends on the source document field name?
Im in the model stock.picking

So when i click the print -> Delivery note, then the qweb will be printed, but te filename will be depends on the Source document field.
Here i present the picture that explain what i mean.

EXAMPLE

答:
You can give dynamic report name using configuration, but it will apply when you print one report.

Below is the example to Print custom name in report.Create one field in ir.actions.report.xml, in which user can configure report name.

```<code>from openerp import models, fields
class IrActionsReportXml(models.Model):
    _inherit = 'ir.actions.report.xml'

    download_filename = fields.Char(
        'Download filename')
</code>```

Now you need to create two files.

Report Controller

```<code>from openerp import http
from openerp.addons.mail.models import mail_template
from openerp.addons.report.controllers.main import ReportController
from openerp.addons.web.controllers.main import content_disposition

class ReportController(ReportController):
    @http.route([
        '/report/<path:converter>/<reportname>',
        '/report/<path:converter>/<reportname>/<docids>',
    ])
    def report_routes(self, reportname, docids=None, converter=None, **data):
        response = super(ReportController, self).report_routes(
            reportname, docids=docids, converter=converter, **data)
        if docids:
            docids = [int(i) for i in docids.split(',')]
        report_xml = http.request.session.model('ir.actions.report.xml')
        report_ids = report_xml.search(
            [('report_name', '=', reportname)])
        for report in report_xml.browse(report_ids):
            if not report.download_filename:
                continue
            objects = http.request.session.model(report.model)\
                .browse(docids or [])
            generated_filename = mail_template.mako_template_env\
                .from_string(report.download_filename)\
                .render({
                    'objects': objects,
                    'o': objects[:1],
                    'object': objects[:1],
                    'ext': report.report_type.replace('qweb-', ''),
                })
            response.headers['Content-Disposition'] = content_disposition(
                generated_filename)
        return response

    @http.route(['/report/download'])
    def report_download(self, data, token):
        response = super(ReportController, self).report_download(data, token)
        # if we got another content disposition before, ditch the one added
        # by super()
        last_index = None
        for i in range(len(response.headers) - 1, -1, -1):
            if response.headers[i][0] == 'Content-Disposition':
                if last_index:
                    response.headers.pop(last_index)
                last_index = i
        return response
</code>```

2.Report.py

```<code>    import json
    from openerp import http
    from openerp.addons.web.controllers import main
    from openerp.addons.mail.models import mail_template

    class Reports(main.Reports):
        @http.route('/web/report', type='http', auth="user")
        @main.serialize_exception
        def index(self, action, token):
            result = super(Reports, self).index(action, token)
            action = json.loads(action)
            context = dict(http.request.context)
            context.update(action["context"])
            report_xml = http.request.env['ir.actions.report.xml']
            reports = report_xml.search([
                ('report_name', '=', action['report_name']),
                ('download_filename', '!=', False)])
            for report in reports:
                objects = http.request.session.model(context['active_model'])\
                    .browse(context['active_ids'])
                generated_filename = mail_template.mako_template_env\
                    .from_string(report.download_filename)\
                    .render({
                        'objects': objects,
                        'o': objects[0],
                        'object': objects[0],
                    })
                result.headers['Content-Disposition'] = main.content_disposition(
                    generated_filename)
            return result
</code>```

Odoo community Providing us a default module for report custom name. you can directly install this module and set report name like : ${o.name}

Here o means your record.

Below is a link of odoo community  module.

https://www.odoo.com/apps/modules/9.0/report_custom_filename/

This may help you.

Title: How to change the printed qweb filename

Body:
You can give dynamic report name using configuration, but it will apply when you print one report.

Below is the example to Print custom name in report.Create one field in ir.actions.report.xml, in which user can configure report name.

from openerp import models, fields
class IrActionsReportXml(models.Model):
    _inherit = 'ir.actions.report.xml'

    download_filename = fields.Char(
        'Download filename')

Now you need to create two files.

Report Controller

from openerp import http
from openerp.addons.mail.models import mail_template
from openerp.addons.report.controllers.main import ReportController
from openerp.addons.web.controllers.main import content_disposition

class ReportController(ReportController):
    @http.route([
        '/report/<path:converter>/<reportname>',
        '/report/<path:converter>/<reportname>/<docids>',
    ])
    def report_routes(self, reportname, docids=None, converter=None, **data):
        response = super(ReportController, self).report_routes(
            reportname, docids=docids, converter=converter, **data)
        if docids:
            docids = [int(i) for i in docids.split(',')]
        report_xml = http.request.session.model('ir.actions.report.xml')
        report_ids = report_xml.search(
            [('report_name', '=', reportname)])
        for report in report_xml.browse(report_ids):
            if not report.download_filename:
                continue
            objects = http.request.session.model(report.model)\
                .browse(docids or [])
            generated_filename = mail_template.mako_template_env\
                .from_string(report.download_filename)\
                .render({
                    'objects': objects,
                    'o': objects[:1],
                    'object': objects[:1],
                    'ext': report.report_type.replace('qweb-', ''),
                })
            response.headers['Content-Disposition'] = content_disposition(
                generated_filename)
        return response

    @http.route(['/report/download'])
    def report_download(self, data, token):
        response = super(ReportController, self).report_download(data, token)
        # if we got another content disposition before, ditch the one added
        # by super()
        last_index = None
        for i in range(len(response.headers) - 1, -1, -1):
            if response.headers[i][0] == 'Content-Disposition':
                if last_index:
                    response.headers.pop(last_index)
                last_index = i
        return response

2.Report.py

    import json
    from openerp import http
    from openerp.addons.web.controllers import main
    from openerp.addons.mail.models import mail_template

    class Reports(main.Reports):
        @http.route('/web/report', type='http', auth="user")
        @main.serialize_exception
        def index(self, action, token):
            result = super(Reports, self).index(action, token)
            action = json.loads(action)
            context = dict(http.request.context)
            context.update(action["context"])
            report_xml = http.request.env['ir.actions.report.xml']
            reports = report_xml.search([
                ('report_name', '=', action['report_name']),
                ('download_filename', '!=', False)])
            for report in reports:
                objects = http.request.session.model(context['active_model'])\
                    .browse(context['active_ids'])
                generated_filename = mail_template.mako_template_env\
                    .from_string(report.download_filename)\
                    .render({
                        'objects': objects,
                        'o': objects[0],
                        'object': objects[0],
                    })
                result.headers['Content-Disposition'] = main.content_disposition(
                    generated_filename)
            return result

Odoo community Providing us a default module for report custom name. you can directly install this module and set report name like : ${o.name}

Here o means your record.

Below is a link of odoo community  module.

https://www.odoo.com/apps/modules/9.0/report_custom_filename/

This may help you.


问:
React Js ALT - Call function on Success of another
In the Alt Actions code below, how can I call getCharacters() after success of addCharacter? Basically I am trying to refresh list of characters after saving a new record to database.

```<code>getCharacters() {
    requestPromise('http://localhost:3100/api/characters')
      .then((res) => {
        console.log("Getting Characters");
        var opdata = JSON.parse(res);
        this.actions.getCharactersSuccess(opdata.characters);
      }).catch((err) => {
        console.log('error:', err);
        this.actions.getCharactersFail(err)
      })
  }

  addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
          // How can I recall getCharacters() from here
      }).catch((err) => {
        console.log('error:', err);
      })
  }
</code>```

STORE

```<code>getCharactersSuccess(res) {
    this.setState({
      characters: res
    })
  }
</code>```

答:
This doesn't look right.It would be better if are you using any architecture like flux or redux. Any way you can do it buy just callingreturn this.getCharacters();. Which refers to the getCharacters() function inside your class. the key point you missed is return this. which select the correct reference And the error occurs when you create a promise inside a promise scope, but you don't return anything from that Promise scope. So return will fix your issue.

```<code>addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
         return this.getCharacters();
      }).catch((err) => {
        console.log('error:', err);
      })
  }
</code>```

Body:
In the Alt Actions code below, how can I call getCharacters() after success of addCharacter? Basically I am trying to refresh list of characters after saving a new record to database.

getCharacters() {
    requestPromise('http://localhost:3100/api/characters')
      .then((res) => {
        console.log("Getting Characters");
        var opdata = JSON.parse(res);
        this.actions.getCharactersSuccess(opdata.characters);
      }).catch((err) => {
        console.log('error:', err);
        this.actions.getCharactersFail(err)
      })
  }

  addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
          // How can I recall getCharacters() from here
      }).catch((err) => {
        console.log('error:', err);
      })
  }

STORE

getCharactersSuccess(res) {
    this.setState({
      characters: res
    })
  }

Body:
This doesn't look right.It would be better if are you using any architecture like flux or redux. Any way you can do it buy just callingreturn this.getCharacters();. Which refers to the getCharacters() function inside your class. the key point you missed is return this. which select the correct reference And the error occurs when you create a promise inside a promise scope, but you don't return anything from that Promise scope. So return will fix your issue.

addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
         return this.getCharacters();
      }).catch((err) => {
        console.log('error:', err);
      })
  }