问:
How can I create dynamic destination files name based on what is filtered?
For example if in my log line appears something like that [xxx], I must put this message in a file with a name starting as xxx.log
And if the message changes and appears [xxy] I must create a new log file named as xxy.log
How can I do that in a syslog-ng config file? </p>

答:
to filter for specific messages, you can use filter expressions in syslog-ng:
You can use regular expressions in the filter as well.
To use the results of the match in the filename, try using a named pattern in the filter expression:

```<code>filter f_myfilter {message("(?<name>pattern)");};
</code>```

Then you can use the named match in the destination template:

```<code>destination d_file {
    file ("/var/log/${name}.log");
};
</code>```

Let me know if it works, I haven't had the time to test it.

Body:
to filter for specific messages, you can use filter expressions in syslog-ng:
You can use regular expressions in the filter as well.
To use the results of the match in the filename, try using a named pattern in the filter expression:

filter f_myfilter {message("(?<name>pattern)");};

Then you can use the named match in the destination template:

destination d_file {
    file ("/var/log/${name}.log");
};

Let me know if it works, I haven't had the time to test it.


来源: stackexchange

问:
Drawing Trapezium shaped ROI OpenCV C++
I'm working on a lane detection problem using OpenCV in C++. To select the ROI, I'm planning to use a trapezium shape mask to filter the region. However, I'm unable to figure out how to draw a trapezium. After choosing the four vertices, a differently shaped polygon is being drawn. Here's my code.</p>

```<code>void select_roi(Mat &frame){
    int rows = frame.rows;
    int cols = frame.cols;

    Point points[1][4];
    points[0][0] = Point(cols*0.05, rows);
    points[0][1] = Point(cols*0.4, rows*0.4);
    points[0][2] = Point(cols*0.95, rows);
    points[0][3] =  Point(cols*0.6, rows*0.4);

    Mat img = empty_image(frame); //User defined function that returns empty image of frame dimensions
    const Point* ppt[1] = {points[0]};
    int npt[] = {4};
    fillPoly(img, ppt, npt, 1, Scalar(255,0,0), 8);
    imshow("Poly",img);
}
</code>```

答:
Really simple error: your points are not in the right order. Currently you're drawing the bottom left, then the top left, then the bottom right, and then the top right, and connecting back to the first. Imagine if you traced it out with those coordinates in order---you'd get the same shape that you have in error. So all you need to do is order them so that if you drew lines from each point to the next, you'd create the shape.</p>

```<code>points[0][0] = Point(cols*0.05, rows);
points[0][1] = Point(cols*0.4, rows*0.4);
points[0][2] = Point(cols*0.6, rows*0.4);
points[0][3] = Point(cols*0.95, rows);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Drawing Trapezium shaped ROI OpenCV C++

Body:
I'm working on a lane detection problem using OpenCV in C++. To select the ROI, I'm planning to use a trapezium shape mask to filter the region. However, I'm unable to figure out how to draw a trapezium. After choosing the four vertices, a differently shaped polygon is being drawn. Here's my code.

void select_roi(Mat &frame){
    int rows = frame.rows;
    int cols = frame.cols;

    Point points[1][4];
    points[0][0] = Point(cols*0.05, rows);
    points[0][1] = Point(cols*0.4, rows*0.4);
    points[0][2] = Point(cols*0.95, rows);
    points[0][3] =  Point(cols*0.6, rows*0.4);

    Mat img = empty_image(frame); //User defined function that returns empty image of frame dimensions
    const Point* ppt[1] = {points[0]};
    int npt[] = {4};
    fillPoly(img, ppt, npt, 1, Scalar(255,0,0), 8);
    imshow("Poly",img);
}

Body:
Really simple error: your points are not in the right order. Currently you're drawing the bottom left, then the top left, then the bottom right, and then the top right, and connecting back to the first. Imagine if you traced it out with those coordinates in order---you'd get the same shape that you have in error. So all you need to do is order them so that if you drew lines from each point to the next, you'd create the shape.

points[0][0] = Point(cols*0.05, rows);
points[0][1] = Point(cols*0.4, rows*0.4);
points[0][2] = Point(cols*0.6, rows*0.4);
points[0][3] = Point(cols*0.95, rows);


问:
Caused by: java.io.IOException: Unable to lock usage tracking spool file
Having problems while building an android application with gradle, here is the error i get when building it;

```<code>Caused by: java.io.IOException: Unable to lock usage tracking spool file
            at com.android.tools.analytics.JournalingUsageTracker.newTrackFile(JournalingUsageTracker.java:98)
            at com.android.tools.analytics.JournalingUsageTracker.<init>(JournalingUsageTracker.java:78)
            ... 121 more
    Caused by: java.nio.channels.OverlappingFileLockException
            at com.android.tools.analytics.JournalingUsageTracker.newTrackFile(JournalingUsageTracker.java:95)
            ... 122 more
</code>```

Here is my gradle details: https://pastebin.com/6v0dk5in

```<code> ./gradlew --version

------------------------------------------------------------
Gradle 4.3.1
------------------------------------------------------------

Build time:   2017-11-08 08:59:45 UTC
Revision:     e4f4804807ef7c2829da51877861ff06e07e006d

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_66 (Oracle Corporation 25.66-b17)
OS:           Mac OS X 10.11 x86_64
</code>```

答:
Killing the java process and re-building fixes it but you have to do this on every build.

os x el capitan 10.11 (15A284)

https://github.com/gradle/gradle/issues/937

https://docs.gradle.org/current/userguide/gradle_daemon.html

Body:
Having problems while building an android application with gradle, here is the error i get when building it;

Caused by: java.io.IOException: Unable to lock usage tracking spool file
            at com.android.tools.analytics.JournalingUsageTracker.newTrackFile(JournalingUsageTracker.java:98)
            at com.android.tools.analytics.JournalingUsageTracker.<init>(JournalingUsageTracker.java:78)
            ... 121 more
    Caused by: java.nio.channels.OverlappingFileLockException
            at com.android.tools.analytics.JournalingUsageTracker.newTrackFile(JournalingUsageTracker.java:95)
            ... 122 more

Here is my gradle details: https://pastebin.com/6v0dk5in

 ./gradlew --version

------------------------------------------------------------
Gradle 4.3.1
------------------------------------------------------------

Build time:   2017-11-08 08:59:45 UTC
Revision:     e4f4804807ef7c2829da51877861ff06e07e006d

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_66 (Oracle Corporation 25.66-b17)
OS:           Mac OS X 10.11 x86_64


问:
draggable droppable with sortable
we trying to integrate multiple drggable and droppable. we are using sortable for ease of clone functionality in this scenario. draggable once dropped need to be draggable again.

how do we limit sortable to receive only one element and revert to original if more than one dropped onto it.

look like out and over functions of sortable are misbehaving in that case.

commented line code is for disabling dropping second element on sortable. which is not working as expected.

Two issues when you enable my commented code:

draggable clone not reverting to original place after moving out of droppable.

draggable element moved from one droppable to another reverting to draggable's original place.

For a demonstration, see this jsfiddle

script:

```<code>//  jQuery.noConflict();

jQuery( document ).ready(function() { init();});
function init() {

  var mouse_button = false;
  jQuery('.ui-draggable').live({
      mousedown: function () {
          mouse_button = true;
      },
      mouseup: function () {

          if (jQuery(this).attr('data-pos') == 'out' && jQuery(this).attr('data-id')) {
              var p = jQuery('#' + jQuery(this).attr('data-id'));
              var offset = p.offset();
              jQuery(this).hide();
              jQuery(this).animate({ left: offset.left, top: offset.top, width: jQuery(this).width, height: jQuery(this).height }, 100, function () {
                  jQuery(this).remove();
                  $( ".ui-droppable" ).each(function() {
                    if($(this).children().length == 0) {
                      $( this ).removeClass("dontDrop");
                    }
                  });
                  //if(p[0].hasAttribute("draggable"))
                  p.draggable("enable");

             //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
             //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));

              });
          }
          mouse_button = false;
      },
      mouseout: function () {
          if (mouse_button) {
              mouse_button = false;
          }
      }

  });

    jQuery( '.ui-draggable' ).draggable( {
      cursor: 'move',
      helper: 'clone',
      connectToSortable: ".ui-droppable",
      revert: function (event, ui) {
        }
    } );

    jQuery(".ui-droppable").sortable({
        cursor: "move",
        connectWith: ".ui-droppable",
        receive: function (event, ui) {

        if($(this).children().length >= 1) {

            $(this).children().addClass('filled');
            $(this).addClass('dontDrop');

            $( ".ui-droppable" ).each(function() {
              if($(this).children().length == 0) {
                $( this ).removeClass("dontDrop");
              }
            });
       //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
       //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));
        }else {
            $(this).children().removeClass('filled');
        }
        if (jQuery(this).data().sortable.currentItem) {
                jQuery(this).data().sortable.currentItem.attr('data-id', jQuery(ui.item).attr("id"));
               // if(jQuery(ui.item)[0].hasAttribute("draggable"))
                jQuery(ui.item).draggable("disable");
            }

        },
        out: function (event, ui) {  if (ui.helper) { ui.helper.attr('data-pos', 'out'); } },
        over: function (event, ui) { ui.helper.attr('data-pos', 'in'); }
    });

  }
</code>```

答:
You can do it like this:(Online Demo (fiddle))

```<code>var draggable_options = {
  helper: 'clone',
  cursor: 'move',
  revert: 'invalid',
};

$(".ui-draggable").draggable(draggable_options);

$(".ui-droppable").droppable({
  drop: function(event, ui) {
    var $item = ui.draggable;
    $item.draggable(draggable_options)
    $item.attr('style', '')
    $(this).append($item)
  },
  accept: function() {
    return $(this).find("li").length === 0 // Your condition
  }
});

$(".textToImageRightPanel").droppable({
  drop: function(event, ui) {
    var $item = ui.draggable;
    $item.draggable(draggable_options);
    $item.attr('style', '');
    // Return to older place in list
    returnToOlderPlace($item);
  }
});

// Return item by drop in older div by data-tabidx
function returnToOlderPlace($item) {
  var indexItem = $item.attr('data-tabidx');
  var itemList = $(".textToImageRightPanel").find('li').filter(function() {
    return $(this).attr('data-tabidx') < indexItem
  });
  if (itemList.length === 0)
    $("#cardPile").find('ul').prepend($item);
  else
    itemList.last().after($item);
}
</code>```

Title: draggable droppable with sortable

Body:
we trying to integrate multiple drggable and droppable. we are using sortable for ease of clone functionality in this scenario. draggable once dropped need to be draggable again.

how do we limit sortable to receive only one element and revert to original if more than one dropped onto it.

look like out and over functions of sortable are misbehaving in that case.

commented line code is for disabling dropping second element on sortable. which is not working as expected.

Two issues when you enable my commented code:

draggable clone not reverting to original place after moving out of droppable.

draggable element moved from one droppable to another reverting to draggable's original place.

For a demonstration, see this jsfiddle

script:

//  jQuery.noConflict();

jQuery( document ).ready(function() { init();});
function init() {

  var mouse_button = false;
  jQuery('.ui-draggable').live({
      mousedown: function () {
          mouse_button = true;
      },
      mouseup: function () {

          if (jQuery(this).attr('data-pos') == 'out' && jQuery(this).attr('data-id')) {
              var p = jQuery('#' + jQuery(this).attr('data-id'));
              var offset = p.offset();
              jQuery(this).hide();
              jQuery(this).animate({ left: offset.left, top: offset.top, width: jQuery(this).width, height: jQuery(this).height }, 100, function () {
                  jQuery(this).remove();
                  $( ".ui-droppable" ).each(function() {
                    if($(this).children().length == 0) {
                      $( this ).removeClass("dontDrop");
                    }
                  });
                  //if(p[0].hasAttribute("draggable"))
                  p.draggable("enable");

             //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
             //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));

              });
          }
          mouse_button = false;
      },
      mouseout: function () {
          if (mouse_button) {
              mouse_button = false;
          }
      }

  });

    jQuery( '.ui-draggable' ).draggable( {
      cursor: 'move',
      helper: 'clone',
      connectToSortable: ".ui-droppable",
      revert: function (event, ui) {
        }
    } );

    jQuery(".ui-droppable").sortable({
        cursor: "move",
        connectWith: ".ui-droppable",
        receive: function (event, ui) {

        if($(this).children().length >= 1) {

            $(this).children().addClass('filled');
            $(this).addClass('dontDrop');

            $( ".ui-droppable" ).each(function() {
              if($(this).children().length == 0) {
                $( this ).removeClass("dontDrop");
              }
            });
       //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
       //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));
        }else {
            $(this).children().removeClass('filled');
        }
        if (jQuery(this).data().sortable.currentItem) {
                jQuery(this).data().sortable.currentItem.attr('data-id', jQuery(ui.item).attr("id"));
               // if(jQuery(ui.item)[0].hasAttribute("draggable"))
                jQuery(ui.item).draggable("disable");
            }

        },
        out: function (event, ui) {  if (ui.helper) { ui.helper.attr('data-pos', 'out'); } },
        over: function (event, ui) { ui.helper.attr('data-pos', 'in'); }
    });

  }

Body:
You can do it like this:(Online Demo (fiddle))

var draggable_options = {
  helper: 'clone',
  cursor: 'move',
  revert: 'invalid',
};

$(".ui-draggable").draggable(draggable_options);

$(".ui-droppable").droppable({
  drop: function(event, ui) {
    var $item = ui.draggable;
    $item.draggable(draggable_options)
    $item.attr('style', '')
    $(this).append($item)
  },
  accept: function() {
    return $(this).find("li").length === 0 // Your condition
  }
});

$(".textToImageRightPanel").droppable({
  drop: function(event, ui) {
    var $item = ui.draggable;
    $item.draggable(draggable_options);
    $item.attr('style', '');
    // Return to older place in list
    returnToOlderPlace($item);
  }
});

// Return item by drop in older div by data-tabidx
function returnToOlderPlace($item) {
  var indexItem = $item.attr('data-tabidx');
  var itemList = $(".textToImageRightPanel").find('li').filter(function() {
    return $(this).attr('data-tabidx') < indexItem
  });
  if (itemList.length === 0)
    $("#cardPile").find('ul').prepend($item);
  else
    itemList.last().after($item);
}


问:
Error: android.view.inflateExeption in CustomTextView
I have a menu activity that gets user setting of font and size and line spacing of text in all of TextView's, so i need a CustomTextView class to set these changes but my custom TextView does't work and give inflate Exception in logcat window. tank's a lot for your helps!

my CustomTextView:

```<code>package com.niloo.test2;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class CustomTextView extends TextView {

Context context;
SharedPreferences shp = context.getSharedPreferences("text", Context.MODE_PRIVATE);
int size = shp.getInt("size", 22);
int fasle = shp.getInt("fasle", 1);
String font = shp.getString("font", "bmitra");

public CustomTextView(Context context) {
    super(context);
    if (!isInEditMode())
        setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/"+font));
        setTextSize(size);
        setLineSpacing(fasle, 1);
}

public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    if (! isInEditMode())
        setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/"+font));
        setTextSize(size);
        setLineSpacing(fasle, 1);
}

public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    if (!isInEditMode())
        setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/"+font));
        setTextSize(size);
        setLineSpacing(fasle, 1);
}

protected void onDraw (Canvas canvas) {
    super.onDraw(canvas);
}
}
</code>```

my XML code:

```<code>      <com.niloo.test2.CustomTextView
           android:id="@+id/tv_onv_amoozsh"
           android:layout_width="match_parent"
           android:layout_height="0dp"
           android:layout_gravity="center_vertical|center_horizontal"
           android:layout_marginTop="10dp"
           android:layout_weight="0.5"
           android:textColor="@color/sabz_lajani"
           android:textSize="25sp"
           android:textStyle="bold" />

    <com.niloo.test2.CustomTextView
          android:id="@+id/tv_num_amoozsh"
          android:layout_width="match_parent"
          android:layout_height="0dp"
          android:layout_gravity="center_vertical|center_horizontal"
          android:layout_marginBottom="2dp"
          android:layout_weight="0.75"
          android:textColor="@color/sabz_lajani"
          android:textSize="35sp" />
</code>```

and my main class:

```<code>final CustomTextView tv_onv_amoozsh= (CustomTextView) findViewById(R.id.tv_onv_amoozsh);
        tv_onv_amoozsh.setText("page");
final CustomTextView tv_num_amoozsh=(CustomTextView) findViewById(R.id.tv_num_amoozsh);
        tv_num_amoozsh.setText(sfhe_num);
</code>```

LogCat Error:

```<code>02-03 22:41:38.329: E/AndroidRuntime(19952): FATAL EXCEPTION: main
02-03 22:41:38.329: E/AndroidRuntime(19952): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.niloo.test2/com.niloo.test2.MainActivity}: android.view.InflateException: Binary XML file line #143: Error inflating class com.niloo.test2.CustomTextView
</code>```

答:
The error is coming from this line:

```<code>setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/"+font));
</code>```

Here we don't need to mention the keyword "fonts/" for path, because getAssets() method giving the route path of assets folder. So you can directly give font name like below:

```<code>setTypeface(Typeface.createFromAsset(context.getAssets(), font));
</code>```

Body:
I have a menu activity that gets user setting of font and size and line spacing of text in all of TextView's, so i need a CustomTextView class to set these changes but my custom TextView does't work and give inflate Exception in logcat window. tank's a lot for your helps!

my CustomTextView:

package com.niloo.test2;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class CustomTextView extends TextView {

Context context;
SharedPreferences shp = context.getSharedPreferences("text", Context.MODE_PRIVATE);
int size = shp.getInt("size", 22);
int fasle = shp.getInt("fasle", 1);
String font = shp.getString("font", "bmitra");

public CustomTextView(Context context) {
    super(context);
    if (!isInEditMode())
        setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/"+font));
        setTextSize(size);
        setLineSpacing(fasle, 1);
}

public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    if (! isInEditMode())
        setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/"+font));
        setTextSize(size);
        setLineSpacing(fasle, 1);
}

public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    if (!isInEditMode())
        setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/"+font));
        setTextSize(size);
        setLineSpacing(fasle, 1);
}

protected void onDraw (Canvas canvas) {
    super.onDraw(canvas);
}
}

my XML code:

      <com.niloo.test2.CustomTextView
           android:id="@+id/tv_onv_amoozsh"
           android:layout_width="match_parent"
           android:layout_height="0dp"
           android:layout_gravity="center_vertical|center_horizontal"
           android:layout_marginTop="10dp"
           android:layout_weight="0.5"
           android:textColor="@color/sabz_lajani"
           android:textSize="25sp"
           android:textStyle="bold" />

    <com.niloo.test2.CustomTextView
          android:id="@+id/tv_num_amoozsh"
          android:layout_width="match_parent"
          android:layout_height="0dp"
          android:layout_gravity="center_vertical|center_horizontal"
          android:layout_marginBottom="2dp"
          android:layout_weight="0.75"
          android:textColor="@color/sabz_lajani"
          android:textSize="35sp" />

and my main class:

final CustomTextView tv_onv_amoozsh= (CustomTextView) findViewById(R.id.tv_onv_amoozsh);
        tv_onv_amoozsh.setText("page");
final CustomTextView tv_num_amoozsh=(CustomTextView) findViewById(R.id.tv_num_amoozsh);
        tv_num_amoozsh.setText(sfhe_num);

LogCat Error:

02-03 22:41:38.329: E/AndroidRuntime(19952): FATAL EXCEPTION: main
02-03 22:41:38.329: E/AndroidRuntime(19952): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.niloo.test2/com.niloo.test2.MainActivity}: android.view.InflateException: Binary XML file line #143: Error inflating class com.niloo.test2.CustomTextView

Body:
The error is coming from this line:

setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/"+font));

Here we don't need to mention the keyword "fonts/" for path, because getAssets() method giving the route path of assets folder. So you can directly give font name like below:

setTypeface(Typeface.createFromAsset(context.getAssets(), font));


问:
How to get index and the range of a div element from a group of divs using jQuery
If I have a group of tokenized divs like the following.

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<div> Barrack </div>
<div> Obama </div>
<div> was </div>
<div> the </div>
<div> president </div>
<div> of </div>
<div> the </div>
<div> United </div>
<div> States </div>
<div> from </div>
<div> the </div>
<div> year </div>
<div> 2012 </div>
<div> to </div>
<div> 2016 </div>
<div> . </div>

<button id="btnClick"> Click me </button>

<script>
$(function(){

$('#btnClick').click(function(){
var selection = window.getSelection();
alert(selection);
});

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

I have tried the above

1) I want to get the index of divs when I click on multiple divs on mouse click event.
Example is if I click on div which contains Barrack and 2012, I am not able to get the selected div's index.

2) If I select the div which contains both Barrack and Obama
I want the range of the div, something like:
startIndex -> 0 and length -> 2.
Where startIndex = "Barrack" is the 0th div and it ranges 2 divs Barrack and Obama.

答:
You can try $.each() or $(selector).each()

```<code><script>
    $(document).ready(function(){
        var lastIdx = 0;
        $("div").each(function(idx, item){
            $(this).click(function(){
                if (idx > lastIdx) {
                    console.log("start:" + lastIdx);
                    console.log("length:" + (idx - lastIdx + 1));
                }
                lastIdx = idx;
            });
        });
    });
</script>
</code>```

Body:
If I have a group of tokenized divs like the following.

 Barrack

 Obama

 was

 the

 president

 of

 the

 United

 States

 from

 the

 year

 2012

 to

 2016

 .

<button id="btnClick"> Click me </button>

I have tried the above

1) I want to get the index of divs when I click on multiple divs on mouse click event.
Example is if I click on div which contains Barrack and 2012, I am not able to get the selected div's index.

2) If I select the div which contains both Barrack and Obama
I want the range of the div, something like:
startIndex -> 0 and length -> 2.
Where startIndex = "Barrack" is the 0th div and it ranges 2 divs Barrack and Obama.

Body:
You can try $.each() or $(selector).each()

<script>
    $(document).ready(function(){
        var lastIdx = 0;
        $("div").each(function(idx, item){
            $(this).click(function(){
                if (idx > lastIdx) {
                    console.log("start:" + lastIdx);
                    console.log("length:" + (idx - lastIdx + 1));
                }
                lastIdx = idx;
            });
        });
    });
</script>


问:
I am wanting to format my X Axis in GGPLOT to be years and months not days
in my ggplot call i am plotting as follows the X Axis just shows every singke days date like this 20171130 etc in the label and I want my lables to be like Nov-17 ,Dec-17 ETC

```<code># Invoke a ggplot with date vs. sessions data, segmented by device category
  ggplot(data = gaDataExt, mapping = aes(x = date, y = pageviews, group = 1, color = deviceCategory) ) +
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "date", y = "Pageviews by Device Category") +
  labs(title = "Andy D) Users by Device Category", x="Date", y="Total Page views") +
  ylim(0,NA)
</code>```

Sombody suggested to us elubridate which  didnt seem to be exactly waht I was looking for

```<code>gaDataExt %>%
  mutate(date = ymd(date),
         month = year(date)) %>%
  group_by(deviceCategory) %>%
  summarise_all(funs(mean)) %>%
  ggplot(aes(month, pageviews)) + geom_point() +
  facet_grid(deviceCategory~.) +
  theme_bw()
</code>```

here is my current output that you can see is all clustered on the date Axis and i would like to display just the month and year on that axis

```<code>gaDataExt %>%
  mutate(date = ymd(date),
         month = year(date)) %>%
  group_by(deviceCategory) %>%
  summarise_all(funs(mean)) %>%
  ggplot(aes(month, pageviews)) + geom_point() +
  facet_grid(deviceCategory~.) +
  theme_bw()
</code>```

was what somebody suggested but that didnt seem to work

here is a head of the dataframe i am trting to plot

```<code>> head(gaData_User)
        date          userType deviceCategory   country            region        city users
1 30-11-2017       New Visitor        desktop Australia          Victoria   Melbourne     2
2 30-11-2017       New Visitor         mobile Australia   New South Wales      Sydney     1
3 30-11-2017       New Visitor         mobile Australia          Victoria   Melbourne     2
4 30-11-2017 Returning Visitor        desktop Australia          Victoria   Melbourne     1
5 30-11-2017 Returning Visitor        desktop Australia          Victoria Warrnambool     1
6 30-11-2017 Returning Visitor        desktop Australia Western Australia       Perth     1
</code>```

答:
you can use scale_x_date, one simple example.

```<code>last_month <- Sys.Date() - 0:29
df <- data.frame(
  date = last_month,
  price = runif(30)
 )

ggplot(df, aes(date, price)) +
  geom_line() +
  scale_x_date(date_labels = "%Y-%m")
</code>```

Body:
in my ggplot call i am plotting as follows the X Axis just shows every singke days date like this 20171130 etc in the label and I want my lables to be like Nov-17 ,Dec-17 ETC

# Invoke a ggplot with date vs. sessions data, segmented by device category
  ggplot(data = gaDataExt, mapping = aes(x = date, y = pageviews, group = 1, color = deviceCategory) ) +
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "date", y = "Pageviews by Device Category") +
  labs(title = "Andy D) Users by Device Category", x="Date", y="Total Page views") +
  ylim(0,NA)

Sombody suggested to us elubridate which  didnt seem to be exactly waht I was looking for

gaDataExt %>%
  mutate(date = ymd(date),
         month = year(date)) %>%
  group_by(deviceCategory) %>%
  summarise_all(funs(mean)) %>%
  ggplot(aes(month, pageviews)) + geom_point() +
  facet_grid(deviceCategory~.) +
  theme_bw()

here is my current output that you can see is all clustered on the date Axis and i would like to display just the month and year on that axis

gaDataExt %>%
  mutate(date = ymd(date),
         month = year(date)) %>%
  group_by(deviceCategory) %>%
  summarise_all(funs(mean)) %>%
  ggplot(aes(month, pageviews)) + geom_point() +
  facet_grid(deviceCategory~.) +
  theme_bw()

was what somebody suggested but that didnt seem to work

here is a head of the dataframe i am trting to plot

> head(gaData_User)
        date          userType deviceCategory   country            region        city users
1 30-11-2017       New Visitor        desktop Australia          Victoria   Melbourne     2
2 30-11-2017       New Visitor         mobile Australia   New South Wales      Sydney     1
3 30-11-2017       New Visitor         mobile Australia          Victoria   Melbourne     2
4 30-11-2017 Returning Visitor        desktop Australia          Victoria   Melbourne     1
5 30-11-2017 Returning Visitor        desktop Australia          Victoria Warrnambool     1
6 30-11-2017 Returning Visitor        desktop Australia Western Australia       Perth     1

Body:
you can use scale_x_date, one simple example.

last_month <- Sys.Date() - 0:29
df <- data.frame(
  date = last_month,
  price = runif(30)
 )

ggplot(df, aes(date, price)) +
  geom_line() +
  scale_x_date(date_labels = "%Y-%m")


问:
Fluent Design System - Devices Supported
I have an UWP app published in Microsoft/Windows Store (available in Windows 10 Desktop and Windows 10 Mobile), and I want update my app to Fluent Design System but I have an doubt.
Fluent Design system dont "exists" in Windows 10 Mobile, right? (transparent background, etc.)
With the update for the Fluent Design System, I want to change the look of my application (just make a few design changes), but I want devices that do not support the Fluent Design System (version of the anniversary update or before)to have access to the application but without the Fluent Design System changes.

It is possible? Do I have to create a new project?

答:
You don't need to create a new project.

As Shubham said you can create specific package for it. However as ARM package does not only specific to Phone device, it is not a perfect idea here.

Official doc has already shared us the right way for solving this kind of problem:
https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/version-adaptive-apps

For coding part, you can perform API checks with the help of this API:

```<code>   bool isScannerDeviceContract_1_Present =
    Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent
        ("Windows.Devices.Scanners.ScannerDeviceContract", 1);
</code>```

For XAML, you can consider write Conditional XAML: https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/conditional-xaml

In this way you can write version adaptive apps.

Body:
You don't need to create a new project.

As Shubham said you can create specific package for it. However as ARM package does not only specific to Phone device, it is not a perfect idea here.

Official doc has already shared us the right way for solving this kind of problem:
https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/version-adaptive-apps

For coding part, you can perform API checks with the help of this API:

   bool isScannerDeviceContract_1_Present =
    Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent
        ("Windows.Devices.Scanners.ScannerDeviceContract", 1);

For XAML, you can consider write Conditional XAML: https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/conditional-xaml

In this way you can write version adaptive apps.


问:
PHP character problem
I have a problem with characters in PHP, I call date from MySQL that holds some special characters for example: (œÏïÎîÔôËÊÉÈëêéèÀàçÍíóÓéèÉÈÚúáàÁÀãñÑÖöÜüßÉ) the result give me � how can I fix that ?</p>

答: That character means you're outputting ANSI characters while telling the browser it is UTF-8. You should correct your HTML ContentType meta and/or content-encoding header, or convert the characters to UTF8 using utf8encode first.</p>

ContentLicense: CC BY-SA 2.5

Title: PHP character problem


问:
Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form
I am getting this error from Angular 2

core.umd.js:5995 EXCEPTION: Uncaught (in promise): Error: Error in app/model_exposure_currencies/model_exposure_currencies.component.html:57:18
caused by: If ngModel is used within a form tag, either the name
attribute must be set or the form
control must be defined as 'standalone' in ngModelOptions.

Example 1:

<input [(ngModel)]="person.firstName" name="first">
```
<p>Example 2:</p>
<pre class="lang-html prettyprint-override"><code><input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
</code>```

        <input name="name" [(ngModel)]="lag.name" [ngModelOptions]="{standalone: true}"  class="form-control" pattern="[0-9]*(\.[0-9]+)?" required>

```
<p>This is how I use form tag:</p>
<pre class="lang-html prettyprint-override"><code><form #f="ngForm" (ngSubmit)="onSubmit()">
</code>```

答:
In order to be able to display the information in the form you would like, you need to give those specific inputs of interest names. I'd recommend you do have:

```<code><form #f="ngForm" (ngSubmit)="onSubmit(f)"> ...
<input **name="firstName" ngModel** placeholder="Enter your first name"> ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting this error from Angular 2

core.umd.js:5995 EXCEPTION: Uncaught (in promise): Error: Error in app/model_exposure_currencies/model_exposure_currencies.component.html:57:18
caused by: If ngModel is used within a form tag, either the name
attribute must be set or the form
control must be defined as 'standalone' in ngModelOptions.

Example 1:

<input [(ngModel)]="person.firstName" name="first">

Example 2:

<input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

        <input name="name" [(ngModel)]="lag.name" [ngModelOptions]="{standalone: true}"  class="form-control" pattern="[0-9]*(\.[0-9]+)?" required>

This is how I use form tag:

<form #f="ngForm" (ngSubmit)="onSubmit()">

Body:
In order to be able to display the information in the form you would like, you need to give those specific inputs of interest names. I'd recommend you do have:

<form #f="ngForm" (ngSubmit)="onSubmit(f)"> ...
<input **name="firstName" ngModel** placeholder="Enter your first name"> ...


问:
Angular 4 TalwindCSS setup
Is there a way to configure TailwindCSS with Angular (4+)?

I'm happy to eject the Angular project, to make webpack configuration available. But I'm not sure what to put in the webpack.config.js so that TailwindCSS works nicely with the internals of Angular.

It would be great to have a setup such that I can still use a single command for dev (something like npm start), and continue to file changes watched (including CSS). Same for building the project.

答: If someone follow Salem's answer above and have the "atRule.before is not a function" error, just update all PostCSS dependencies to the latest version and everything should be working again.

Title: Angular 4 TalwindCSS setup


问:
Items displaying only from recyclerview and not from top of the items android
I am using nested scrollview. Inside the nested scrollview,
I have two title (Text and button)
and then below another text
then followed by recyclerview below the layout.
Then below the recyclerview, there is two edittext and submit button.

Structure looks like this.

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView 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:background="@color/colorWhite"
    android:isScrollContainer="false"
    android:paddingBottom="20dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!--Profile icon-->
        <include layout="@layout/common_profile_layout" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="26dp"
            android:background="@color/colorGrey">

            <TextView
                android:id="@+id/count_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="24dp"
                android:gravity="center"
                android:text="Ringkasan Aktifitas"
                android:textColor="?attr/colorUserGroup" />

            <Button
                android:id="@+id/dafatar_filter"
                android:layout_width="72dp"
                android:layout_height="20dp"
                android:layout_alignParentRight="true"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="10dp"
                android:background="@drawable/curve_corner_change_day"
                android:clickable="true"
                android:paddingLeft="5dp"
                android:paddingRight="5dp"
                android:text="Pilih Tanggal"
                android:textAllCaps="false"
                android:textColor="@android:color/white"
                android:textSize="10sp" />
        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/dateTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="24dp"
                android:text="06/13/2017"
                android:textColor="@color/colorBlack"
                android:textSize="@dimen/text_size_small" />
        </LinearLayout>

    //here is recyclerview where loading items.

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="19dp"
            android:background="@color/colorWhite" />
    //here below recyclerview, another edittext with buttons

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:background="@color/edit_retailer_light_color"
            android:orientation="vertical"
            android:paddingBottom="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="21dp"
                android:layout_marginTop="22dp"
                android:text="Laporan Via"
                android:textColor="@color/colorBlack"
                android:textSize="14sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="13dp"
                android:orientation="horizontal">

                <RelativeLayout
                    android:id="@+id/sms_rel"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <ImageView
                        android:id="@+id/sms_icon"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentLeft="true"
                        android:layout_marginLeft="32dp"
                        android:layout_marginTop="3dp"
                        android:src="@drawable/ic_mark_white" />

                    <TextView
                        android:id="@+id/sms_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="13dp"
                        android:layout_marginTop="3dp"
                        android:layout_toRightOf="@+id/sms_icon"
                        android:text="SMS" />

                    <EditText
                        android:id="@+id/edtSms"
                        android:layout_width="222dp"
                        android:layout_height="28dp"
                        android:layout_marginLeft="19dp"
                        android:layout_toRightOf="@+id/sms_text"
                        android:background="@drawable/edittext_border_curve"
                        android:focusable="true"
                        android:focusableInTouchMode="true"
                        android:inputType="number"
                        android:paddingLeft="5dp"
                        android:text="+62"
                        android:textColor="@color/colorBlack"
                        android:textSize="@dimen/text_size_small" />
                </RelativeLayout>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:orientation="horizontal">

                <RelativeLayout
                    android:id="@+id/rel_1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <ImageView
                        android:id="@+id/email_icon"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentLeft="true"
                        android:layout_marginLeft="32dp"
                        android:layout_marginTop="2dp"
                        android:src="@drawable/ic_mark_white" />

                    <TextView
                        android:id="@+id/email_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="13dp"
                        android:layout_marginTop="3dp"
                        android:layout_toRightOf="@+id/email_icon"
                        android:text="Email" />

                    <EditText
                        android:id="@+id/emailSms"
                        android:layout_width="222dp"
                        android:layout_height="28dp"
                        android:layout_marginLeft="15dp"
                        android:layout_toRightOf="@+id/email_text"
                        android:background="@drawable/edittext_border_curve"
                        android:inputType="textEmailAddress"
                        android:paddingLeft="5dp"
                        android:text="bejo@gmail.com"
                        android:textColor="@color/colorBlack"
                        android:textSize="@dimen/text_size_small" />
                </RelativeLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:orientation="horizontal">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="15dp">

                    <Button
                        android:id="@+id/submit_btn"
                        android:layout_width="148dp"
                        android:layout_height="30dp"
                        android:layout_centerInParent="true"
                        android:background="@drawable/curve_corner"
                        android:gravity="center"
                        android:text="Kirim"
                        android:textAllCaps="false"
                        android:textColor="@color/colorWhite"
                        android:textSize="@dimen/text_size_small" />
                </RelativeLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>
</code>```

But problem is, when I launch, it always displays only from recycler list  when there is more items and it's not displaying from top of recycler view items ie from above recyclerview layouts (titles).

In code,

```<code>LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setNestedScrollingEnabled(false); // i used only this..
        recyclerView.setAdapter(adapter);
</code>```

recycler_item_rows.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
    android:layout_marginTop="12dp"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:weightSum="2">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="8dp">

                <ImageView
                    android:id="@+id/recycle_profile"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="16dp"
                    android:src="@drawable/ic_tag" />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:layout_gravity="center"
                    android:layout_marginLeft="16dp"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/recycle_txt_acc_num"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:ellipsize="end"
                        android:maxLines="1"
                        android:singleLine="false"
                        android:text="Sell in"
                        android:textColor="@color/colorBlack"
                        android:textSize="@dimen/text_size_small" />

                    <TextView
                        android:id="@+id/recycle_txt_acc_name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:ellipsize="end"
                        android:maxLines="1"
                        android:singleLine="false"
                        android:text="Selli Cell"
                        android:textColor="?attr/colorUserGroup"
                        android:textSize="@dimen/text_size_very_small" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>

        <TextView
            android:id="@+id/timestamp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="21dp"
            android:layout_marginTop="12dp"
            android:gravity="center"
            android:text="12/11/2017 1.30"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/text_size_very_small" />
    </RelativeLayout>
</LinearLayout>
</code>```

Kindly correct my mistake to display from top.

Here is my output:

Where it's not displaying from top. And I need to manually scroll to top.

答: Add this line of code to main LinearLayout android:focusableInTouchMode="true"

Body:
I am using nested scrollview. Inside the nested scrollview,
I have two title (Text and button)
and then below another text
then followed by recyclerview below the layout.
Then below the recyclerview, there is two edittext and submit button.

Structure looks like this.

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView 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:background="@color/colorWhite"
    android:isScrollContainer="false"
    android:paddingBottom="20dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <include layout="@layout/common_profile_layout" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="26dp"
            android:background="@color/colorGrey">

            <TextView
                android:id="@+id/count_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="24dp"
                android:gravity="center"
                android:text="Ringkasan Aktifitas"
                android:textColor="?attr/colorUserGroup" />

            <Button
                android:id="@+id/dafatar_filter"
                android:layout_width="72dp"
                android:layout_height="20dp"
                android:layout_alignParentRight="true"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="10dp"
                android:background="@drawable/curve_corner_change_day"
                android:clickable="true"
                android:paddingLeft="5dp"
                android:paddingRight="5dp"
                android:text="Pilih Tanggal"
                android:textAllCaps="false"
                android:textColor="@android:color/white"
                android:textSize="10sp" />
        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/dateTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="24dp"
                android:text="06/13/2017"
                android:textColor="@color/colorBlack"
                android:textSize="@dimen/text_size_small" />
        </LinearLayout>

    //here is recyclerview where loading items.

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="19dp"
            android:background="@color/colorWhite" />
    //here below recyclerview, another edittext with buttons

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:background="@color/edit_retailer_light_color"
            android:orientation="vertical"
            android:paddingBottom="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="21dp"
                android:layout_marginTop="22dp"
                android:text="Laporan Via"
                android:textColor="@color/colorBlack"
                android:textSize="14sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="13dp"
                android:orientation="horizontal">

                <RelativeLayout
                    android:id="@+id/sms_rel"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <ImageView
                        android:id="@+id/sms_icon"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentLeft="true"
                        android:layout_marginLeft="32dp"
                        android:layout_marginTop="3dp"
                        android:src="@drawable/ic_mark_white" />

                    <TextView
                        android:id="@+id/sms_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="13dp"
                        android:layout_marginTop="3dp"
                        android:layout_toRightOf="@+id/sms_icon"
                        android:text="SMS" />

                    <EditText
                        android:id="@+id/edtSms"
                        android:layout_width="222dp"
                        android:layout_height="28dp"
                        android:layout_marginLeft="19dp"
                        android:layout_toRightOf="@+id/sms_text"
                        android:background="@drawable/edittext_border_curve"
                        android:focusable="true"
                        android:focusableInTouchMode="true"
                        android:inputType="number"
                        android:paddingLeft="5dp"
                        android:text="+62"
                        android:textColor="@color/colorBlack"
                        android:textSize="@dimen/text_size_small" />
                </RelativeLayout>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:orientation="horizontal">

                <RelativeLayout
                    android:id="@+id/rel_1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <ImageView
                        android:id="@+id/email_icon"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentLeft="true"
                        android:layout_marginLeft="32dp"
                        android:layout_marginTop="2dp"
                        android:src="@drawable/ic_mark_white" />

                    <TextView
                        android:id="@+id/email_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="13dp"
                        android:layout_marginTop="3dp"
                        android:layout_toRightOf="@+id/email_icon"
                        android:text="Email" />

                    <EditText
                        android:id="@+id/emailSms"
                        android:layout_width="222dp"
                        android:layout_height="28dp"
                        android:layout_marginLeft="15dp"
                        android:layout_toRightOf="@+id/email_text"
                        android:background="@drawable/edittext_border_curve"
                        android:inputType="textEmailAddress"
                        android:paddingLeft="5dp"
                        android:text="bejo@gmail.com"
                        android:textColor="@color/colorBlack"
                        android:textSize="@dimen/text_size_small" />
                </RelativeLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:orientation="horizontal">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="15dp">

                    <Button
                        android:id="@+id/submit_btn"
                        android:layout_width="148dp"
                        android:layout_height="30dp"
                        android:layout_centerInParent="true"
                        android:background="@drawable/curve_corner"
                        android:gravity="center"
                        android:text="Kirim"
                        android:textAllCaps="false"
                        android:textColor="@color/colorWhite"
                        android:textSize="@dimen/text_size_small" />
                </RelativeLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

But problem is, when I launch, it always displays only from recycler list  when there is more items and it's not displaying from top of recycler view items ie from above recyclerview layouts (titles).

In code,

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setNestedScrollingEnabled(false); // i used only this..
        recyclerView.setAdapter(adapter);

recycler_item_rows.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
    android:layout_marginTop="12dp"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:weightSum="2">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="8dp">

                <ImageView
                    android:id="@+id/recycle_profile"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="16dp"
                    android:src="@drawable/ic_tag" />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:layout_gravity="center"
                    android:layout_marginLeft="16dp"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/recycle_txt_acc_num"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:ellipsize="end"
                        android:maxLines="1"
                        android:singleLine="false"
                        android:text="Sell in"
                        android:textColor="@color/colorBlack"
                        android:textSize="@dimen/text_size_small" />

                    <TextView
                        android:id="@+id/recycle_txt_acc_name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:ellipsize="end"
                        android:maxLines="1"
                        android:singleLine="false"
                        android:text="Selli Cell"
                        android:textColor="?attr/colorUserGroup"
                        android:textSize="@dimen/text_size_very_small" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>

        <TextView
            android:id="@+id/timestamp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="21dp"
            android:layout_marginTop="12dp"
            android:gravity="center"
            android:text="12/11/2017 1.30"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/text_size_very_small" />
    </RelativeLayout>
</LinearLayout>

Kindly correct my mistake to display from top.

Here is my output:

Where it's not displaying from top. And I need to manually scroll to top.


问:
WinAPI - Problem to append text to an editbox
I created a simple window with a multiline Edit Control:

```<code>Edit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), NULL,
                    WS_CHILD | WS_VISIBLE | ES_MULTILINE,
                    20, 200, 200, 200,
                    hWnd, (HMENU)EDIT, GetModuleHandle(NULL), NULL);
</code>```

If I set text using a WM_SETTEXT message, I don't get errorrs, but if I use EM_REPLACESEL
I get Error 5 (ERROR_ACCESS_DENIED):

```<code>SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}
</code>```

Same problem with EM_SETSEL:

```<code>SendMessage(GetDlgItem(hWnd, EDIT), EM_SETSEL, (WPARAM)(0),(LPARAM)(-1));
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}
</code>```

I noticed that if I send a WM_SETFOCUS message before the EM_REPLACESEL there are no error:

```<code>SendMessage(GetDlgItem(hWnd, EDIT), WM_SETFOCUS, (WPARAM)GetDlgItem(hWnd, EDIT), 0);
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* NO ERRORS */
}
</code>```

How can I resolve this problem?
Do I have to send a WM_SETFOCUS message before the EM_REPLACESEL one every time I want to append some text to my Editbox?

Thanks for help!

答: Notice that EM_SETSEL, EM_REPLACESEL, etc. act on the caret; if the focus is not on the control, it has no caret, and these messages won't work. Either your user has to click on the control to make it gain the focus, or you have to do WM_SETFOCUS first. Unfortunately that's how the control works, it has no memory of the selection after it loses focus (and neither can have one before it gains it).</p>

Body:
I created a simple window with a multiline Edit Control:

Edit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), NULL,
                    WS_CHILD | WS_VISIBLE | ES_MULTILINE,
                    20, 200, 200, 200,
                    hWnd, (HMENU)EDIT, GetModuleHandle(NULL), NULL);

If I set text using a WM_SETTEXT message, I don't get errorrs, but if I use EM_REPLACESEL
I get Error 5 (ERROR_ACCESS_DENIED):

SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}

Same problem with EM_SETSEL:

SendMessage(GetDlgItem(hWnd, EDIT), EM_SETSEL, (WPARAM)(0),(LPARAM)(-1));
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}

I noticed that if I send a WM_SETFOCUS message before the EM_REPLACESEL there are no error:

SendMessage(GetDlgItem(hWnd, EDIT), WM_SETFOCUS, (WPARAM)GetDlgItem(hWnd, EDIT), 0);
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* NO ERRORS */
}

How can I resolve this problem?
Do I have to send a WM_SETFOCUS message before the EM_REPLACESEL one every time I want to append some text to my Editbox?

Thanks for help!


问:
What else is required to allow CORS on incoming requests in Angular 2/4 app on S3 buckets
We've an Angular 2/4 web app running on AWS S3 buckets. We wanted to allow any * 3rd party website to access it's assets viz. .css, .js, .images etc.

The 3rd party website is supposed to embed a code like this:

```<code><script src="http://angular2-4-app.domain/widget.js"></script>
</code>```

The widget.js file internally calls other assets viz. .css, .js, .images etc.

For example:

```<code>var n=document.createElement("script");
n.setAttribute("type","text/javascript");
n.setAttribute("src","folder1/asset1.js");
n.async="async";
</code>```

The green line represent the requests in which the assets are served back to the 3rd party website which is not happening currently.

The red line represent the requests in which the assets are not served back to the 3rd party website which is happening currently because of CORS issues.

We wanted to achieve the green line requests.

The CORS seems to be enabled on them from the AWS console:

We need a solution like CORS in node.js

What else is required to enable CORS in this case?

答:
The reason is this CORS Common Request Header:

```<code><AllowedHeader>Authorization</AllowedHeader>
</code>```

Common Request Headers

Basically the way you have your CORS policy written is that the only header supported is Authorization. Example:

```<code>Authorization: AWS AWSAccessKeyId:Signature
</code>```

The solution is to change it to:

```<code><AllowedHeader>*</AllowedHeader>
</code>```

Cross-Origin Resource Sharing (CORS)

Body:
We've an Angular 2/4 web app running on AWS S3 buckets. We wanted to allow any * 3rd party website to access it's assets viz. .css, .js, .images etc.

The 3rd party website is supposed to embed a code like this:

The widget.js file internally calls other assets viz. .css, .js, .images etc.

For example:

var n=document.createElement("script");
n.setAttribute("type","text/javascript");
n.setAttribute("src","folder1/asset1.js");
n.async="async";

The green line represent the requests in which the assets are served back to the 3rd party website which is not happening currently.

The red line represent the requests in which the assets are not served back to the 3rd party website which is happening currently because of CORS issues.

We wanted to achieve the green line requests.

The CORS seems to be enabled on them from the AWS console:

We need a solution like CORS in node.js

What else is required to enable CORS in this case?

Body:
The reason is this CORS Common Request Header:

<AllowedHeader>Authorization</AllowedHeader>

Common Request Headers

Basically the way you have your CORS policy written is that the only header supported is Authorization. Example:

Authorization: AWS AWSAccessKeyId:Signature

The solution is to change it to:

<AllowedHeader>*</AllowedHeader>

Cross-Origin Resource Sharing (CORS)


问:
Got “Blocked:mixed content” on HTTPS website
What is the current behavior?

I'm Running a Website using Webpack in Production.

I was surprised to see in Chrome console the following error about loading the js file which is mixed with weback and laravel-mix

My questions:

How can we have a mixed content on a website loaded using HTTPS protocol?

How can I fix the error? I don't plan to serve website over HTTP and I want my js to load properly both in development and production.

答:
From MDN documentation on mixed content

To fix this type of error, all requests to HTTP content should be
  removed and replaced with content served over HTTPS. Some common
  examples of mixed content include JavaScript files, stylesheets,
  images, videos, and other media.


问:
Unexpected error from external database driver (1) in .NET WebAPI hosted on Azure app services
I have a .NET C# web api application hosted inside Azure App Services. This api reads .xls files from blob storage and stores it inside sql database. I am using following connection string to connect to .xls file.

var connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fpath + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;Importmixedtypes=text;typeguessrows=0;\"";

Last week everything was working properly but now I am getting following error

Unexpected error from external database driver (1)

I also tried to change provider from Microsoft.Jet.OLEDB.4.0 to Microsoft.ACE.OLEDB.12.0 in connection string but I found that it is not supported in Azure App Services. MSDN link

I have not changed any code related to this issue. I think the problem is from Microsoft side, they might have run some security updates.

How should I get it fixed. I need help.

答:
According to this blog, it seems that it is caused by OS update. If you are host in the Azure WebApp, please have a try to connect to Azure support. As the WebApp is the Sandbox, we have no access to change the registry or install the  Microsoft.ACE.OLEDB.12.0 for it.

The JET provider is no longer able to connect after the October update. This update (released October 10th, 2017) includes a security update release that inadvertently affects the JET provider. The update was kb4041678 and included in the patch kb4041681

I also create a new Azure WebApp to use Microsoft.Jet.OLEDB.4.0 to read xls file, it also doesn't work on the Azure website.

If other way to read .xls in the Azure WebApp is acceptable, you could use OpenXml SDK. How to use the OpenXml SDK, you could refer to this document.


问:
How do I use a DataFrame to conditionally create documents using Jinja?
For each row in a DataFrame I would like to print out some values for an avro schema. I have a DataFrame that looks something like this.

```<code>import pandas as pd

x = pd.DataFrame({'column' : ['id','type','time']
    , 'desc': ['the sk',' the type' , 'epoch time']
    ,'nullable':[False, False, True]})

print x
</code>```

For each row in the DataFrame I would like to create inputs for a Jinja template

So my output would look something like:

```<code>{
name       : "id"
description: "the sk"
}
{
name       :"type"
description:"the type"
}
{
name       :"time","null"
description:"epoch time"
}
</code>```

How can I do that? I would also like to nest results conditionally based on other column values from my dataframe.

答:
I think transforming the DataFrame to a dict is the solution. I use orient='records' to get a dict suitable for rendering.

```<code>from jinja2 import Template

# Template definition
template = Template("""{% for row in data %}
{
name:  {{ row['column'] }}{{ ', null' if row['nullable'] }}
description: {{ row['desc'] }}
}
{% endfor %}""")

# Rendering
print(template.render(name='John Doe', data=x.to_dict(orient='records')))

# {
# name:  id
# description: the sk
# }
#
# {
# name:  type
# description:  the type
# }
#
# {
# name:  time, null
# description: epoch time
# }
</code>```

Body:
For each row in a DataFrame I would like to print out some values for an avro schema. I have a DataFrame that looks something like this.

import pandas as pd

x = pd.DataFrame({'column' : ['id','type','time']
    , 'desc': ['the sk',' the type' , 'epoch time']
    ,'nullable':[False, False, True]})

print x

For each row in the DataFrame I would like to create inputs for a Jinja template

So my output would look something like:

{
name       : "id"
description: "the sk"
}
{
name       :"type"
description:"the type"
}
{
name       :"time","null"
description:"epoch time"
}

How can I do that? I would also like to nest results conditionally based on other column values from my dataframe.

Body:
I think transforming the DataFrame to a dict is the solution. I use orient='records' to get a dict suitable for rendering.

from jinja2 import Template

# Template definition
template = Template("""{% for row in data %}
{
name:  {{ row['column'] }}{{ ', null' if row['nullable'] }}
description: {{ row['desc'] }}
}
{% endfor %}""")

# Rendering
print(template.render(name='John Doe', data=x.to_dict(orient='records')))

# {
# name:  id
# description: the sk
# }
#
# {
# name:  type
# description:  the type
# }
#
# {
# name:  time, null
# description: epoch time
# }


问:
Virtual machine management
I'm looking for a VM management solution that will allow me to easily maintain VMs in a single repository accessible on the corporate intranet.

I'm currently looking into VMware's vCenter, HP's Manager, Microsoft's VM Manager.  vCenter seems to require an ESX server, which I'm not very happy about.  I haven't looked into others yet.

But can anyone suggest a good/simple solution to this?  I'm looking for a bit more than just SAN space for the VMs, but at the same time I don't want to run a whole ESX server for this.  Any ideas, suggestions?

答:
Whether you were to go with VMware ESXi (the free edition of ESX) or the full-blown ESX is a business and maintainability decision.

Personally, the cost of the license for ESX to ensure I had the administrative tools, support, and maintenance is worth it in a corporate environment.

If it were my personal computer collection, then I'd go with ESXi because I don't have a reason to need the support and admin tools provided with a full ESX license.

The $2640 cost for a license to also get support for 3 years is pretty small in my book.

(http://store.vmware.com/servlet/ControllerServlet?Action=DisplayPage&Env=BASE&Locale=en_US&SiteID=vmware&id=ProductDetailsPage&productID=83581600)

Title: Virtual machine management

OwnerDisplayName: warren


问:
Hosting Sharepoint and SQL Server off same server
Is it possible to host Sharepoint and SQL Server off the same server for small time testing. Environment would be set up for purely education purposes. Non-production. Thanks.</p>

答:
It is possible, but SQL server likes to use up all the RAM, making sharepoint really slow, and sometimes with sharepoint 2010 it crashes the web application.

Try to limit how much RAM sql server takes

http://blog.stevehorn.cc/2007/10/limit-memory-usage-in-sql-server-2005.html


问:
State in componentDidMount always null, there should be data from the task variable
I have a problem, every i call state "modalData" in componentDidMount, state always null, there should be data from the task variable.</p>

```<code>constructor(props){
    super(props);
    this.tasksRef = firebase.database().ref('/users/'+ this.props.card_id);
    this.state = {
        modalData : null,
    }
}

componentDidMount(tasksRef){
    var task = [];
    tasksRef.on('value', (dataSnapshot) => {
        task.push({
            about : dataSnapshot.val().about,
            card : dataSnapshot.val().card,
            company : dataSnapshot.val().company,
            first_name : dataSnapshot.val().first_name,
            job_title : dataSnapshot.val().job_title,
            last_name : dataSnapshot.val().last_name,
            photo : dataSnapshot.val().photo,
            role : dataSnapshot.val().role,
            thumbnail : dataSnapshot.val().thumbnail,
            title : dataSnapshot.val().title,
            website : dataSnapshot.val().website,
            _key : dataSnapshot.key
        });
        console.log('dataSnapshot.val().first_name : ' + dataSnapshot.val().first_name);
    });
    console.log(task); //there is data
    this.setState({
        modalData : task,
    });
    console.log(this.state.modalData); //there is no data
}
</code>```

答:
setState is asynchronous, so you'll need to add a callback to display the console.log i.e.,:

```<code>this.setState({ modalData: task }, () => console.log(this.state));
</code>```

setState Docs

Body:
I have a problem, every i call state "modalData" in componentDidMount, state always null, there should be data from the task variable.

constructor(props){
    super(props);
    this.tasksRef = firebase.database().ref('/users/'+ this.props.card_id);
    this.state = {
        modalData : null,
    }
}

componentDidMount(tasksRef){
    var task = [];
    tasksRef.on('value', (dataSnapshot) => {
        task.push({
            about : dataSnapshot.val().about,
            card : dataSnapshot.val().card,
            company : dataSnapshot.val().company,
            first_name : dataSnapshot.val().first_name,
            job_title : dataSnapshot.val().job_title,
            last_name : dataSnapshot.val().last_name,
            photo : dataSnapshot.val().photo,
            role : dataSnapshot.val().role,
            thumbnail : dataSnapshot.val().thumbnail,
            title : dataSnapshot.val().title,
            website : dataSnapshot.val().website,
            _key : dataSnapshot.key
        });
        console.log('dataSnapshot.val().first_name : ' + dataSnapshot.val().first_name);
    });
    console.log(task); //there is data
    this.setState({
        modalData : task,
    });
    console.log(this.state.modalData); //there is no data
}

Body:
setState is asynchronous, so you'll need to add a callback to display the console.log i.e.,:

this.setState({ modalData: task }, () => console.log(this.state));

setState Docs


问:
angular "Expression has changed after it was checked error" using moment.js

Expression has changed after it was checked. Previous value: '25 minutes ago'. Current value: '26 minutes ago'.

I am attempting to show moment based times in my angular 4 component.

Component Markup

```<code><div class="float-right">
    <small *ngIf="!isInProgress(batch)" class="text-muted"
    [textContent]="getMomentEndTime(batch)"></small>
</div>
</code>```

Component

```<code>export class BatchStatusComponent {
@Input() batchStatuses: BatchStatus[];

constructor(
    private readonly logger: NGXLogger) {
}

isInProgress(batch) {
    var estimate = batch.percentCompleted || 0;
    return (estimate > 0 && estimate < 100);
}

getMomentEndTime(batch: BatchStatus) {
    return (batch.endTime)
        ? moment(batch.endTime).fromNow()
        : "";
}
</code>```

Clearly the value is changing as time progresses, so no surprises there?

答:
The error itself is harmless and indicates that something may go wrong on change detection. If this is expected, the error can be safely ignored.

The error is caused by the fact that the value has changed during change detection cycle. This can be improved by throttling the method:

```<code>throttledGetMomentEndTime = _.throttle(this.getMomentEndTime, 100);
</code>```

Alternatively, the code can be refactored to use pure pipe to convert time to ... minutes ago string, like amTimeAgo pipe from angular2-moment package.

The fact that it is possible to see this error more or less often may suggest that change detection cycles occur too often. Additionally, the amount of change detection cycles can be reduced by setting OnPush change detection strategy for the component, if it fits the case.

Body:
Expression has changed after it was checked. Previous value: '25 minutes ago'. Current value: '26 minutes ago'.

I am attempting to show moment based times in my angular 4 component.

Component Markup

Component

export class BatchStatusComponent {
@Input() batchStatuses: BatchStatus[];

constructor(
    private readonly logger: NGXLogger) {
}

isInProgress(batch) {
    var estimate = batch.percentCompleted || 0;
    return (estimate > 0 && estimate < 100);
}

getMomentEndTime(batch: BatchStatus) {
    return (batch.endTime)
        ? moment(batch.endTime).fromNow()
        : "";
}

Clearly the value is changing as time progresses, so no surprises there?

Body:
The error itself is harmless and indicates that something may go wrong on change detection. If this is expected, the error can be safely ignored.

The error is caused by the fact that the value has changed during change detection cycle. This can be improved by throttling the method:

throttledGetMomentEndTime = _.throttle(this.getMomentEndTime, 100);

Alternatively, the code can be refactored to use pure pipe to convert time to ... minutes ago string, like amTimeAgo pipe from angular2-moment package.

The fact that it is possible to see this error more or less often may suggest that change detection cycles occur too often. Additionally, the amount of change detection cycles can be reduced by setting OnPush change detection strategy for the component, if it fits the case.


问:
Clearing Javascript basics regarding variables

console.log(x);
x = 20;```

the value returned on the console is undefined.
I was expecting a value of 20 or a reference error.
Why is that so??

答:
Well, this is a old trick, first print a variable, then set its value.
To solve this you should first set the x, then console.log like this:

```<code>x=20;
console.log(x);
</code>```

and what is happening with your question is:

Initially:
The value of x is undefined

Log:

Console.log(x); //this will print a empty line, because x is here undefined yet

Set variable x to 20:

x=20; //the x is set, but without use.

Body:
console.log(x);
x = 20;

the value returned on the console is undefined.
I was expecting a value of 20 or a reference error.
Why is that so??

Body:
Well, this is a old trick, first print a variable, then set its value.
To solve this you should first set the x, then console.log like this:

x=20;
console.log(x);

and what is happening with your question is:

Initially:
The value of x is undefined

Log:

Console.log(x); //this will print a empty line, because x is here undefined yet

Set variable x to 20:

x=20; //the x is set, but without use.


问:
Custom Translucent Color (changing transparency)
I am trying to achieve brighter translucent status bar ,only the status bar and trying to keep navigation bar as its default.

I tried some solutions(actually non of them worked as what i want).

In this one i couldn't change translucent transparency, i am trying to get brighter one.But it is not changing.

http://blog.raffaeu.com/archive/2015/04/11/android-and-the-transparent-status-bar.aspx

The other option, i tried to use fullscreen theme and placed a gradient view same height as status(that is what i want). But in this time Layout extends behind of navigation and navigation looses its black background.I couldn't find solution for that.(making it translucent not what i want)

TLDR : i am trying to get brighter translucent status with keeping navigation as its default. Is it possible?

Edit. min SDK is 20
(sorry for bad english)

答:
Yes, it is possibile.

Set the translucent status

```<code><style name="AppThemeTranslucent" parent="Theme.AppCompat.Light.NoActionBar">
      <item name="android:windowTranslucentStatus">true</item>
      <item name="android:windowTranslucentNavigation">true</item>
</style>
</code>```

Set a color for your status bar using:

```<code>@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setTrasparentStatusBar() {
Window window = getWindow();
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

    window.setStatusBarColor(ContextCompat.getColor(this, R.color.status_bar_color));

    window.setNavigationBarColor(ContextCompat.getColor(this, android.R.color.black));
}
</code>```

Add this property to you root layout

```<code>android:fitsSystemWindows="true"
</code>```

And this is what I achieve with this code

EDIT

I investigated about this feature, not all the view implement fitsSystemWindows so not always you can get this results.

I suggest you to read this and here a repo with a sample using a CoordinatorLayout with a negative marginTop

Body:
Yes, it is possibile.

Set the translucent status

<style name="AppThemeTranslucent" parent="Theme.AppCompat.Light.NoActionBar">
      <item name="android:windowTranslucentStatus">true</item>
      <item name="android:windowTranslucentNavigation">true</item>
</style>

Set a color for your status bar using:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setTrasparentStatusBar() {
Window window = getWindow();
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

    window.setStatusBarColor(ContextCompat.getColor(this, R.color.status_bar_color));

    window.setNavigationBarColor(ContextCompat.getColor(this, android.R.color.black));
}

Add this property to you root layout

android:fitsSystemWindows="true"

And this is what I achieve with this code

EDIT

I investigated about this feature, not all the view implement fitsSystemWindows so not always you can get this results.

I suggest you to read this and here a repo with a sample using a CoordinatorLayout with a negative marginTop


问:
Content type check for uploading APK file in JAVA
How to check if user is actually uploading APK file in java.

By checking only the extension of file user can rename any file(Eg:TXT file) to apk and upload.

I tried to check the contentType of the particular file as shown below:

```<code>if(apkFile.getContentType().equals("application/vnd.android.package-archive"))
</code>```

But here the problem is when upload from some browser the content type comes as application/vnd.android.package-archive but for some others its application/octet-stream.

What is the proper way to check this?

答: Apk is formated in zip,so you could check whether it's a zip file to decrease  the probability that it' not an apk file ,in addtion to checking the file extension.After all ,not all of the marplots change file extensions only from zip to apk

Body:
How to check if user is actually uploading APK file in java.

By checking only the extension of file user can rename any file(Eg:TXT file) to apk and upload.

I tried to check the contentType of the particular file as shown below:

if(apkFile.getContentType().equals("application/vnd.android.package-archive"))

But here the problem is when upload from some browser the content type comes as application/vnd.android.package-archive but for some others its application/octet-stream.

What is the proper way to check this?


问:
Efficiently selecting latest charge per patient
I've got three tables in SQL Server 2005 (relevant rows included):

```<code>Patient (560K rows, has many Appts)
    ID (PK, Clustered)
Appt (5.8M rows, has many ApptCPTs)
    ID (PK, Unique, Non-clustered)
    PatientID (Indexed, Non-unique, Non-clustered)
ApptCPT (13.4M rows)
    ID (PK, Clustered)
    ApptID (Indexed, Non-unique, Non-clustered)
    CPTID (Indexed, Non-unique, Non-clustered)
</code>```

I want to get the latest ApptCPT for each CPT code, for each patient, but the query I've got so far takes about a minute to return ~7M rows.

My current query:

```<code>SELECT
    p.ID AS PatientID,
    MAX(ac.ID) AS ApptCPTID,
    ac.CPTID
FROM
    Patient p
INNER JOIN Appt a ON a.PatientID = p.ID
INNER JOIN ApptCPT ac ON ac.ApptID = a.ID
GROUP BY
    p.ID, ac.CPTID
ORDER BY
    p.ID, ac.CPTID
</code>```

Example output:

```<code>PatientID    ApptCPTID    CPTID
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258166      77080
123456789    18627813     80053
123456789    18627814     80061
</code>```

If I take the MAX out and put ac.ID in the GROUP BY clause, I can see that I'm getting the correct data with my original query, because it's getting the last ApptCPT containing that CPTID for that patient, but it's horribly slow. For reference, here's the same output not using the MAX clause:

```<code>PatientID    ApptCPTID    CPTID
123456789    18126508     3088
123456789    4596004      3088
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    4595928      3551
123456789    9989218      3551
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258050      77057
123456789    5258166      77080
123456789    4595932      80053
123456789    18126505     80053
123456789    9989223      80053
123456789    18627813     80053
123456789    18627814     80061
</code>```

Anyone have any ideas for making it (hopefully) much, much faster?

答:
First of all, if you can possibly change the database, I would encourage the removal of the ID column from ApptCPT. It's useless, and even if kept as a PK it's a bad idea to make it the clustered index. Instead, I think the table should be clustered on ApptID and CPTID (whichever one first that is accessed most often). Then put an index on the one that is second in the list.

I do not think that you should add Patient to the Appt table if ApptID already fully implies patient. The reason for this is that doing so violates normalization rules, allowing an ApptCPT row to simultaneously point to a patient and an appointment that are not related. You would be mixing two different levels/granularities of data in doing so.

It also seems to me that a ton of pain can be avoided if you don't name columns "ID" because then you don't have to deal with aliasing and column confusion. It took some real staring to figure out the below query for you because there were so many ID columns. Name columns the same everywhere they are used!

Your query is probably already the fastest it can be. If you had an index on ApptCPT with both CPTID and ApptID in it, then it would be a covering index and the main table could be completely avoided, which could speed up your query (because as it is now the engine has to access indexes twice from that table). What does your execution plan look like? Are you getting seeks or scans or what?

Also, why do you need to return 7 million rows? This can't be for a user sitting there ready to consume it, so I don't see why a 1 minute response time is all that bad.

If you were only going to be selecting certain patients or certain CPTs, then this query could be an improvement over the entire-table query. But if you do need all 7 million rows, this is probably going to perform abysmally:

```<code>SELECT
   P.ID PatientID,
   X.ID ApptCPTID,
   X.CPTID
FROM
   Patient P
   CROSS JOIN CPTs C -- your master CPT table listing all CPTs
   CROSS APPLY (
      SELECT TOP 1 AC.ID, AC.CPTID
      FROM
         Appt A
         INNER JOIN ApptCPT AC ON A.ID = AC.ApptID
      WHERE
         A.PatientID = P.ID
         AND C.CPTID = AC.CPTID
      ORDER BY AC.ID DESC
   ) X
WHERE
   P.Something = 'Z'
   AND CPT.Code IN ('A', 'B')
</code>```

However, one benefit of this query is that the column you use to choose the latest item doesn't have to be the one in the SELECT clause. You could say ORDER BY AC.Date DESC if you wanted. I don't know enough about what you're doing to really know for sure, but that could be important to you.

Note: I just realized that the CROSS JOIN with OUTER APPLY would have returned a bunch of spurious rows. So I switched it to CROSS APPLY and everything should be okay. There's probably something else that could be done to make nonqualifying patients included but I don't have time to think about it right now.

Body:
I've got three tables in SQL Server 2005 (relevant rows included):

Patient (560K rows, has many Appts)
    ID (PK, Clustered)
Appt (5.8M rows, has many ApptCPTs)
    ID (PK, Unique, Non-clustered)
    PatientID (Indexed, Non-unique, Non-clustered)
ApptCPT (13.4M rows)
    ID (PK, Clustered)
    ApptID (Indexed, Non-unique, Non-clustered)
    CPTID (Indexed, Non-unique, Non-clustered)

I want to get the latest ApptCPT for each CPT code, for each patient, but the query I've got so far takes about a minute to return ~7M rows.

My current query:

SELECT
    p.ID AS PatientID,
    MAX(ac.ID) AS ApptCPTID,
    ac.CPTID
FROM
    Patient p
INNER JOIN Appt a ON a.PatientID = p.ID
INNER JOIN ApptCPT ac ON ac.ApptID = a.ID
GROUP BY
    p.ID, ac.CPTID
ORDER BY
    p.ID, ac.CPTID

Example output:

PatientID    ApptCPTID    CPTID
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258166      77080
123456789    18627813     80053
123456789    18627814     80061

If I take the MAX out and put ac.ID in the GROUP BY clause, I can see that I'm getting the correct data with my original query, because it's getting the last ApptCPT containing that CPTID for that patient, but it's horribly slow. For reference, here's the same output not using the MAX clause:

PatientID    ApptCPTID    CPTID
123456789    18126508     3088
123456789    4596004      3088
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    4595928      3551
123456789    9989218      3551
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258050      77057
123456789    5258166      77080
123456789    4595932      80053
123456789    18126505     80053
123456789    9989223      80053
123456789    18627813     80053
123456789    18627814     80061

Anyone have any ideas for making it (hopefully) much, much faster?

Body:
First of all, if you can possibly change the database, I would encourage the removal of the ID column from ApptCPT. It's useless, and even if kept as a PK it's a bad idea to make it the clustered index. Instead, I think the table should be clustered on ApptID and CPTID (whichever one first that is accessed most often). Then put an index on the one that is second in the list.

I do not think that you should add Patient to the Appt table if ApptID already fully implies patient. The reason for this is that doing so violates normalization rules, allowing an ApptCPT row to simultaneously point to a patient and an appointment that are not related. You would be mixing two different levels/granularities of data in doing so.

It also seems to me that a ton of pain can be avoided if you don't name columns "ID" because then you don't have to deal with aliasing and column confusion. It took some real staring to figure out the below query for you because there were so many ID columns. Name columns the same everywhere they are used!

Your query is probably already the fastest it can be. If you had an index on ApptCPT with both CPTID and ApptID in it, then it would be a covering index and the main table could be completely avoided, which could speed up your query (because as it is now the engine has to access indexes twice from that table). What does your execution plan look like? Are you getting seeks or scans or what?

Also, why do you need to return 7 million rows? This can't be for a user sitting there ready to consume it, so I don't see why a 1 minute response time is all that bad.

If you were only going to be selecting certain patients or certain CPTs, then this query could be an improvement over the entire-table query. But if you do need all 7 million rows, this is probably going to perform abysmally:

SELECT
   P.ID PatientID,
   X.ID ApptCPTID,
   X.CPTID
FROM
   Patient P
   CROSS JOIN CPTs C -- your master CPT table listing all CPTs
   CROSS APPLY (
      SELECT TOP 1 AC.ID, AC.CPTID
      FROM
         Appt A
         INNER JOIN ApptCPT AC ON A.ID = AC.ApptID
      WHERE
         A.PatientID = P.ID
         AND C.CPTID = AC.CPTID
      ORDER BY AC.ID DESC
   ) X
WHERE
   P.Something = 'Z'
   AND CPT.Code IN ('A', 'B')

However, one benefit of this query is that the column you use to choose the latest item doesn't have to be the one in the SELECT clause. You could say ORDER BY AC.Date DESC if you wanted. I don't know enough about what you're doing to really know for sure, but that could be important to you.

Note: I just realized that the CROSS JOIN with OUTER APPLY would have returned a bunch of spurious rows. So I switched it to CROSS APPLY and everything should be okay. There's probably something else that could be done to make nonqualifying patients included but I don't have time to think about it right now.