问:
NODE.JS connect to multiple database on the fly gives me error
I am creating an API where I need to connect to different database using thier credentials on the fly. I need to make functionality similar to MySql workbench - test connection. Currently, I need to deal with MySql and MSSql server. I have to check all the permutation and combination for wrong credentials. i.e. if I pass correct credentials for example, correct host, username, password, port but wrong connector instead of MySql I pass Mssql. That is throwing an exception.

```<code>var db = {
   host           : data.hostName,
   port           : data.port,
   database       : data.database,
   username       : data.userName,
   password       : data.password,
   connector      : response[0].node_js_connector
 }

 var dataSource = new DataSource(db.connector, db);
 dataSource.on('connected', function (er) {
   if(er) {
     console.log("reject");
     reject(er);
   }
   else {
     console.log("resolve");
     resolve('Work With Database');
   }
 });
 dataSource.on('error', function (er) {
   if(er) {
     console.log("reject1");
     reject(er);
   }
   else {
     console.log("reject1");
     reject('Not Connected Databse');
   }
 });
</code>```

I have also put the code in try/catch block to handle exception. However, I am not able to catch it. Currently, I am getting following error:

```<code>throw new RangeError('Index out of range');

RangeError: Index out of range
    at checkOffset (buffer.js:968:11)
    at Buffer.readUInt8 (buffer.js:1006:5)
</code>```

It would be a great help, if someone can assist me in solving this issue.

Thanks in advance.

答:
i use process.on() method to headland uncaughtException. this method handle all the exception in file execution time. so, in this time uncaughtException will handle my Index out of range exception. and reject my dataSource connection.

```<code>process.on('uncaughtException', function (err) {
    console.log('UNCAUGHT EXCEPTION - keeping process alive:', err); // err.message is "foobar"
    reject('Connected Faile');
});
</code>```

Body:
I am creating an API where I need to connect to different database using thier credentials on the fly. I need to make functionality similar to MySql workbench - test connection. Currently, I need to deal with MySql and MSSql server. I have to check all the permutation and combination for wrong credentials. i.e. if I pass correct credentials for example, correct host, username, password, port but wrong connector instead of MySql I pass Mssql. That is throwing an exception.

var db = {
   host           : data.hostName,
   port           : data.port,
   database       : data.database,
   username       : data.userName,
   password       : data.password,
   connector      : response[0].node_js_connector
 }

 var dataSource = new DataSource(db.connector, db);
 dataSource.on('connected', function (er) {
   if(er) {
     console.log("reject");
     reject(er);
   }
   else {
     console.log("resolve");
     resolve('Work With Database');
   }
 });
 dataSource.on('error', function (er) {
   if(er) {
     console.log("reject1");
     reject(er);
   }
   else {
     console.log("reject1");
     reject('Not Connected Databse');
   }
 });

I have also put the code in try/catch block to handle exception. However, I am not able to catch it. Currently, I am getting following error:

throw new RangeError('Index out of range');

RangeError: Index out of range
    at checkOffset (buffer.js:968:11)
    at Buffer.readUInt8 (buffer.js:1006:5)

It would be a great help, if someone can assist me in solving this issue.

Thanks in advance.

Body:
i use process.on() method to headland uncaughtException. this method handle all the exception in file execution time. so, in this time uncaughtException will handle my Index out of range exception. and reject my dataSource connection.

process.on('uncaughtException', function (err) {
    console.log('UNCAUGHT EXCEPTION - keeping process alive:', err); // err.message is "foobar"
    reject('Connected Faile');
});


来源: stackexchange

问:
Adding custom methods to standard ruby objects
How can I add custom methods to standard ruby objects, such as strings and integers?

I have seen this in, for example, rails, and the mojinizer library for ruby that can convert a romaji string into hiragana, as in

```<code>"tsukue".hiragana #=> "つくえ"
</code>```

答:
Just open the class and add the method.  You can open a class as many times as you need to.

```<code>class Fixnum
  def lucky?
    self == 7
  end
end

95.lucky?
=> false

7.lucky?
=> true
</code>```

It's a useful ability and we've all done it.  Take care that your code is maintainable and that you don't break basic functionality.

ContentLicense: CC BY-SA 3.0

Body:
How can I add custom methods to standard ruby objects, such as strings and integers?

I have seen this in, for example, rails, and the mojinizer library for ruby that can convert a romaji string into hiragana, as in

"tsukue".hiragana #=> "つくえ"

Body:
Just open the class and add the method.  You can open a class as many times as you need to.

class Fixnum
  def lucky?
    self == 7
  end
end

95.lucky?
=> false

7.lucky?
=> true

It's a useful ability and we've all done it.  Take care that your code is maintainable and that you don't break basic functionality.


问:
DataTables warning - Requested unknown parameter '0' for row 0, column 0
I am working with DataTable.js and trying to implement into MVC. I've written code as per below:

View:

```<code><div id="container">
    <div id="demo">
        <h2>Index</h2>
        <table id="myDataTable" class="display">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Event Name</th>
                    <th>Event Type</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>
@section scripts{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#myDataTable').dataTable({
                "bServerSide": true,
                "sAjaxSource": "@Url.Action("AjaxHandler","DataTable")",
                "bProcessing": true,
                "aoColumns": [
                    { "sName": "EventID" },
                    { "sName": "EventName" },
                    { "sName": "EventTypeTitle" }
                ]
            });
        });
    </script>
}
</code>```

And Controller:

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

public ActionResult AjaxHandler(jQueryDataTableParamModel param)
{
      return Json(new
      {
           sEcho = param.sEcho,
           iTotalRecords = getAllEvent().Count(),
           iTotalDisplayRecords = getAllEvent().Count(),
           aaData = getAllEvent()
      }, JsonRequestBehavior.AllowGet);
}

private List<EventModel> getAllEvent()
{
      List<EventModel> model = new List<EventModel>();
      EventModel model1 = new EventModel { EventID = 1, EventName = "Event 1", EventType = 1, EventTypeTitle = "General" };
      model1.EventScheduleList = new List<EventScheduleModel> { new EventScheduleModel {EventScheduleID = 1 }, new EventScheduleModel { EventScheduleID = 2 } };
      model.Add(model1);
      return model;
}
</code>```

I am getting DataTables warning: table id=myDataTable - Requested
  unknown parameter '0' for row 0, column 0. For more information about
  this error, please see http://datatables.net/tn/4

As I research about the error I could find that this particular error is occur when data is not in correct manner. but, when I check response, I am getting correct data.

Is it because I have returned more numbers of columns which are used
  in View? or Do I send integer value in JSON?

I've attached fiddle link as well:
https://dotnetfiddle.net/MEoqg8

答:
You need to make very small change in you JacaScript code which goes like this, which means instead of using sName you need to use data inside aoColumns array.

```<code>    <script>
    $(document).ready(function () {
        $('#myDataTable').dataTable({
            "bServerSide": true,
            "sAjaxSource": '@Url.Action("AjaxHandler","Home")',
            "bProcessing": true,
            "aoColumns": [
                {
                    "data": "EventID",
                    "bSearchable": false,
                    "fnRender": function (oObj) {
                        return '<a href=\"Details/' +
                            oObj.aData[0] + '\">View</a>';
                    }
                },
                { "data": "EventName" },
                { "data": "EventTypeTitle" }
            ]
        });
    });
</script>
</code>```

You can check a fork from your fiddle here : https://dotnetfiddle.net/7sXghO

Body:
I am working with DataTable.js and trying to implement into MVC. I've written code as per below:

View:

Index

                    ID
                    Event Name
                    Event Type

@section scripts{

}

And Controller:

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

public ActionResult AjaxHandler(jQueryDataTableParamModel param)
{
      return Json(new
      {
           sEcho = param.sEcho,
           iTotalRecords = getAllEvent().Count(),
           iTotalDisplayRecords = getAllEvent().Count(),
           aaData = getAllEvent()
      }, JsonRequestBehavior.AllowGet);
}

private List<EventModel> getAllEvent()
{
      List<EventModel> model = new List<EventModel>();
      EventModel model1 = new EventModel { EventID = 1, EventName = "Event 1", EventType = 1, EventTypeTitle = "General" };
      model1.EventScheduleList = new List<EventScheduleModel> { new EventScheduleModel {EventScheduleID = 1 }, new EventScheduleModel { EventScheduleID = 2 } };
      model.Add(model1);
      return model;
}

I am getting DataTables warning: table id=myDataTable - Requested
  unknown parameter '0' for row 0, column 0. For more information about
  this error, please see http://datatables.net/tn/4

As I research about the error I could find that this particular error is occur when data is not in correct manner. but, when I check response, I am getting correct data.

Is it because I have returned more numbers of columns which are used
  in View? or Do I send integer value in JSON?

I've attached fiddle link as well:
https://dotnetfiddle.net/MEoqg8

Body:
You need to make very small change in you JacaScript code which goes like this, which means instead of using sName you need to use data inside aoColumns array.

    <script>
    $(document).ready(function () {
        $('#myDataTable').dataTable({
            "bServerSide": true,
            "sAjaxSource": '@Url.Action("AjaxHandler","Home")',
            "bProcessing": true,
            "aoColumns": [
                {
                    "data": "EventID",
                    "bSearchable": false,
                    "fnRender": function (oObj) {
                        return '<a href=\"Details/' +
                            oObj.aData[0] + '\">View</a>';
                    }
                },
                { "data": "EventName" },
                { "data": "EventTypeTitle" }
            ]
        });
    });
</script>

You can check a fork from your fiddle here : https://dotnetfiddle.net/7sXghO


问:
OutOfMemoryException when adding large number of files in ZipFile
I am facing an issue of OutofMemoryException when I add large number of files in ZipFile. The sample code is as below:

```<code>ZipFile file = new ZipFile("E:\\test1.zip");
file.UseZip64WhenSaving = Zip64Option.AsNecessary;
file.ParallelDeflateThreshold = -1;
for (Int64 i = 0; i < 1000000; i++)
{
   file.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
   byte[] data = Encoding.ASCII.GetBytes("rama");
   ZipEntry entry = file.AddEntry(@"myFolder1/test1/myhtml111.html" + i.ToString(), data);
}
file.Save();
</code>```

I have downloaded the source Code of Ionic.zip library and I see that for every Add*() function like AddEntry(), AddFile() etc. they add item into Dictionary called _entry.

This dictionary does not get cleared when we call Save() or Dispose() methods on ZipFile object.

I feel this is the root cause of OutOfMemoryException.

How do I overcome this issue? Is there any other way to achieve the same result without running into OutOfMemoryException? Am I missing something?
I am open to using other open Source libraries too.

答:
The dictionary holding the internal structure of the archvie shouldn't be a problem.
Assuming your entry 'path' is a string of about 50 bytes - even 1000000 entries should amount to about 50 Mb (a lot - but nowhere near the limit of 2 Gb) - while I haven't bothered checking the size of the ZipEntry - I also doubt it would be large enough (would need to be around 2kb each)

I also think that your expectation for this Entry dictionary to be cleared is wrong. Since this is the informational structure of the contents of the zip file - you need it to hold all the entries.

From this point on I am going to assume that the posted code:

```<code>byte[] data = Encoding.ASCII.GetBytes("rama");
</code>```

Is a place holder for actual file data in bytes (since for 1M x 4 bytes - should be under 4Mb)

The most likely issue here that the declared byte[] data remains in memory  untill the entire ZipFile is disposed.
It makes sense to keep this array untill the data is saved.
The simplest way to work around this is to wrap the ZipFile in using re-opening and closing for every file you want to add.

```<code>        var zipFileName = "E:\\test1.zip";
        for (int i = 0; i < 1000000; ++i)
        {
            using (ZipFile zf = new ZipFile(zipFileName))
            {

                byte[] data = File.ReadAllBytes(file2Zip);

                ZipEntry entry = zf.AddEntry(@"myFolder1/test1/myhtml111.html" + i.ToString(), data);

                zf.Save();
            }

        }
</code>```

This approach might seem wasteful if you are saving a lot of small files, since you are using byte[] directly it would be quite simple to implement a buffering mechanism.

While it is true that it's possible to side step this issue by compiling to 64-bit, unless you are really just barelly going over the 2Gb limit, this would create a very memory hungry app.

Body:
I am facing an issue of OutofMemoryException when I add large number of files in ZipFile. The sample code is as below:

ZipFile file = new ZipFile("E:\\test1.zip");
file.UseZip64WhenSaving = Zip64Option.AsNecessary;
file.ParallelDeflateThreshold = -1;
for (Int64 i = 0; i < 1000000; i++)
{
   file.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
   byte[] data = Encoding.ASCII.GetBytes("rama");
   ZipEntry entry = file.AddEntry(@"myFolder1/test1/myhtml111.html" + i.ToString(), data);
}
file.Save();

I have downloaded the source Code of Ionic.zip library and I see that for every Add*() function like AddEntry(), AddFile() etc. they add item into Dictionary called _entry.

This dictionary does not get cleared when we call Save() or Dispose() methods on ZipFile object.

I feel this is the root cause of OutOfMemoryException.

How do I overcome this issue? Is there any other way to achieve the same result without running into OutOfMemoryException? Am I missing something?
I am open to using other open Source libraries too.

Body:
The dictionary holding the internal structure of the archvie shouldn't be a problem.
Assuming your entry 'path' is a string of about 50 bytes - even 1000000 entries should amount to about 50 Mb (a lot - but nowhere near the limit of 2 Gb) - while I haven't bothered checking the size of the ZipEntry - I also doubt it would be large enough (would need to be around 2kb each)

I also think that your expectation for this Entry dictionary to be cleared is wrong. Since this is the informational structure of the contents of the zip file - you need it to hold all the entries.

From this point on I am going to assume that the posted code:

byte[] data = Encoding.ASCII.GetBytes("rama");

Is a place holder for actual file data in bytes (since for 1M x 4 bytes - should be under 4Mb)

The most likely issue here that the declared byte[] data remains in memory  untill the entire ZipFile is disposed.
It makes sense to keep this array untill the data is saved.
The simplest way to work around this is to wrap the ZipFile in using re-opening and closing for every file you want to add.

        var zipFileName = "E:\\test1.zip";
        for (int i = 0; i < 1000000; ++i)
        {
            using (ZipFile zf = new ZipFile(zipFileName))
            {

                byte[] data = File.ReadAllBytes(file2Zip);

                ZipEntry entry = zf.AddEntry(@"myFolder1/test1/myhtml111.html" + i.ToString(), data);

                zf.Save();
            }

        }

This approach might seem wasteful if you are saving a lot of small files, since you are using byte[] directly it would be quite simple to implement a buffering mechanism.

While it is true that it's possible to side step this issue by compiling to 64-bit, unless you are really just barelly going over the 2Gb limit, this would create a very memory hungry app.


问:
The Relative Layout in the Android APP is overlapping my fields
The attached is my code for the Relative Layout based Image display, The Profile name along with the username - displays the username, Email id - displays the email id, Change password and Signout. But the Field values are overlapping in the username and Email. Can any one suggest a better idea that the values do not overlap.

Please find the code as below:

```<code><android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.LinearLayoutCompat
        android:id="@+id/profile"
        android:background="@color/grey_100"
        app:layout_aspectRatio="300%"
        app:layout_widthPercent="100%">
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/img_avatar"
                android:layout_gravity="center"
                android:layout_width="75dp"
                android:layout_height="75dp"
                android:layout_marginTop="5dp"
                android:src="@drawable/default_avata"
                android:background="#00000000"/>
            <TextView
                android:layout_gravity="center"
                android:textSize="20sp"
                android:textColor="@android:color/black"
                android:layout_marginTop="15dp"
                android:id="@+id/tv_username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
    </android.support.v7.widget.LinearLayoutCompat>

    <android.support.v7.widget.RecyclerView
        android:layout_below="@+id/profile"
        android:id="@+id/info_recycler_view"
        android:layout_marginTop="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.percent.PercentRelativeLayout>
</code>```

Please find the screenshot attached:

答:
change your item_row used in recyclerView

android:layout_height="match_parent"

Body:
The attached is my code for the Relative Layout based Image display, The Profile name along with the username - displays the username, Email id - displays the email id, Change password and Signout. But the Field values are overlapping in the username and Email. Can any one suggest a better idea that the values do not overlap.

Please find the code as below:

<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.LinearLayoutCompat
        android:id="@+id/profile"
        android:background="@color/grey_100"
        app:layout_aspectRatio="300%"
        app:layout_widthPercent="100%">
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/img_avatar"
                android:layout_gravity="center"
                android:layout_width="75dp"
                android:layout_height="75dp"
                android:layout_marginTop="5dp"
                android:src="@drawable/default_avata"
                android:background="#00000000"/>
            <TextView
                android:layout_gravity="center"
                android:textSize="20sp"
                android:textColor="@android:color/black"
                android:layout_marginTop="15dp"
                android:id="@+id/tv_username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
    </android.support.v7.widget.LinearLayoutCompat>

    <android.support.v7.widget.RecyclerView
        android:layout_below="@+id/profile"
        android:id="@+id/info_recycler_view"
        android:layout_marginTop="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.percent.PercentRelativeLayout>

Please find the screenshot attached:


问:
WCF-BasicHttp NTLM ESB guidance
I am trying to access an asmx service located on IIS, the asmx is using integradted security
I am trying to call it with wcf-basichttp adapter configured inside ESB guidance 1.0

The error i am getting is :

The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM'

I tryed to set in the endpoint config:

```<code>UserName=DOMAIN\Username&Password=Password&TransportClientCredentialType=NTLM
</code>```

Any idea would be appriciated

答: I would take a look at this similar thread.</p>

Title: WCF-BasicHttp NTLM ESB guidance

Body:
I am trying to access an asmx service located on IIS, the asmx is using integradted security
I am trying to call it with wcf-basichttp adapter configured inside ESB guidance 1.0

The error i am getting is :

The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM'

I tryed to set in the endpoint config:

UserName=DOMAIN\Username&Password=Password&TransportClientCredentialType=NTLM

Any idea would be appriciated

ContentLicense: CC BY-SA 2.5


问:
Create stream with FFmpeg from different ip
I need to create HLS stream with FFmpeg from different ip. It's like --bind-address in wget command. i have 2 network interface i need choose which i want and process command in terminal.

答:
Finally i use http_proxy.

http_proxy
set HTTP proxy to tunnel through e.g. http://example.com:1234

http://ffmpeg.org/ffmpeg-all.html


问:
"Command not found" piping a variable to cut when output stored in a variable
In a bash script I am using a variable to hold a path like this:

```<code>MY_DIR=/just/a/string/to/my/path
</code>```

And I want to remove the last two parts of it so it looks like this:

```<code>/just/a/string
</code>```

I am using 'cut' to do it, like this:

```<code>echo $MY_DIR | cut -d'/' -f-4
</code>```

The output is what I expect. Fine.
But I want to store in an other variable, like this:

```<code>MY_DIR2=$($MY_DIR | cut -d'/' -f-4)
</code>```

When I execute the script I get the error:

```<code>... /just/a/string/to/my/path: No such file or directory
</code>```

Why is the direct output with echo working, but storing the output in a variable is not?

答:
You need to pass an input string to the shell command using a pipeline in which case cut or any standard shell commands, reads from stdin and acts on it. Some of the ways you can do this are use a pipe-line

```<code>dir2=$(echo "$MY_DIR" | cut -d'/' -f-4)
</code>```

(or) use a here-string which is a shell built-in instead of launching a external shell process

```<code>dir2=$(cut -d'/' -f-4 <<< "$MY_DIR")
</code>```

Body:
In a bash script I am using a variable to hold a path like this:

MY_DIR=/just/a/string/to/my/path

And I want to remove the last two parts of it so it looks like this:

/just/a/string

I am using 'cut' to do it, like this:

echo $MY_DIR | cut -d'/' -f-4

The output is what I expect. Fine.
But I want to store in an other variable, like this:

MY_DIR2=$($MY_DIR | cut -d'/' -f-4)

When I execute the script I get the error:

... /just/a/string/to/my/path: No such file or directory

Why is the direct output with echo working, but storing the output in a variable is not?

Body:
You need to pass an input string to the shell command using a pipeline in which case cut or any standard shell commands, reads from stdin and acts on it. Some of the ways you can do this are use a pipe-line

dir2=$(echo "$MY_DIR" | cut -d'/' -f-4)

(or) use a here-string which is a shell built-in instead of launching a external shell process

dir2=$(cut -d'/' -f-4 <<< "$MY_DIR")


问:
Hero Unit Styles not being applied
I am starting a conversation of a psd to html using bootstrap but my hero unit is not getting its default style

        <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/cerulean/bootstrap.css" >

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

We build well desgined websites

Class aptent taciti sociosqu ad litora torquent per conubia nostra.

          Get Started

        Learn More

    ```

You will see here in the image its getting the style of the images ok but ntot the hero unit does anybody have an idea as to why?.

答:
If you are uisng twitter bootstrap 3 you should use jumbotron instead of hero-unit

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

https://getbootstrap.com/docs/3.3/css/

https://getbootstrap.com/docs/3.3/components/#jumbotron

Title: Hero Unit Styles not being applied

Body:
I am starting a conversation of a psd to html using bootstrap but my hero unit is not getting its default style

        <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/cerulean/bootstrap.css" >

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

We build well desgined websites

Class aptent taciti sociosqu ad litora torquent per conubia nostra.

          Get Started

        Learn More

You will see here in the image its getting the style of the images ok but ntot the hero unit does anybody have an idea as to why?.

Body:
If you are uisng twitter bootstrap 3 you should use jumbotron instead of hero-unit

  <div class="jumbotron">

https://getbootstrap.com/docs/3.3/css/

https://getbootstrap.com/docs/3.3/components/#jumbotron


问:
Mapping two tables without relationship and without a loop
I have a complex problem to solve without using a loop. With loop it seems pretty straight forward. But it's proving to be very tricky when trying to think in Set based operation..

Details

Following is a PaymentPlan table where I stored every customers payment plans.
For example: how much customer is going to pay and on which date.

```<code>PlanId |PaymentAmount   |CustomerId |StartDate
100    |200.00          |100        |2017-01-01
200    |100.00          |100        |2017-02-01
300    |100.00          |100        |2017-03-01
400    |200.00          |100        |2017-04-01
</code>```

As you can see in table above it contains all the payment plans for customerId 100.

Next I have a table called Transaction. This table stored the transactions for the above payment plans.

```<code>TransId |CustomerId |Amount |TransactionDate |IsReversed
100     |100        |100.00 |2017-01-01      |0
200     |100        |100.00 |2017-01-02      |0
300     |100        |60.00  |2017-01-04      |0
400     |100        |40.00  |2017-02-02      |0
500     |100        |300.00 |2017-04-02      |0
600     |100        |200.00 |2017-04-10      |1
</code>```

The problem is that there is no relationship between PaymentPlan and Transaction Table and we cannot create one it's too complex and the system is monolithic.

I am trying create a new table called TransPaymentPlanMapping
that will store the mapping between the two tables in following format.
Creating mapping using a loop isn't hard but performance wont be good. I am having trouble coming up with a set based solution.

```<code>CustomerId  |transId    |PlanId |RunningPaidAmount  |transDateTime  |IsReversed
100         |100        |100    |100                |2017-01-01     |0
100         |200        |100    |200                |2017-01-02     |0
100         |300        |200    |60                 |2017-01-04     |0
100         |400        |200    |100                |2017-02-02     |0
100         |500        |300    |100                |2017-04-02     |0
100         |500        |400    |200                |2017-04-02     |0
100         |600        |400    |-200               |2017-04-10     |1
</code>```

Here is the breakdown how the mapping is done.

On 2017-01-01 customer pays $100 which results in TransId: 100
and this transId gets allocated planId 100. Why? Because this is
the plan which is the earliest.

On 2017-01-02 customer makes another payment of $100 generates TransId
200 which again gets allocated to planId 100. Why? because it was
partially paid in step 1. Total amount for planId 100 is $200.

On 2017-01-04 customer pays $60 and generates transId: 300 which is allocated to planId: 200 because this pay payment plan is the next in line.

On 2017-02-02 customer pays $40 amount left for planId: 200 for this payment transId: 400 is generated and mapped to planId: 200.

Customer was running late on his payment for planId: 300 and 400  On 2017-04-02 he/she decides to pay $300 which will cover both planId: 300 and 400. This payment generate 1 transId: 500. But in the mapping table this event create two entries for planId 300 and 400.

Final step! on 2017-04-10 customers card declines for the payment he made on 2017-04-02 it only declines for $200. This resulted in a reversal transaction in transaction table. This transaction is then mapped to the most recent entry in the mapping table. As show in mapping table, planId:400 is now -200.

Following is the script to crate the PaymentPlan and transaction table.

```<code>CREATE TABLE #PaymentPlan(PlanId        INT ,
                          PaymentAmount  NUMERIC(8,2),
                          CustomerId     INT,
                          StartDate     DATETIME)
INSERT #PaymentPlan(
        PlanId ,
        PaymentAmount ,
        CustomerId ,
        StartDate )
VALUES  ( 100,  200.00, 100, '2017-01-01'),
        ( 200,  100.00, 100, '2017-02-01'),
        ( 300,  100.00, 100, '2017-03-01'),
        ( 400,  200.00, 100, '2017-04-01')

CREATE TABLE #transaction(TransId         INT,
                          CustomerId      INT,
                          Amount          NUMERIC(8,2),
                          TransactionDate DATETIME,
                          IsReversed BIT)
INSERT #transaction(
       TransId ,
       CustomerId ,
       Amount ,
       TransactionDate ,
       IsReversed)
VALUES  (100,100,100.00,'2017-01-01',0),
        (200,100,100.00,'2017-01-02',0),
        (300,100,60.00 ,'2017-01-04',0),
        (400,100,40.00, '2017-02-02',0),
        (500,100,300.00,'2017-04-02',0),
        (600,100,200.00,'2017-04-10',1)

SELECT * FROM #PaymentPlan ORDER BY StartDate
SELECT * FROM #transaction ORDER BY TransactionDate
</code>```

Here is a SQL fiddle

Really appreciate any help I can get.

答:
It's possible to present amounts in the both tables as consecutive ranges and then find overlapping ones. The next snippet could be a base for the more elaborated version.</p>

```<code>CREATE TABLE #PaymentPlan(PlanId        INT,
                          PaymentAmount NUMERIC(8, 2),
                          CustomerId    INT,
                          StartDate     DATETIME);
INSERT #PaymentPlan(
        PlanId,
        PaymentAmount,
        CustomerId,
        StartDate)
VALUES ( 100,  200.00, 100, '2017-01-01'),
       ( 200,  100.00, 100, '2017-02-01'),
       ( 300,  100.00, 100, '2017-03-01'),
       ( 400,  200.00, 100, '2017-04-01');
CREATE TABLE #transaction(TransId         INT,
                          CustomerId      INT,
                          Amount          NUMERIC(8,2),
                          TransactionDate DATETIME,
                          IsReversed      BIT);
INSERT #transaction(
       TransId,
       CustomerId,
       Amount,
       TransactionDate,
       IsReversed)
VALUES (100,100,100.00,'2017-01-01',0),
       (200,100,100.00,'2017-01-02',0),
       (300,100,60.00 ,'2017-01-04',0),
       (400,100,40.00, '2017-02-02',0),
       (500,100,200.00,'2017-04-02',0),
       (600,100,300.00,'2017-04-10',1);
WITH
  p AS (
    SELECT *,
      SUM(PaymentAmount) OVER(PARTITION BY CustomerId ORDER BY StartDate) - PaymentAmount LeftBound,
      SUM(PaymentAmount) OVER(PARTITION BY CustomerId ORDER BY StartDate) RightBound
    FROM #PaymentPlan
  ),
  t AS (
    SELECT *,
      SUM(Amount) OVER(PARTITION BY CustomerId ORDER BY TransactionDate) - Amount LeftBound,
      SUM(Amount) OVER(PARTITION BY CustomerId ORDER BY TransactionDate) RightBound
    FROM #transaction
  )
SELECT
  t.CustomerId, t.TransId, p.PlanId,
  p.LeftBound PlanLeftBound, p.RightBound PlanRightBound,
  t.LeftBound TransLeftBound, t.RightBound TransRightBound,
  t.TransactionDate transDateTime, t.IsReversed
FROM p JOIN t
  ON p.CustomerId = t.CustomerId AND
     p.LeftBound < t.RightBound AND
     p.RightBound > t.LeftBound;
</code>```

Body:
I have a complex problem to solve without using a loop. With loop it seems pretty straight forward. But it's proving to be very tricky when trying to think in Set based operation..

Details

Following is a PaymentPlan table where I stored every customers payment plans.
For example: how much customer is going to pay and on which date.

PlanId |PaymentAmount   |CustomerId |StartDate
100    |200.00          |100        |2017-01-01
200    |100.00          |100        |2017-02-01
300    |100.00          |100        |2017-03-01
400    |200.00          |100        |2017-04-01

As you can see in table above it contains all the payment plans for customerId 100.

Next I have a table called Transaction. This table stored the transactions for the above payment plans.

TransId |CustomerId |Amount |TransactionDate |IsReversed
100     |100        |100.00 |2017-01-01      |0
200     |100        |100.00 |2017-01-02      |0
300     |100        |60.00  |2017-01-04      |0
400     |100        |40.00  |2017-02-02      |0
500     |100        |300.00 |2017-04-02      |0
600     |100        |200.00 |2017-04-10      |1

The problem is that there is no relationship between PaymentPlan and Transaction Table and we cannot create one it's too complex and the system is monolithic.

I am trying create a new table called TransPaymentPlanMapping
that will store the mapping between the two tables in following format.
Creating mapping using a loop isn't hard but performance wont be good. I am having trouble coming up with a set based solution.

CustomerId  |transId    |PlanId |RunningPaidAmount  |transDateTime  |IsReversed
100         |100        |100    |100                |2017-01-01     |0
100         |200        |100    |200                |2017-01-02     |0
100         |300        |200    |60                 |2017-01-04     |0
100         |400        |200    |100                |2017-02-02     |0
100         |500        |300    |100                |2017-04-02     |0
100         |500        |400    |200                |2017-04-02     |0
100         |600        |400    |-200               |2017-04-10     |1

Here is the breakdown how the mapping is done.

On 2017-01-01 customer pays $100 which results in TransId: 100
and this transId gets allocated planId 100. Why? Because this is
the plan which is the earliest.

On 2017-01-02 customer makes another payment of $100 generates TransId
200 which again gets allocated to planId 100. Why? because it was
partially paid in step 1. Total amount for planId 100 is $200.

On 2017-01-04 customer pays $60 and generates transId: 300 which is allocated to planId: 200 because this pay payment plan is the next in line.

On 2017-02-02 customer pays $40 amount left for planId: 200 for this payment transId: 400 is generated and mapped to planId: 200.

Customer was running late on his payment for planId: 300 and 400  On 2017-04-02 he/she decides to pay $300 which will cover both planId: 300 and 400. This payment generate 1 transId: 500. But in the mapping table this event create two entries for planId 300 and 400.

Final step! on 2017-04-10 customers card declines for the payment he made on 2017-04-02 it only declines for $200. This resulted in a reversal transaction in transaction table. This transaction is then mapped to the most recent entry in the mapping table. As show in mapping table, planId:400 is now -200.

Following is the script to crate the PaymentPlan and transaction table.

CREATE TABLE #PaymentPlan(PlanId        INT ,
                          PaymentAmount  NUMERIC(8,2),
                          CustomerId     INT,
                          StartDate     DATETIME)
INSERT #PaymentPlan(
        PlanId ,
        PaymentAmount ,
        CustomerId ,
        StartDate )
VALUES  ( 100,  200.00, 100, '2017-01-01'),
        ( 200,  100.00, 100, '2017-02-01'),
        ( 300,  100.00, 100, '2017-03-01'),
        ( 400,  200.00, 100, '2017-04-01')

CREATE TABLE #transaction(TransId         INT,
                          CustomerId      INT,
                          Amount          NUMERIC(8,2),
                          TransactionDate DATETIME,
                          IsReversed BIT)
INSERT #transaction(
       TransId ,
       CustomerId ,
       Amount ,
       TransactionDate ,
       IsReversed)
VALUES  (100,100,100.00,'2017-01-01',0),
        (200,100,100.00,'2017-01-02',0),
        (300,100,60.00 ,'2017-01-04',0),
        (400,100,40.00, '2017-02-02',0),
        (500,100,300.00,'2017-04-02',0),
        (600,100,200.00,'2017-04-10',1)

SELECT * FROM #PaymentPlan ORDER BY StartDate
SELECT * FROM #transaction ORDER BY TransactionDate

Here is a SQL fiddle

Really appreciate any help I can get.

Body:
It's possible to present amounts in the both tables as consecutive ranges and then find overlapping ones. The next snippet could be a base for the more elaborated version.

CREATE TABLE #PaymentPlan(PlanId        INT,
                          PaymentAmount NUMERIC(8, 2),
                          CustomerId    INT,
                          StartDate     DATETIME);
INSERT #PaymentPlan(
        PlanId,
        PaymentAmount,
        CustomerId,
        StartDate)
VALUES ( 100,  200.00, 100, '2017-01-01'),
       ( 200,  100.00, 100, '2017-02-01'),
       ( 300,  100.00, 100, '2017-03-01'),
       ( 400,  200.00, 100, '2017-04-01');
CREATE TABLE #transaction(TransId         INT,
                          CustomerId      INT,
                          Amount          NUMERIC(8,2),
                          TransactionDate DATETIME,
                          IsReversed      BIT);
INSERT #transaction(
       TransId,
       CustomerId,
       Amount,
       TransactionDate,
       IsReversed)
VALUES (100,100,100.00,'2017-01-01',0),
       (200,100,100.00,'2017-01-02',0),
       (300,100,60.00 ,'2017-01-04',0),
       (400,100,40.00, '2017-02-02',0),
       (500,100,200.00,'2017-04-02',0),
       (600,100,300.00,'2017-04-10',1);
WITH
  p AS (
    SELECT *,
      SUM(PaymentAmount) OVER(PARTITION BY CustomerId ORDER BY StartDate) - PaymentAmount LeftBound,
      SUM(PaymentAmount) OVER(PARTITION BY CustomerId ORDER BY StartDate) RightBound
    FROM #PaymentPlan
  ),
  t AS (
    SELECT *,
      SUM(Amount) OVER(PARTITION BY CustomerId ORDER BY TransactionDate) - Amount LeftBound,
      SUM(Amount) OVER(PARTITION BY CustomerId ORDER BY TransactionDate) RightBound
    FROM #transaction
  )
SELECT
  t.CustomerId, t.TransId, p.PlanId,
  p.LeftBound PlanLeftBound, p.RightBound PlanRightBound,
  t.LeftBound TransLeftBound, t.RightBound TransRightBound,
  t.TransactionDate transDateTime, t.IsReversed
FROM p JOIN t
  ON p.CustomerId = t.CustomerId AND
     p.LeftBound < t.RightBound AND
     p.RightBound > t.LeftBound;


问:
Input Layout toggle hintText color change
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

```<code>  <style name="labelcolor" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">#868686</item>
    <item name="android:textSize">16sp</item>
    <item name="android:paddingTop">5sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">#0ea3ff</item>
    <item name="colorControlNormal">#0ea3ffr</item>
    <item name="colorControlActivated">#0ea3ff</item>
</style>
</code>```

please help me how can i solve this issues.

答:
Change TextInputLayout Lebel Color Dynamicaly in on Focus change of edittext and pass color according work for me.

```<code> public static void textInoutLayoutColor(TextInputLayout textInputLayout, @ColorInt int color) {

    try {
        Field fDefaultTextColor = TextInputLayout.class.getDeclaredField("mDefaultTextColor");
        fDefaultTextColor.setAccessible(true);
        fDefaultTextColor.set(textInputLayout, new ColorStateList(new int[][]{{0}}, new int[]{ color }));

        Field fFocusedTextColor = TextInputLayout.class.getDeclaredField("mFocusedTextColor");
        fFocusedTextColor.setAccessible(true);
        fFocusedTextColor.set(textInputLayout, new ColorStateList(new int[][]{{0}}, new int[]{ color }));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

and change the color like this.

```<code>input_layout= (TextInputLayout) findViewById(R.id.input_layout);
   etuser_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasfocus) {
            if(hasfocus){
                textInoutLayoutColor(input_layout,getResources().getColor(R.color.bullet_color));
            }
            else
            {
                if(etuser_name.getText().toString().trim().length()>0) {
                    textInoutLayoutColor(input_layout,getResources().getColor(R.color.bullet_color));;
                }
                else
                {
                    textInoutLayoutColor(input_layout,getResources().getColor(R.color.hint_grey));
                }
            }
        }
    });
</code>```

Body:
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

please help me how can i solve this issues.

Body:
Change TextInputLayout Lebel Color Dynamicaly in on Focus change of edittext and pass color according work for me.

 public static void textInoutLayoutColor(TextInputLayout textInputLayout, @ColorInt int color) {

    try {
        Field fDefaultTextColor = TextInputLayout.class.getDeclaredField("mDefaultTextColor");
        fDefaultTextColor.setAccessible(true);
        fDefaultTextColor.set(textInputLayout, new ColorStateList(new int[][]{{0}}, new int[]{ color }));

        Field fFocusedTextColor = TextInputLayout.class.getDeclaredField("mFocusedTextColor");
        fFocusedTextColor.setAccessible(true);
        fFocusedTextColor.set(textInputLayout, new ColorStateList(new int[][]{{0}}, new int[]{ color }));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

and change the color like this.

input_layout= (TextInputLayout) findViewById(R.id.input_layout);
   etuser_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasfocus) {
            if(hasfocus){
                textInoutLayoutColor(input_layout,getResources().getColor(R.color.bullet_color));
            }
            else
            {
                if(etuser_name.getText().toString().trim().length()>0) {
                    textInoutLayoutColor(input_layout,getResources().getColor(R.color.bullet_color));;
                }
                else
                {
                    textInoutLayoutColor(input_layout,getResources().getColor(R.color.hint_grey));
                }
            }
        }
    });


问:
Exploded Struct in Spark
I have DataFrame with following schema:

```<code> |-- data: struct (nullable = true)
 |    |-- asin: string (nullable = true)
 |    |-- customerId: long (nullable = true)
 |    |-- eventTime: long (nullable = true)
 |    |-- marketplaceId: long (nullable = true)
 |    |-- rating: long (nullable = true)
 |    |-- region: string (nullable = true)
 |    |-- type: string (nullable = true)
 |-- uploadedDate: long (nullable = true)
</code>```

I want to explode the struct such that all elements like asin, customerId, eventTime become the columns in DataFrame. I tried explode function but it works on Array not on struct type. Is it possible to convert the able data frame to below dataframe:

```<code>     |-- asin: string (nullable = true)
     |-- customerId: long (nullable = true)
     |-- eventTime: long (nullable = true)
     |-- marketplaceId: long (nullable = true)
     |-- rating: long (nullable = true)
     |-- region: string (nullable = true)
     |-- type: string (nullable = true)
     |-- uploadedDate: long (nullable = true)
</code>```

答:
It's quite simple:

```<code>val newDF = df.select("uploadedDate", "data.*");
</code>```

You tell to select uploadedDate and then all subelements of field data

Example:

```<code>scala> case class A(a: Int, b: Double)
scala> val df = Seq((A(1, 1.0), "1"), (A(2, 2.0), "2")).toDF("data", "uploadedDate")
scala> val newDF = df.select("uploadedDate", "data.*")
scala> newDF.show()
+------------+---+---+
|uploadedDate|  a|  b|
+------------+---+---+
|           1|  1|1.0|
|           2|  2|2.0|
+------------+---+---+

scala> newDF.printSchema()
root
 |-- uploadedDate: string (nullable = true)
 |-- a: integer (nullable = true)
 |-- b: double (nullable = true)
</code>```

Title: Exploded Struct in Spark

Body:
I have DataFrame with following schema:

 |-- data: struct (nullable = true)
 |    |-- asin: string (nullable = true)
 |    |-- customerId: long (nullable = true)
 |    |-- eventTime: long (nullable = true)
 |    |-- marketplaceId: long (nullable = true)
 |    |-- rating: long (nullable = true)
 |    |-- region: string (nullable = true)
 |    |-- type: string (nullable = true)
 |-- uploadedDate: long (nullable = true)

I want to explode the struct such that all elements like asin, customerId, eventTime become the columns in DataFrame. I tried explode function but it works on Array not on struct type. Is it possible to convert the able data frame to below dataframe:

     |-- asin: string (nullable = true)
     |-- customerId: long (nullable = true)
     |-- eventTime: long (nullable = true)
     |-- marketplaceId: long (nullable = true)
     |-- rating: long (nullable = true)
     |-- region: string (nullable = true)
     |-- type: string (nullable = true)
     |-- uploadedDate: long (nullable = true)

Body:
It's quite simple:

val newDF = df.select("uploadedDate", "data.*");

You tell to select uploadedDate and then all subelements of field data

Example:

scala> case class A(a: Int, b: Double)
scala> val df = Seq((A(1, 1.0), "1"), (A(2, 2.0), "2")).toDF("data", "uploadedDate")
scala> val newDF = df.select("uploadedDate", "data.*")
scala> newDF.show()
+------------+---+---+
|uploadedDate|  a|  b|
+------------+---+---+
|           1|  1|1.0|
|           2|  2|2.0|
+------------+---+---+

scala> newDF.printSchema()
root
 |-- uploadedDate: string (nullable = true)
 |-- a: integer (nullable = true)
 |-- b: double (nullable = true)


问:
Spawning a docker command yields an empty result
I have the following Go code, where I try to spawn docker command and get its output:

```<code>package main

import "fmt"
import "os/exec"

func main() {
    cmd := exec.Command("docker")
    cmdOutput, err := cmd.Output()
    if (err != nil) {
        panic(err)
    }
    fmt.Println(string(cmdOutput))
}
</code>```

But when I run this code as a result I get an empty string, which is stange since I get an output when I run docker command directly in a command line.

Moreover, this same code yields results just fine if I spawn other commands with it, for example ls.

What may be wrong here?

答: try using cmd.CombinedOutput()</p>

Body:
I have the following Go code, where I try to spawn docker command and get its output:

package main

import "fmt"
import "os/exec"

func main() {
    cmd := exec.Command("docker")
    cmdOutput, err := cmd.Output()
    if (err != nil) {
        panic(err)
    }
    fmt.Println(string(cmdOutput))
}

But when I run this code as a result I get an empty string, which is stange since I get an output when I run docker command directly in a command line.

Moreover, this same code yields results just fine if I spawn other commands with it, for example ls.

What may be wrong here?

Body: try using cmd.CombinedOutput()


问:
How to pass null value in RESTful way (GET filtering)? As an empty value or as 'null'?
I want to retrieve all installations that weren't removed yet.

Should I do this like that:

```<code>/installations?removedOn=
</code>```

or

```<code>/installations?removedOn=null
</code>```

or maybe in some other way?

```<code>/installations?removed=false
</code>```

Despite the fact, that something tells me that removed=false looks better, removedOn` may be more practical because later I could query installations that are removed in particular timeframe using the same param.

答:
REST doesn't care what spelling you use for your URI.

/installationsThatArentRemovedYet

/installations?neverRemoved

/f784d74e-b8bf-4832-9297-03816e5b4936

Any of these are fine, as far as REST is concerned.

It follows that these are also fine

/installations?removedOn=

/installations?removedOn=null

/installations?removed=false

One important thing to keep in mind is that the URI should still work even if your underlying implementation changes.  So you want stable semantics, with your controller having the responsibility of mapping those semantics to your current implementation.

Body:
I want to retrieve all installations that weren't removed yet.

Should I do this like that:

/installations?removedOn=

or

/installations?removedOn=null

or maybe in some other way?

/installations?removed=false

Despite the fact, that something tells me that removed=false looks better, removedOn` may be more practical because later I could query installations that are removed in particular timeframe using the same param.

ContentLicense: CC BY-SA 4.0


问:
ruby - rails - Dealing with a Boolean False- It outputs nothing
I have record in my db that is a boolean field (true/false).

The field is archived. When archived is true all these work great to output true:

```<code>  Rails.logger.info @commentable.archived
  Rails.logger.info @commentable.archived?
  Rails.logger.info !!@commentable.archived?
</code>```

BUT when the archived is false, it outputs nothing for either of the above. How can I get an output of false when the field is FALSE?

Thanks

答:
false.to_s == 'false', but Rails.logger.info seems to do the wrong thing here:

```<code>> puts true
true
> puts false
false
> Rails.logger.info true
true
> Rails.logger.info false
</code>```

Body:
I have record in my db that is a boolean field (true/false).

The field is archived. When archived is true all these work great to output true:

  Rails.logger.info @commentable.archived
  Rails.logger.info @commentable.archived?
  Rails.logger.info !!@commentable.archived?

BUT when the archived is false, it outputs nothing for either of the above. How can I get an output of false when the field is FALSE?

Thanks

Body:
false.to_s == 'false', but Rails.logger.info seems to do the wrong thing here:

> puts true
true
> puts false
false
> Rails.logger.info true
true
> Rails.logger.info false


问:
How can I access a protected property of a Model located in a package (vendor folders)
The model is in the vendor folder (normal package). I need to access an attribute of the model which is protected.
NOTE: Not possible of making a getter in the model class.</p>

答:
To access a class property that is marked as protected you need to extend that class. Note that if that class is marked as final, you won't be able to do it.

Example:

```<code>class Parent {

    protected $property;

}

class Child extends Parent {

    public function getProperty()
    {
        return $this->property;
    }

}
</code>```

Body:
To access a class property that is marked as protected you need to extend that class. Note that if that class is marked as final, you won't be able to do it.

Example:

class Parent {

    protected $property;

}

class Child extends Parent {

    public function getProperty()
    {
        return $this->property;
    }

}


问:
Trying to list declared XML-namespaces
We have a number of applications accessing our APIs by providing XML data. At a certain point we decided to use xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" for incoming NULL-values to be able to distinguish empty values from NULL values in a uniform way.

Because the transition to xsi:nil is still ongoing, I want to be able to tell whether or not the xsi-namespace is declared as an indicator of whether or not the calling application would use xsi:nil="true" for NULL-values.

I tried

DECLARE @SomeXML xml = N'<ROOT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><blubb><blah xsi:nil="true"/></blubb></ROOT>';

SELECT  @SomeXML.exist('declare namespace xsi="http://www.w3.org/2001/XMLSchema-instance"; //xsi:*, //@xsi:*');
```

<p>but this will only work if the namespace is actually referred to in the XML-document. A query like <code>//@xmlns:*</code> leads to the error</p>

<pre class="lang-none prettyprint-override"><code>Msg 2229, Level 16, State 1, Line 6
XQuery [query()]: The name "xmlns" does not denote a namespace.
</code>```

while a query for //@*:xsi just returns nothing at all.

Is there any way to determine the declared XML-namespaces in SQL Server 2016?

答:
I learned from this thread, that there is a rather old way to enumerate namespaces utilizing OPENXML:

```<code>DECLARE @SomeXML xml = N'<ROOT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema-instance"><blubb xmlns:xsiu="http://www.w3.org/2001/XMLSchema-instance"><blah xsi:nil="true"/></blubb></ROOT>';

DECLARE @hDoc int;

EXEC sys.sp_xml_preparedocument
    @hDoc OUTPUT,
    @SomeXML;

IF EXISTS ( SELECT  namespace = NULLIF(XmlnsAttribute.localname, 'xmlns'),
                    namespace_uri = XmlnsValue.text
            FROM    OPENXML( @hDoc, '//*' ) XmlnsAttribute
            INNER JOIN OPENXML( @hDoc, '//*' ) XmlnsValue ON XmlnsValue.parentid = XmlnsAttribute.id
            WHERE   XmlnsAttribute.prefix = 'xmlns'
                    AND XmlnsValue.nodetype = 3 /*text*/
                    AND CAST(XmlnsValue.text AS nvarchar(MAX)) = N'http://www.w3.org/2001/XMLSchema-instance' )
    PRINT 'Has http://www.w3.org/2001/XMLSchema-instance namespace';
ELSE
    PRINT 'Does not have http://www.w3.org/2001/XMLSchema-instance namespace';

EXEC sys.sp_xml_removedocument
    @hDoc;
</code>```

I am uncertain how elegant this is, as text column is of type ntext, and the calls to sys.sp_xml_preparedocument and sys.sp_xml_removedocument mean, that you need to pay a bit more attention, when you include this into other queries. Probably the worst draw-back is, that you need to do this RBAR.

Still this is a solution without casting xml to varchar, so it should be difficult to spoof.

Listing all namespaces:

```<code>DECLARE @SomeXML xml = N'<ROOT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema-instance"><blubb xmlns:xsiu="http://www.w3.org/2001/XMLSchema-instance"><blah xsi:nil="true"/></blubb></ROOT>';

DECLARE @hDoc int;

EXEC sys.sp_xml_preparedocument
    @hDoc OUTPUT,
    @SomeXML;

-- All registered namespaces
WITH    XmlNodes
          AS (SELECT    OX.id,
                        OX.parentid,
                        OX.nodetype,
                        OX.localname,
                        OX.prefix,
                        OX.text
              FROM      OPENXML( @hDoc, '//*' ) OX)
    SELECT  namespace = NULLIF(XmlnsAttribute.localname, 'xmlns'),
            namespace_uri = XmlnsValue.text
    FROM    XmlNodes XmlnsAttribute
    INNER JOIN XmlNodes XmlnsValue ON XmlnsValue.parentid = XmlnsAttribute.id
    WHERE   XmlnsAttribute.prefix = 'xmlns'
            AND XmlnsValue.nodetype = 3
 /*text*/;

-- All registered namespaces with scope
WITH    XmlNodes
          AS (SELECT    OX.id,
                        OX.parentid,
                        OX.nodetype,
                        OX.localname,
                        OX.prefix,
                        OX.text
              FROM      OPENXML( @hDoc, '//*' ) OX),
        XmlNodesWithPath
          AS (SELECT    XN.id,
                        path = CAST(N'/' + ISNULL(XN.prefix + N':', N'') + XN.localname AS nvarchar(MAX))
              FROM      XmlNodes XN
              WHERE     XN.parentid IS NULL
              UNION ALL
              SELECT    XN.id,
                        path = XNWP.path + N'/' + ISNULL(XN.prefix + N':', N'') + XN.localname
              FROM      XmlNodesWithPath XNWP
              INNER JOIN XmlNodes XN ON XN.parentid = XNWP.id
                                        AND XN.nodetype = 1)
    SELECT  scope = Scope.path,
            namespace = NULLIF(XmlnsAttribute.localname, 'xmlns'),
            namespace_uri = XmlnsValue.text
    FROM    XmlNodesWithPath Scope
    INNER JOIN XmlNodes XmlnsAttribute ON XmlnsAttribute.parentid = Scope.id
    INNER JOIN XmlNodes XmlnsValue ON XmlnsValue.parentid = XmlnsAttribute.id
    WHERE   XmlnsAttribute.prefix = 'xmlns'
            AND XmlnsValue.nodetype = 3
 /*text*/;

EXEC sys.sp_xml_removedocument
    @hDoc;
</code>```

Title: Trying to list declared XML-namespaces

Body:
We have a number of applications accessing our APIs by providing XML data. At a certain point we decided to use xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" for incoming NULL-values to be able to distinguish empty values from NULL values in a uniform way.

Because the transition to xsi:nil is still ongoing, I want to be able to tell whether or not the xsi-namespace is declared as an indicator of whether or not the calling application would use xsi:nil="true" for NULL-values.

I tried

DECLARE @SomeXML xml = N'<ROOT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><blubb><blah xsi:nil="true"/></blubb></ROOT>';

SELECT  @SomeXML.exist('declare namespace xsi="http://www.w3.org/2001/XMLSchema-instance"; //xsi:*, //@xsi:*');

but this will only work if the namespace is actually referred to in the XML-document. A query like //@xmlns:* leads to the error

Msg 2229, Level 16, State 1, Line 6
XQuery [query()]: The name "xmlns" does not denote a namespace.

while a query for //@*:xsi just returns nothing at all.

Is there any way to determine the declared XML-namespaces in SQL Server 2016?

Body:
I learned from this thread, that there is a rather old way to enumerate namespaces utilizing OPENXML:

DECLARE @SomeXML xml = N'<ROOT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema-instance"><blubb xmlns:xsiu="http://www.w3.org/2001/XMLSchema-instance"><blah xsi:nil="true"/></blubb></ROOT>';

DECLARE @hDoc int;

EXEC sys.sp_xml_preparedocument
    @hDoc OUTPUT,
    @SomeXML;

IF EXISTS ( SELECT  namespace = NULLIF(XmlnsAttribute.localname, 'xmlns'),
                    namespace_uri = XmlnsValue.text
            FROM    OPENXML( @hDoc, '//*' ) XmlnsAttribute
            INNER JOIN OPENXML( @hDoc, '//*' ) XmlnsValue ON XmlnsValue.parentid = XmlnsAttribute.id
            WHERE   XmlnsAttribute.prefix = 'xmlns'
                    AND XmlnsValue.nodetype = 3 /*text*/
                    AND CAST(XmlnsValue.text AS nvarchar(MAX)) = N'http://www.w3.org/2001/XMLSchema-instance' )
    PRINT 'Has http://www.w3.org/2001/XMLSchema-instance namespace';
ELSE
    PRINT 'Does not have http://www.w3.org/2001/XMLSchema-instance namespace';

EXEC sys.sp_xml_removedocument
    @hDoc;

I am uncertain how elegant this is, as text column is of type ntext, and the calls to sys.sp_xml_preparedocument and sys.sp_xml_removedocument mean, that you need to pay a bit more attention, when you include this into other queries. Probably the worst draw-back is, that you need to do this RBAR.

Still this is a solution without casting xml to varchar, so it should be difficult to spoof.

Listing all namespaces:

DECLARE @SomeXML xml = N'<ROOT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/2001/XMLSchema-instance"><blubb xmlns:xsiu="http://www.w3.org/2001/XMLSchema-instance"><blah xsi:nil="true"/></blubb></ROOT>';

DECLARE @hDoc int;

EXEC sys.sp_xml_preparedocument
    @hDoc OUTPUT,
    @SomeXML;

-- All registered namespaces
WITH    XmlNodes
          AS (SELECT    OX.id,
                        OX.parentid,
                        OX.nodetype,
                        OX.localname,
                        OX.prefix,
                        OX.text
              FROM      OPENXML( @hDoc, '//*' ) OX)
    SELECT  namespace = NULLIF(XmlnsAttribute.localname, 'xmlns'),
            namespace_uri = XmlnsValue.text
    FROM    XmlNodes XmlnsAttribute
    INNER JOIN XmlNodes XmlnsValue ON XmlnsValue.parentid = XmlnsAttribute.id
    WHERE   XmlnsAttribute.prefix = 'xmlns'
            AND XmlnsValue.nodetype = 3
 /*text*/;

-- All registered namespaces with scope
WITH    XmlNodes
          AS (SELECT    OX.id,
                        OX.parentid,
                        OX.nodetype,
                        OX.localname,
                        OX.prefix,
                        OX.text
              FROM      OPENXML( @hDoc, '//*' ) OX),
        XmlNodesWithPath
          AS (SELECT    XN.id,
                        path = CAST(N'/' + ISNULL(XN.prefix + N':', N'') + XN.localname AS nvarchar(MAX))
              FROM      XmlNodes XN
              WHERE     XN.parentid IS NULL
              UNION ALL
              SELECT    XN.id,
                        path = XNWP.path + N'/' + ISNULL(XN.prefix + N':', N'') + XN.localname
              FROM      XmlNodesWithPath XNWP
              INNER JOIN XmlNodes XN ON XN.parentid = XNWP.id
                                        AND XN.nodetype = 1)
    SELECT  scope = Scope.path,
            namespace = NULLIF(XmlnsAttribute.localname, 'xmlns'),
            namespace_uri = XmlnsValue.text
    FROM    XmlNodesWithPath Scope
    INNER JOIN XmlNodes XmlnsAttribute ON XmlnsAttribute.parentid = Scope.id
    INNER JOIN XmlNodes XmlnsValue ON XmlnsValue.parentid = XmlnsAttribute.id
    WHERE   XmlnsAttribute.prefix = 'xmlns'
            AND XmlnsValue.nodetype = 3
 /*text*/;

EXEC sys.sp_xml_removedocument
    @hDoc;


问:
how to get the size of array inside a hashmap in java
I have a new ArrayList inside a HashMap, but i don't know how to calculate the size of ArrayList inside the HashMap

```<code>Map<String, List<fruit>> groupbyregion = new HashMap<>();
for (fruit s : ll) {
    if (!groupbyregion.containsKey(s.getRegionName())) {
        groupbyregion.put(s.getRegionName(), new ArrayList<>());
    }
    groupbyregion.get(s.getRegionName()).add(s);
}
System.out.println("Group by region: " + groupbyregion);
</code>```

答:
You are already using:

```<code>groupbyregion.get(s.getRegionName()).add(s);
</code>```

This calls the add() method of the ArrayList in that map slot.
Thus:

```<code>groupbyregion.get(s.getRegionName()).size();
</code>```

gives you the size.

Beyond that: you want to look here for how to create lists within maps in more elegant (java8) ways.

Body:
I have a new ArrayList inside a HashMap, but i don't know how to calculate the size of ArrayList inside the HashMap

Map<String, List<fruit>> groupbyregion = new HashMap<>();
for (fruit s : ll) {
    if (!groupbyregion.containsKey(s.getRegionName())) {
        groupbyregion.put(s.getRegionName(), new ArrayList<>());
    }
    groupbyregion.get(s.getRegionName()).add(s);
}
System.out.println("Group by region: " + groupbyregion);

Body:
You are already using:

groupbyregion.get(s.getRegionName()).add(s);

This calls the add() method of the ArrayList in that map slot.
Thus:

groupbyregion.get(s.getRegionName()).size();

gives you the size.

Beyond that: you want to look here for how to create lists within maps in more elegant (java8) ways.


问:
AWS ElasticBeanstalk EC2 gives postgresql connection error
When I deploy my app on aws beanstalk using eb deploy it gives an error

```<code>rake aborted!
PG::ConnectionBad: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

.ebextensions/postgres.config:

```<code>packages:
yum:
 postgresql93-devel: []
</code>```

config/database.yml:

```<code>default: &default
adapter: postgresql
encoding: unicode
# For details on connection pooling, see rails configuration guide
# http://guides.rubyonrails.org/configuring.html#database-pooling
pool: 5

production:
<<: *default
database: <%= ENV['RDS_DB_NAME'] %>
username: <%= ENV['RDS_USERNAME'] %>
password: <%= ENV['RDS_PASSWORD'] %>
host: <%= ENV['RDS_HOSTNAME'] %>
port: <%= ENV['RDS_PORT'] %>
</code>```

答:
I had the exact same issue.

The problem is that you have to connect your database to the application through the environment variables.

First you need to create an RDS instance to connect to. This link shows you how: https://aws.amazon.com/getting-started/tutorials/create-connect-postgresql-db/?nc1=h_ls

Then, after the instance is created, you need to go to the RDS Service page, and choose instance in the left menu. Choose the instance you created in the list and proceed to the section called "Connect". Those are the values you put inside those environment variables, with the HOSTNAME value being the endpoint.

Hope it helped, worked for me!

Body:
When I deploy my app on aws beanstalk using eb deploy it gives an error

rake aborted!
PG::ConnectionBad: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

.ebextensions/postgres.config:

packages:
yum:
 postgresql93-devel: []

config/database.yml:

default: &default
adapter: postgresql
encoding: unicode
# For details on connection pooling, see rails configuration guide
# http://guides.rubyonrails.org/configuring.html#database-pooling
pool: 5

production:
<<: *default
database: <%= ENV['RDS_DB_NAME'] %>
username: <%= ENV['RDS_USERNAME'] %>
password: <%= ENV['RDS_PASSWORD'] %>
host: <%= ENV['RDS_HOSTNAME'] %>
port: <%= ENV['RDS_PORT'] %>


问:
how to use --no-data for few tables and full data for few tables in single command mysqldump?
I have scenarios like to back up the few tables structures and other few tables structure + contents.

I read about all the options of mysqldump

It says that --no-data will backup all the tables structures only like

```<code>mysqldump -h localhost -u root -p wp2 --no-data wp_options wp_users > mydatabase_backup.sql
</code>```

but I want the same command to perform the both such as few tables only structures and few tables structure + contents.

Is there any possibility to achieve this?

答:
I had to run two different commands

First one structure only tables mysqldump command

```<code>mysqldump -h localhost -u root -p wp2 --no-data structure_only_table > mydatabase_backup.sql
</code>```

Then executed full table backups and >> helped to merge both files.

```<code>mysqldump -h localhost -u root -p wp2 full_tables >> mydatabase_backup.sql
</code>```

Body:
I have scenarios like to back up the few tables structures and other few tables structure + contents.

I read about all the options of mysqldump

It says that --no-data will backup all the tables structures only like

mysqldump -h localhost -u root -p wp2 --no-data wp_options wp_users > mydatabase_backup.sql

but I want the same command to perform the both such as few tables only structures and few tables structure + contents.

Is there any possibility to achieve this?

Body:
I had to run two different commands

First one structure only tables mysqldump command

mysqldump -h localhost -u root -p wp2 --no-data structure_only_table > mydatabase_backup.sql

Then executed full table backups and >> helped to merge both files.

mysqldump -h localhost -u root -p wp2 full_tables >> mydatabase_backup.sql


问:
Should I avoid Alternative Control Syntax?
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

```<code>x = (y == true) ? "foo" : "bar";
</code>```

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

答:
This is known as a ternary expression.  If the the intent can be expressened clearly and concisely with a ternary operator then I do so.  I usually draw the line and having compound expressions (more than 1 combined with && or ||)

Good:

```<code>var x = (someVar > 42 ) ? ThisFunction() : ThisOtherFunction();
</code>```

Bad:

```<code>var x = (someVar > 42 && anotherVariable.IsSafeForConsumption() && IsNotProcessing ) ? ThisFunction() : ThisOTherFunction();
</code>```

OwnerDisplayName: Chris

Body:
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

x = (y == true) ? "foo" : "bar";

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

Body:
This is known as a ternary expression.  If the the intent can be expressened clearly and concisely with a ternary operator then I do so.  I usually draw the line and having compound expressions (more than 1 combined with && or ||)

Good:

var x = (someVar > 42 ) ? ThisFunction() : ThisOtherFunction();

Bad:

var x = (someVar > 42 && anotherVariable.IsSafeForConsumption() && IsNotProcessing ) ? ThisFunction() : ThisOTherFunction();

OwnerDisplayName: JaredPar


问:
Flask-Admin | How to fix route to the image
I have a question according to image path in Flask.
I have a DB model Image, that contains all necessary info about image, including path - '/animals/sometype/image.jpg'.

I'm using Flask-admin module, and the problem is the wrong path to the image in editing mode.
Here's a code:

```<code>class ImageView(ModelView):
    edit_template = 'image_edit.html'

    def _list_thumbnail(view, context, model, name):
        if not model.path:
            return ''
        return Markup('<img src="%s">' % url_for('static', filename=('images' + model.path)))

column_formatters = {
    'path': _list_thumbnail
}

form_extra_fields = {
    'path': form.ImageUploadField('Image', base_path='static/images', url_relative_path='images/')
}
</code>```

For column formatters path is correct, but for the extra fields is wrong,  resulting in 404 error: http://127.0.0.1:5000/static//animals/birds/the_bird-wallpaper-1366x768.jpg

How can I solve this?
Also, I was thinking about passing an image to the custom edit template, but I don't understand, how to do it in Flask-Admin.

答:
I've found a solution to pass an image to the edit view in Flask-admin without ImageUploadField. The solution is simple, all I need is to pass an image id from DB and use it in Jinja template.

```<code>class ImageView(ModelView):
edit_template = 'image_edit.html'

@expose('/edit/', methods=['GET', 'POST'])
def edit_view(self):
    id = request.args.get('id')
    self._template_args['image'] = db.session.query(Image.path).filter(Image.id == id).first()[0]
    return super(ImageView, self).edit_view()
</code>```

And HTML template:

```<code>{% extends "admin/model/edit.html" %}
{% block body %}
  <img src=/static/images/{{ image }}/>
  {{ super() }}
{% endblock %}
</code>```

Body:
I have a question according to image path in Flask.
I have a DB model Image, that contains all necessary info about image, including path - '/animals/sometype/image.jpg'.

I'm using Flask-admin module, and the problem is the wrong path to the image in editing mode.
Here's a code:

class ImageView(ModelView):
    edit_template = 'image_edit.html'

    def _list_thumbnail(view, context, model, name):
        if not model.path:
            return ''
        return Markup('' % url_for('static', filename=('images' + model.path)))

column_formatters = {
    'path': _list_thumbnail
}

form_extra_fields = {
    'path': form.ImageUploadField('Image', base_path='static/images', url_relative_path='images/')
}

For column formatters path is correct, but for the extra fields is wrong,  resulting in 404 error: http://127.0.0.1:5000/static//animals/birds/the_bird-wallpaper-1366x768.jpg

How can I solve this?
Also, I was thinking about passing an image to the custom edit template, but I don't understand, how to do it in Flask-Admin.

Body:
I've found a solution to pass an image to the edit view in Flask-admin without ImageUploadField. The solution is simple, all I need is to pass an image id from DB and use it in Jinja template.

class ImageView(ModelView):
edit_template = 'image_edit.html'

@expose('/edit/', methods=['GET', 'POST'])
def edit_view(self):
    id = request.args.get('id')
    self._template_args['image'] = db.session.query(Image.path).filter(Image.id == id).first()[0]
    return super(ImageView, self).edit_view()

And HTML template:

{% extends "admin/model/edit.html" %}
{% block body %}
  <img src=/static/images/{{ image }}/>
  {{ super() }}
{% endblock %}


问:
Jenkins Build Failed : Xcode couldn't find a provisioning profile matching
I have Jenkins Master running on Aws instance of Ubuntu and created mac laptop as slave , when I ran using Xcode in mac loptop build is successful but when I trigger it from Jenkins it's giving.

```<code>     error :

        Check dependencies : No profiles for 'com.xyz.abc' were found: Xcode couldn't find a provisioning profile matching 'com.xyz.abc'. Code signing is required for product type 'Application' in SDK 'iOS 10.2'

* ARCHIVE FAILED * The following build commands failed: Check dependencies (1 failure) Build step 'Xcode' marked build as failure.
</code>```

Ps :

I have already tried to read previous post but most of them were having Jenkins running on MAC, also xcode is running on same server which is not my case.

As I am able to run my project in xcode I feel that my code signing & provisioning profile are correct. Furthermore now I am able to create IPA using
Xcode option :

Product --> Archive in Xcode in Mac Laptop

Then why jenkins is not able to create ipa ?

I also have moved all keys in login.keychain to system.keychain

I have connected jenkins master(ubuntu) to slave(mac) using java slave-agent.jnlp

Jenkins Console Output :

===========================================================
== Available provisioning profiles
[ios] $ /usr/bin/security find-identity -p codesigning -v

27) XXXXX "Mac Developer: Ashish Karpe (YYYYY)"

Which is similar as in xcode in mac laptop so I am not able to figure out what is wrong her !

答:
At last I got the solution and now I can saw we can build IPA from Jenkins Master (Ubuntu AWS instance) using MAC laptop as slave.

My mistake was there were too many provisioning profiles created. I Xcode on Mac laptop when I used one profile (10 digit Development Team ID) which was working properly so I used same on Jenkins side but it failed !

Furthermore Jenkins showed all the detected profiles when I configured Provisioning profiles on Jenkins master and tried with another 10 digit  Development Team ID which worked for me.

All together now I am able to create IPA using Jenkins build but I am not sure why my profile which worked in Xcode worked but didn't worked in Jenkins.

Since, my task is done to marking it here as Answer so in case someone else face similar issues, he can try with 10 digit Development Team ID to get it working !

Hope so this helps someone as I was frustrated a lot and had started hating IOS Deployment !

Body:
I have Jenkins Master running on Aws instance of Ubuntu and created mac laptop as slave , when I ran using Xcode in mac loptop build is successful but when I trigger it from Jenkins it's giving.

     error :

        Check dependencies : No profiles for 'com.xyz.abc' were found: Xcode couldn't find a provisioning profile matching 'com.xyz.abc'. Code signing is required for product type 'Application' in SDK 'iOS 10.2'

* ARCHIVE FAILED * The following build commands failed: Check dependencies (1 failure) Build step 'Xcode' marked build as failure.

Ps :

I have already tried to read previous post but most of them were having Jenkins running on MAC, also xcode is running on same server which is not my case.

As I am able to run my project in xcode I feel that my code signing & provisioning profile are correct. Furthermore now I am able to create IPA using
Xcode option :

Product --> Archive in Xcode in Mac Laptop

Then why jenkins is not able to create ipa ?

I also have moved all keys in login.keychain to system.keychain

I have connected jenkins master(ubuntu) to slave(mac) using java slave-agent.jnlp

Jenkins Console Output :

===========================================================
== Available provisioning profiles
[ios] $ /usr/bin/security find-identity -p codesigning -v

27) XXXXX "Mac Developer: Ashish Karpe (YYYYY)"

Which is similar as in xcode in mac laptop so I am not able to figure out what is wrong her !


问:
Extracting certain parts on image with PHP
I would like to be able to extract radar data from gif which occurs every hour.

This is an example of one gif:

Data colors can vary according data legend on the right. I would also like that country borders are not visible, as gif is drown in order: base layer, radar data layer, borders layer - I only need pure radar data.

Any suggestion or solution will be very much appriciated!

答: You can use 'imagecreatefromgif' to retrieve the gif and load it as an GD object (requires GD enabled in the php.ini). From there you can use quite a few image manipulation tricks to cut down to what you want from the gif. The PHP.net site has an example on what you can do with it.</p>


问:
How can I add a button that toggles a drop down result in React?
I'm still learning a lot about React but I'm finding a toggle a lot difficult than I think it should be.

What I'm aiming to achieve is a link titled 'Add Me' that when clicked on shows a a new label that is title 'Added!' having also removed the original 'Add Me' link.

The current code below is what I have, of which I thought would work but it doesn't. I have read A LOT of questions & answers around this simple action, none of which has worked here. Any insight into what I'm doing wrong &/or how to correct it would be extremely helpful!

Thank you in advance!

JSX:

```<code>class App extends React.Component {

constructor(props) {
  super(props);
  this.state = {
    showComponent: false,
  };
  this.Search__toggle = this.Search__toggle.bind(this);
}

Search__toggle() {
  this.setState({
    showComponent: true,
  });
}

render() {
    return (
        <div className="FormField__control">
            <a onClick={this.Search__toggle}><i className="fa fa-plus" aria-hidden="true" />
                Add Me
            </a>
            {this.state.showComponent ? <div>Added!</div> : null }
        </div>
    );
}

export default App;
</code>```

答:
You were almost there :-). Not sure you Search__toggle is the right name for your function since you don't want to toggle the element but rather add it once.

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      showComponent: false,
    };
    this.addItem = this.addItem.bind(this);
  }

  addItem() {
    this.setState({
      showComponent: true,
    });
  }

  render() {
    return (

            { this.state.showComponent ?
            "Added"
            :

              Add Me

            }

    );
  }
}

ReactDOM.render(
  <App name="World" />,
  document.getElementById('container')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div></code>```

If however you'd like to rather toggle your element, here is another version.

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      showComponent: false,
    };
    this.Search__toggle = this.Search__toggle.bind(this);
  }

  Search__toggle() {
    this.setState({
      showComponent: !this.state.showComponent,
    });
  }

  render() {
    return (

            { this.state.showComponent ?

              Added

            :

              Add Me

            }

    );
  }
}

ReactDOM.render(
  <App name="World" />,
  document.getElementById('container')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div></code>```

Hope this helps!

Body:
I'm still learning a lot about React but I'm finding a toggle a lot difficult than I think it should be.

What I'm aiming to achieve is a link titled 'Add Me' that when clicked on shows a a new label that is title 'Added!' having also removed the original 'Add Me' link.

The current code below is what I have, of which I thought would work but it doesn't. I have read A LOT of questions & answers around this simple action, none of which has worked here. Any insight into what I'm doing wrong &/or how to correct it would be extremely helpful!

Thank you in advance!

JSX:

class App extends React.Component {

constructor(props) {
  super(props);
  this.state = {
    showComponent: false,
  };
  this.Search__toggle = this.Search__toggle.bind(this);
}

Search__toggle() {
  this.setState({
    showComponent: true,
  });
}

render() {
    return (

                Add Me

            {this.state.showComponent ?
Added!
 : null }

    );
}

export default App;

Body:
You were almost there :-). Not sure you Search__toggle is the right name for your function since you don't want to toggle the element but rather add it once.

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      showComponent: false,
    };
    this.addItem = this.addItem.bind(this);
  }

  addItem() {
    this.setState({
      showComponent: true,
    });
  }

  render() {
    return (
        <div className="FormField__control">
            { this.state.showComponent ?
            "Added"
            :
            <a onClick={this.addItem}>
              <i className="fa fa-plus" aria-hidden="true" />Add Me
            </a>
            }
        </div>
    );
  }
}

ReactDOM.render(
  <App name="World" />,
  document.getElementById('container')
);

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

If however you'd like to rather toggle your element, here is another version.

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      showComponent: false,
    };
    this.Search__toggle = this.Search__toggle.bind(this);
  }

  Search__toggle() {
    this.setState({
      showComponent: !this.state.showComponent,
    });
  }

  render() {
    return (
        <div className="FormField__control">
            { this.state.showComponent ?
            <a onClick={this.Search__toggle}>
              <i className="fa fa-minus" aria-hidden="true" />Added
            </a>
            :
            <a onClick={this.Search__toggle}>
              <i className="fa fa-plus" aria-hidden="true" />Add Me
            </a>
            }
        </div>
    );
  }
}

ReactDOM.render(
  <App name="World" />,
  document.getElementById('container')
);

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

Hope this helps!


问:
Xamarin, Android: Change size of linear Layout programmatically
here is my code:

```<code>        linlay = FindViewById<LinearLayout>(Resource.Id.linlay_profile);
        LinearLayout.LayoutParams _params = new LinearLayout.LayoutParams
            (500, 500);
        linlay.LayoutParameters = _params;
</code>```

So, in my xml, there is a linearlayout with a height 0f 200.
Now, in the programcode I need to change the height to 500.
But it crashes on the last bit of code:

```<code>    linlay.LayoutParameters = _params;
</code>```

Why is that?

Thank you!

答:
I just stumbled upon the solution:
appearently, the layoutparams have to be of the parent. in my case this was a framelayout.
dont get it either but its working now.</p>

```<code>        linlay = FindViewById<LinearLayout>(Resource.Id.linlay_profile);
        FrameLayout.LayoutParams _params = new FrameLayout.LayoutParams
            (ViewGroup.LayoutParams.FillParent,
            (Resources.DisplayMetrics.HeightPixels / 3));
        linlay.LayoutParameters = _params;
</code>```

Body:
here is my code:

        linlay = FindViewById<LinearLayout>(Resource.Id.linlay_profile);
        LinearLayout.LayoutParams _params = new LinearLayout.LayoutParams
            (500, 500);
        linlay.LayoutParameters = _params;

So, in my xml, there is a linearlayout with a height 0f 200.
Now, in the programcode I need to change the height to 500.
But it crashes on the last bit of code:

    linlay.LayoutParameters = _params;

Why is that?

Thank you!

Body:
I just stumbled upon the solution:
appearently, the layoutparams have to be of the parent. in my case this was a framelayout.
dont get it either but its working now.

        linlay = FindViewById<LinearLayout>(Resource.Id.linlay_profile);
        FrameLayout.LayoutParams _params = new FrameLayout.LayoutParams
            (ViewGroup.LayoutParams.FillParent,
            (Resources.DisplayMetrics.HeightPixels / 3));
        linlay.LayoutParameters = _params;


问:
Python code performance on big data os.path.getsize
Below is my code to get file size in ascending order.

```<code>def Create_Files_Structure(directoryname):
   for path, subdirs, files in os.walk(directoryname,followlinks=False):
        subdirs[:] = [d for d in subdirs if not d[0] == '.']
        try:
           files_list.extend([(os.path.join(path, file),os.path.getsize(os.path.join(path, file))) for file in files ])
        except Exception as e:
            print()
   files_list.sort(key=lambda s: s[1], reverse=True)
   for pair in files_list:
     print(pair)
   print(len(files_list))

start=time.time()
Create_Files_Structure("/home/<username>")
end=time.time()
print(end-start)
</code>```

This code is working however performance is slow if size of a directory is in TB or PB. Any suggestion to improve the code to get faster result please.

答:
To get a feel for how fast you can get, try running and timing du -k on the directory. You probably won't be getting faster than that with Python for a full listing.

If you're running on Python < 3.5, try upgrading or using scandir for a nice performance improvement.

If you don't really need the whole list of files but can live with e.g the largest 1000 files:

Avoid keeping the list and use heapq.nlargest with a generator

```<code>def get_sizes(root):
  for path, dirs, files in os.walk(root):
    dirs[:] = [d for d in dirs if not d.startswith('.')]
    for file in files:
        full_path = os.path.join(path, file)
        try:
          # keeping the size first means no need for a key function
          # which can affect performance
          yield (os.path.getsize(full_path), full_path)
        except Exception:
          pass

import heapq
for (size, name) in heapq.nlargest(1000, get_sizes(r"c:\some\path")):
  print(name, size)
</code>```

EDIT - to get even faster on Windows - os.scandir yields entries that already contain the size helping avoid another system call.

This means using os.scandir and recursing yourself instead of relying on os.walk which doesn't yield that information.

There's a similar working example get_tree_size() function in the scandir PEP 471 that can be easily modified to yield names and sizes instead. Each entry's size is accessible with entry.stat(follow_symlinks=False).st_size.

Body:
Below is my code to get file size in ascending order.

def Create_Files_Structure(directoryname):
   for path, subdirs, files in os.walk(directoryname,followlinks=False):
        subdirs[:] = [d for d in subdirs if not d[0] == '.']
        try:
           files_list.extend([(os.path.join(path, file),os.path.getsize(os.path.join(path, file))) for file in files ])
        except Exception as e:
            print()
   files_list.sort(key=lambda s: s[1], reverse=True)
   for pair in files_list:
     print(pair)
   print(len(files_list))

start=time.time()
Create_Files_Structure("/home/<username>")
end=time.time()
print(end-start)

This code is working however performance is slow if size of a directory is in TB or PB. Any suggestion to improve the code to get faster result please.

Body:
To get a feel for how fast you can get, try running and timing du -k on the directory. You probably won't be getting faster than that with Python for a full listing.

If you're running on Python < 3.5, try upgrading or using scandir for a nice performance improvement.

If you don't really need the whole list of files but can live with e.g the largest 1000 files:

Avoid keeping the list and use heapq.nlargest with a generator

def get_sizes(root):
  for path, dirs, files in os.walk(root):
    dirs[:] = [d for d in dirs if not d.startswith('.')]
    for file in files:
        full_path = os.path.join(path, file)
        try:
          # keeping the size first means no need for a key function
          # which can affect performance
          yield (os.path.getsize(full_path), full_path)
        except Exception:
          pass

import heapq
for (size, name) in heapq.nlargest(1000, get_sizes(r"c:\some\path")):
  print(name, size)

EDIT - to get even faster on Windows - os.scandir yields entries that already contain the size helping avoid another system call.

This means using os.scandir and recursing yourself instead of relying on os.walk which doesn't yield that information.

There's a similar working example get_tree_size() function in the scandir PEP 471 that can be easily modified to yield names and sizes instead. Each entry's size is accessible with entry.stat(follow_symlinks=False).st_size.


问:
Whatsapp share not working in Webview
I have created a simple website app using webview in android studio and given it internet access permission also enabled java script on app

When I have added a WhatsApp share button using this code

```<code> <button>
<a href="whatsapp://send?text=HERE GOES THE URL ENCODED TEXT YOU WANT TO SHARE" data-action="share/whatsapp/share">Share via Whatsapp</a>
</button>
</code>```

This is working well in all mobile browsers but when I try to use this on my app I am getting an error screen saying

Web page not available

The web page
  at whatsapp://send?text=I'm%20interested%20in%20your%20car%20for%20salecould
  not be loaded because:

net::ERR_UNKNOWN_URL_SCHEME

This is my code in mainactivity.java

```<code>package com.a4extras.ukzz.whatsappdaily;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    private WebView mywebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mywebView = (WebView)findViewById(R.id.WebView);
        WebSettings webSettings = mywebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mywebView.loadUrl("http://ukzz4u.blogspot.com/2017/11/whatsapp-share-01.html");
        mywebView.setWebViewClient(new WebViewClient());
    }

    @Override
    public void onBackPressed() {
        if (mywebView.canGoBack()) {
            mywebView.goBack();
        } else {
            super.onBackPressed();
        }
    }}
</code>```

This is because my app is taking whatsapp:// as a URL
So how can prevent this so that the Share button will work properly

Please help me with necessary script
Thanks

答:
Using the following code i am able to open the url in webview: Put the
blow code snippet to your onCreate() method

```<code>wv1.setWebViewClient(new MyBrowser());
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl("http://ukzz4u.blogspot.com/2017/11/whatsapp-share-01.html");
</code>```

And then add this class to your activity:

```<code>private class MyBrowser extends WebViewClient {
         @Override
         public boolean shouldOverrideUrlLoading(WebView view, String url)  {
             view.loadUrl(url);
             return true;
         }
     }
</code>```

Title: Whatsapp share not working in Webview

Body:
I have created a simple website app using webview in android studio and given it internet access permission also enabled java script on app

When I have added a WhatsApp share button using this code

 <button>
Share via Whatsapp
</button>

This is working well in all mobile browsers but when I try to use this on my app I am getting an error screen saying

Web page not available

The web page
  at whatsapp://send?text=I'm%20interested%20in%20your%20car%20for%20salecould
  not be loaded because:

net::ERR_UNKNOWN_URL_SCHEME

This is my code in mainactivity.java

package com.a4extras.ukzz.whatsappdaily;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    private WebView mywebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mywebView = (WebView)findViewById(R.id.WebView);
        WebSettings webSettings = mywebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mywebView.loadUrl("http://ukzz4u.blogspot.com/2017/11/whatsapp-share-01.html");
        mywebView.setWebViewClient(new WebViewClient());
    }

    @Override
    public void onBackPressed() {
        if (mywebView.canGoBack()) {
            mywebView.goBack();
        } else {
            super.onBackPressed();
        }
    }}

This is because my app is taking whatsapp:// as a URL
So how can prevent this so that the Share button will work properly

Please help me with necessary script
Thanks

Body:
Using the following code i am able to open the url in webview: Put the
blow code snippet to your onCreate() method

wv1.setWebViewClient(new MyBrowser());
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl("http://ukzz4u.blogspot.com/2017/11/whatsapp-share-01.html");

And then add this class to your activity:

private class MyBrowser extends WebViewClient {
         @Override
         public boolean shouldOverrideUrlLoading(WebView view, String url)  {
             view.loadUrl(url);
             return true;
         }
     }