问:
scroll bar should be at bootom without setInterval()
I want to keep my scroll bar each time user send or receive a new message .

```<code><script>
$ = jQuery;
var currentID = null;
var chatTimer = null;
var scrolled;

function fetch_data() {
  $.ajax({
    url: "select.php",
    method: "POST",
    success: function(data) {
      $('#live_data').html(data);
     }
  });
}

function fetch_chat() {

  $.ajax({
    url: "fetch_chat.php",
    method: "POST",
    data: {
      id: currentID
    },
    dataType: "text",
    success: function(data) {
      $("#chatbox").show();
      $('#messages').html(data);
      $("div.area").show();
      if(!scrolled){
      $('#messages').scrollTop($('#messages')[0].scrollHeight);
      scrolled=true;
      }
    }

  });

}

$(document).ready(function() {

 fetch_data();

  $(document).on('click', '.first_name', function() {
      scrolled=false;
    currentID = $(this).data("id1");
    fetch_chat();
});

  $("#sub").click(function() {

    var text = $("#text").val();
    $.post('insert_chat.php', {
      id: currentID,
      msg: text
    }, function(data) {
      $("#messages").append(data);
      $("#text").val('');
      scrolled=false;
      setInterval(function() {
    fetch_chat();}, 500);
    });
  });

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

what I want is that whenever a user send or receive a new message the scroll  bar should come to bottom but it should be scrollable according to user's desire. the setinterval() bring the scroll bar down whenever its scrolled up .
I want to call the fetch_chat() repeatedly but not the scroll bar ,I want it to be at bottom : at the beginning,after sending or receiving a new message and must be scrollable freely.

答:
Basic logic of the following answer:

Compare the current chat HTML with the previous chat HTML, and if they are different, then scroll, if they are the same, then don't.

```<code><script>
$ = jQuery;
var currentID = null,
    chatTimer = null,
    oldHtml = "";

function fetch_data() {
  $.ajax({
    url: "select.php",
    method: "POST",
    success: function(data) {
      $('#live_data').html(data);
     }
  });
}

function fetch_chat() {

  $.ajax({
    url: "fetch_chat.php",
    method: "POST",
    data: {
      id: currentID
    },
    dataType: "text",
    success: function(data) {
      $("#chatbox").show();
      $('#messages').html(data);
      $("div.area").show();
      if (oldHtml !== data) {
        $('#messages').scrollTop($('#messages')[0].scrollHeight);
      }
      oldHtml = data;
    }

  });

}

$(document).ready(function() {

 fetch_data();

  $(document).on('click', '.first_name', function() {
    currentID = $(this).data("id1");
    fetch_chat();
});

  $("#sub").click(function() {

    var text = $("#text").val();
    $.post('insert_chat.php', {
      id: currentID,
      msg: text
    }, function(data) {
      $("#messages").append(data);
      $("#text").val('');
      setInterval(fetch_chat, 500);
    });
  });

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

Body:
I want to keep my scroll bar each time user send or receive a new message .

what I want is that whenever a user send or receive a new message the scroll  bar should come to bottom but it should be scrollable according to user's desire. the setinterval() bring the scroll bar down whenever its scrolled up .
I want to call the fetch_chat() repeatedly but not the scroll bar ,I want it to be at bottom : at the beginning,after sending or receiving a new message and must be scrollable freely.

Body:
Basic logic of the following answer:

Compare the current chat HTML with the previous chat HTML, and if they are different, then scroll, if they are the same, then don't.

<script>
$ = jQuery;
var currentID = null,
    chatTimer = null,
    oldHtml = "";

function fetch_data() {
  $.ajax({
    url: "select.php",
    method: "POST",
    success: function(data) {
      $('#live_data').html(data);
     }
  });
}

function fetch_chat() {

  $.ajax({
    url: "fetch_chat.php",
    method: "POST",
    data: {
      id: currentID
    },
    dataType: "text",
    success: function(data) {
      $("#chatbox").show();
      $('#messages').html(data);
      $("div.area").show();
      if (oldHtml !== data) {
        $('#messages').scrollTop($('#messages')[0].scrollHeight);
      }
      oldHtml = data;
    }

  });

}

$(document).ready(function() {

 fetch_data();

  $(document).on('click', '.first_name', function() {
    currentID = $(this).data("id1");
    fetch_chat();
});

  $("#sub").click(function() {

    var text = $("#text").val();
    $.post('insert_chat.php', {
      id: currentID,
      msg: text
    }, function(data) {
      $("#messages").append(data);
      $("#text").val('');
      setInterval(fetch_chat, 500);
    });
  });

});
</script>


来源: stackexchange

问:
How can I retrieve all users from firebase to a fragment?
I have created a Recycler view in my fragment_add_friends.xml like below

```<code><android.support.v7.widget.RecyclerView
android:id="@+id/all_user_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</code>```

and I created all_user_display_layout.xml file for display each user like below

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

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

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/all_user_image">

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

            <TextView
                android:id="@+id/all_user_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="full name"/>

            <TextView
                android:id="@+id/all_user_status"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="user status"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>
</code>```

In my AddFriendsFragment.java I got the recycler view like below in my on create view method

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_add_friends, container, false);

        all_user_list = (RecyclerView) v.findViewById(R.id.all_user_list);
        all_user_list.setHasFixedSize(true);
        all_user_list.setLayoutManager(new LinearLayoutManager(getActivity()));

        return v;
    }
</code>```

and I have created a helper class that have Strings name, status,
  image and there getters setters and constructor and empty construcor because I have to retrieve those data and xml file those things in is all_user_display_layout.xml

and I got the database reference like below

```<code>databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
</code>```

and I create the onViewCreated method like below

```<code>@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }
</code>```

after that what are the things that I have to do to get data from
  fireabse to recycler view

please help me im new to these stuff

答:
Assuming that users node is a direct child of your Firebase database root, to get the name, image and status, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List <String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            String image = ds.child("image").getValue(String.class);
            String status = ds.child("status").getValue(String.class);
            list.add(name + " / " + image + " / " + status);
            Log.d("TAG", name + " / " + image + " / " + status);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
</code>```

Your output will be:

```<code>Hemal / https... / Busy
Jake Stewart / https... / Busy
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created a Recycler view in my fragment_add_friends.xml like below

<android.support.v7.widget.RecyclerView
android:id="@+id/all_user_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />

and I created all_user_display_layout.xml file for display each user like below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

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

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/all_user_image">

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

            <TextView
                android:id="@+id/all_user_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="full name"/>

            <TextView
                android:id="@+id/all_user_status"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="user status"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

In my AddFriendsFragment.java I got the recycler view like below in my on create view method

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_add_friends, container, false);

        all_user_list = (RecyclerView) v.findViewById(R.id.all_user_list);
        all_user_list.setHasFixedSize(true);
        all_user_list.setLayoutManager(new LinearLayoutManager(getActivity()));

        return v;
    }

and I have created a helper class that have Strings name, status,
  image and there getters setters and constructor and empty construcor because I have to retrieve those data and xml file those things in is all_user_display_layout.xml

and I got the database reference like below

databaseReference = FirebaseDatabase.getInstance().getReference().child("users");

and I create the onViewCreated method like below

@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

after that what are the things that I have to do to get data from
  fireabse to recycler view

please help me im new to these stuff

Body:
Assuming that users node is a direct child of your Firebase database root, to get the name, image and status, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List <String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            String image = ds.child("image").getValue(String.class);
            String status = ds.child("status").getValue(String.class);
            list.add(name + " / " + image + " / " + status);
            Log.d("TAG", name + " / " + image + " / " + status);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);

Your output will be:

Hemal / https... / Busy
Jake Stewart / https... / Busy


问:
How to use MS Ajax PageMethods to call a function on the server
I have a project that uses PageMethods to call functions on the server.
The server functions (written in C#) return the values as array of strings, without doing any kind of serialization and in the client side (from Js) the accessing of the return values is by using static variable called arguments.
I found that sometimes for some users (cases are not repro) sometimes an exception occured

"WebServiceFailedException the server method 'Foo' returned invalid data.
the 'd' property is missing from JSON."

Some searching on google I found that people are serializing the return values using DataContractJsonSerializer class and in js accessing the return value using one of the callback function
Example:

function OnRequestComplete(result,
  userContext, methodName) {

  var Person = eval('(' + result + ')');
  alert(Person.Forename);

  alert(Person.Surname);        }

So is the first technique is correct? or what?

P.S:
the function on the server is defined on the default.aspx.cs file as follows:

```<code>[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] Foo(string s);
</code>```

from the client side the calling is as follows

```<code>PageMethods.Foo("value",OnSuccess);
</code>```

Also all the users have the same browser version (IE8)

答:
I don't know if it's the entire problem, but your first issue is manually serializing the return value.  PageMethods and ScriptServices automatically JSON serialize their return values.  Nesting two levels of JSON could definitely be throwing a wrench in the framework's client-side deserialization process (which is also happening automatically, before your eval() code).

To return an instance of your Person class, this is all you need:

```<code>public static Person GetPerson() {
  Person p = new Person();

  // Populate the Person object here.

  return p;
}
</code>```

Then, on the client-side you can work with the object's properties as expected:

```<code>function OnRequestComplete(result, userContext, methodName) {
  console.log('Person name: ' + result.Forename + ' ' + result.Surname);
}
</code>```

Alternatively, if you're using jQuery for other tasks and already have it on the page, you don't even need the ScriptManager and MS AJAX to call page methods.  You can directly call page methods with jQuery and skip all that overhead.

ContentLicense: CC BY-SA 2.5

Body:
I have a project that uses PageMethods to call functions on the server.
The server functions (written in C#) return the values as array of strings, without doing any kind of serialization and in the client side (from Js) the accessing of the return values is by using static variable called arguments.
I found that sometimes for some users (cases are not repro) sometimes an exception occured

"WebServiceFailedException the server method 'Foo' returned invalid data.
the 'd' property is missing from JSON."

Some searching on google I found that people are serializing the return values using DataContractJsonSerializer class and in js accessing the return value using one of the callback function
Example:

function OnRequestComplete(result,
  userContext, methodName) {

  var Person = eval('(' + result + ')');
  alert(Person.Forename);

  alert(Person.Surname);        }

So is the first technique is correct? or what?

P.S:
the function on the server is defined on the default.aspx.cs file as follows:

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] Foo(string s);

from the client side the calling is as follows

PageMethods.Foo("value",OnSuccess);

Also all the users have the same browser version (IE8)

Body:
I don't know if it's the entire problem, but your first issue is manually serializing the return value.  PageMethods and ScriptServices automatically JSON serialize their return values.  Nesting two levels of JSON could definitely be throwing a wrench in the framework's client-side deserialization process (which is also happening automatically, before your eval() code).

To return an instance of your Person class, this is all you need:

public static Person GetPerson() {
  Person p = new Person();

  // Populate the Person object here.

  return p;
}

Then, on the client-side you can work with the object's properties as expected:

function OnRequestComplete(result, userContext, methodName) {
  console.log('Person name: ' + result.Forename + ' ' + result.Surname);
}

Alternatively, if you're using jQuery for other tasks and already have it on the page, you don't even need the ScriptManager and MS AJAX to call page methods.  You can directly call page methods with jQuery and skip all that overhead.


问:
Can't install sense plugin for Kibana
I am trying to install sense plugin for elasticsearch/kibana.
I have successfully installed Kibana but when following the instruction on https://www.elastic.co/guide/en/sense/current/installing.html
I type :
./kibana plugin --install elastic/sense, on the bin directory inside kibana folder, and I get :

```<code> ERROR  unknown command plugin

  Usage: bin/kibana [command=serve] [options]

  Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.

  Commands:
    serve  [options]  Run the kibana server
    help  <command>   Get the help for a specific command

  "serve" Options:

    -h, --help                 output usage information
    -e, --elasticsearch <uri>  Elasticsearch instance
    -c, --config <path>        Path to the config file, can be changed with the CONFIG_PATH environment variable as well. Use mulitple --config args to include multiple config files.
    -p, --port <port>          The port to bind to
    -q, --quiet                Prevent all logging except errors
    -Q, --silent               Prevent all logging
    --verbose                  Turns on verbose logging
    -H, --host <host>          The host to bind to
    -l, --log-file <path>      The file to log to
    --plugin-dir <path>        A path to scan for plugins, this can be specified multiple times to specify multiple directories
    --plugin-path <path>       A path to a plugin which should be included by the server, this can be specified multiple times to specify multiple paths
    --plugins <path>           an alias for --plugin-dir
</code>```

I can't figure out why I get this error, how can I install sense plugin then ?

答:
Manual Downloaded it
Kibana’s bin/plugin script requires direct internet access for downloading and installing Sense. If your server doesn’t have internet access, you can download the Sense tar file from the following link: https://download.elasticsearch.org/elastic/sense/sense-latest.tar.gz

Once downloaded you can install Sense using the following command:

```<code>$ bin/kibana plugin -i sense -u file:///PATH_TO_SENSE_TAR_FILE
</code>```

ContentLicense: CC BY-SA 4.0

Title: Can't install sense plugin for Kibana

Body:
I am trying to install sense plugin for elasticsearch/kibana.
I have successfully installed Kibana but when following the instruction on https://www.elastic.co/guide/en/sense/current/installing.html
I type :
./kibana plugin --install elastic/sense, on the bin directory inside kibana folder, and I get :

 ERROR  unknown command plugin

  Usage: bin/kibana [command=serve] [options]

  Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.

  Commands:
    serve  [options]  Run the kibana server
    help  <command>   Get the help for a specific command

  "serve" Options:

    -h, --help                 output usage information
    -e, --elasticsearch <uri>  Elasticsearch instance
    -c, --config <path>        Path to the config file, can be changed with the CONFIG_PATH environment variable as well. Use mulitple --config args to include multiple config files.
    -p, --port <port>          The port to bind to
    -q, --quiet                Prevent all logging except errors
    -Q, --silent               Prevent all logging
    --verbose                  Turns on verbose logging
    -H, --host <host>          The host to bind to
    -l, --log-file <path>      The file to log to
    --plugin-dir <path>        A path to scan for plugins, this can be specified multiple times to specify multiple directories
    --plugin-path <path>       A path to a plugin which should be included by the server, this can be specified multiple times to specify multiple paths
    --plugins <path>           an alias for --plugin-dir

I can't figure out why I get this error, how can I install sense plugin then ?

Body:
Manual Downloaded it
Kibana’s bin/plugin script requires direct internet access for downloading and installing Sense. If your server doesn’t have internet access, you can download the Sense tar file from the following link: https://download.elasticsearch.org/elastic/sense/sense-latest.tar.gz

Once downloaded you can install Sense using the following command:

$ bin/kibana plugin -i sense -u file:///PATH_TO_SENSE_TAR_FILE


问:
Oracle SQL statement to select string between '\' and '#'
I have a table in an Oracle 11g database with a column named REPORT. I'm trying to write a select statement that would display the required results below. I need to select the character string between the "\" and the following occurrence of "#". I thought this could be accomplished using the regexp_substr function, but I haven't had any success. I have too many examples of my unsuccessful attempts over the last week to post here. Any help would be appreciated.

REPORT_COLUMN

```<code>#Med Reports\Client, Ray.dco#
Financial Reports\Client, Justin-1.dco#Financial Reports/Client, Justin-1.dco#
#Med Reports\Client, Jessy.dco#
Financial Reports\Client, Channa-1.dco#Financial Reports/Client, Charnisha-1.dco#
</code>```

Required results:

```<code>Client, Ray.dco
Client, Justin-1.dco
Client, Jessy.dco
Client, Channa-1.dco
</code>```

答:
```<code>select regexp_substr(REPORT_COLUMN,'\\(.*?)#',1,1,'',1)
  from Table
</code>```

Body:
I have a table in an Oracle 11g database with a column named REPORT. I'm trying to write a select statement that would display the required results below. I need to select the character string between the "\" and the following occurrence of "#". I thought this could be accomplished using the regexp_substr function, but I haven't had any success. I have too many examples of my unsuccessful attempts over the last week to post here. Any help would be appreciated.

REPORT_COLUMN

#Med Reports\Client, Ray.dco#
Financial Reports\Client, Justin-1.dco#Financial Reports/Client, Justin-1.dco#
#Med Reports\Client, Jessy.dco#
Financial Reports\Client, Channa-1.dco#Financial Reports/Client, Charnisha-1.dco#

Required results:

Client, Ray.dco
Client, Justin-1.dco
Client, Jessy.dco
Client, Channa-1.dco


问:
Javascript: Avoiding multiple pop up boxes / check if div is empty
I created a pop up box that appears when a user clicks a button. Currently I am able to get the box to appear but when the user closes it and re-opens it the code is ran through again and another box is stacked on top of the old one.

What I want to do is make it so no matter how many times the user clicks the box it only shows one box... my thoughts was maybe checking if it was empty similar to How do I check if an HTML element is empty using jQuery? however that has not worked so far.

Any suggestions for a noob idiot? Appreciation for all responses in advance.

```<code><button onclick="popup()">text</button>

<script>
var box = document.getElementById('popupbox');

function popup(){
  box.style.display = "block";
  var content = document.createElement('div');
  content.className = 'boxstyle';
  content.innerHTML = ' ...a handful of tags...';
  box.appendChild(content);}

function exit(){
box.style.display = "none";}
</script>
</code>```

答:
I actually managed to solve it by simply tossing in box.innerHTML = '' right after the block appears so that it has a clean slate to work with. I was trying to go a little more elegant and seeking to use an If/Else statement but in the end it seems to work. Much appreciation for all who answered / commented, you all are awesome!

```<code><button onclick="popup()">text</button>

<script>
var box = document.getElementById('popupbox');

function popup(){
  box.style.display = "block";
  box.innerHTML = '';
  var content = document.createElement('div');
  content.className = 'boxstyle';
  content.innerHTML = ' ...a handful of tags...';
  box.appendChild(content);}

function exit(){
  box.style.display = "none";}
</code>```

Body:
I created a pop up box that appears when a user clicks a button. Currently I am able to get the box to appear but when the user closes it and re-opens it the code is ran through again and another box is stacked on top of the old one.

What I want to do is make it so no matter how many times the user clicks the box it only shows one box... my thoughts was maybe checking if it was empty similar to How do I check if an HTML element is empty using jQuery? however that has not worked so far.

Any suggestions for a noob idiot? Appreciation for all responses in advance.

<button onclick="popup()">text</button>

Body:
I actually managed to solve it by simply tossing in box.innerHTML = '' right after the block appears so that it has a clean slate to work with. I was trying to go a little more elegant and seeking to use an If/Else statement but in the end it seems to work. Much appreciation for all who answered / commented, you all are awesome!

<button onclick="popup()">text</button>

<script>
var box = document.getElementById('popupbox');

function popup(){
  box.style.display = "block";
  box.innerHTML = '';
  var content = document.createElement('div');
  content.className = 'boxstyle';
  content.innerHTML = ' ...a handful of tags...';
  box.appendChild(content);}

function exit(){
  box.style.display = "none";}


问:
Failed to write to file error - ADODB.stream
I want to download files from the internet with a .vbs file. I got the code here: Is it possible to download using the Windows command line?

It uses ADODB.stream to extract the file to my C drive. I ran it on Windows XP SP3    and it worked fine. Then when I tried to run it on Windows 10 I got a "could not write to file" error. I also tried it in CMD with "cscript.exe download.vbs" and the same thing happened. What is the difference between Windows XP and Windows 10 that makes this error? Can it be fixed?

Here is the exact code:

```<code>strFileURL = "http://www.it1.net/images/it1_logo2.jpg"
strHDLocation = "c:\logo.jpg"
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0
Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing
objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if
Set objXMLHTTP = Nothing
</code>```

答:
While this might appear to be a programming issue it is in fact related directly to the Operating System. The change you've encountered between Windows XP and Windows 10 is known as User Account Control (first introduced with Windows Vista).

As stated in How do I get permissions to save in a folder that Windows 7 denies me from?

This is due to UAC (User Access/Account Control) On Windows Vista / 7, and trying to write to a protected folder.

In Windows 10 the root of the system drive (usually the drive where the OS is installed) is classed as a Protected Folder.

Accessing Protected Folders requires elevated privileges which when running VBScript through the Windows Scripting Host can be done by starting the command prompt in Administrator Mode (available from the program context menu) and calling the wscript.exe or csscript.exe with the required script path.

Body:
I want to download files from the internet with a .vbs file. I got the code here: Is it possible to download using the Windows command line?

It uses ADODB.stream to extract the file to my C drive. I ran it on Windows XP SP3    and it worked fine. Then when I tried to run it on Windows 10 I got a "could not write to file" error. I also tried it in CMD with "cscript.exe download.vbs" and the same thing happened. What is the difference between Windows XP and Windows 10 that makes this error? Can it be fixed?

Here is the exact code:

strFileURL = "http://www.it1.net/images/it1_logo2.jpg"
strHDLocation = "c:\logo.jpg"
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0
Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing
objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if
Set objXMLHTTP = Nothing


问:
expect: how to send an EOF to spawnd process
I have a program read from stdin and process it. ( like "tee /some/file" )

This program wait stdin end to exit itself.

If I spawn it from Expect, after I send many content, how to send an "EOF" to the program?

there is a close command in Expect, but it will also send a SIGHUP, and can not expect program output anymore.

答:
Expect works (on non-Windows) by using a virtual terminal which the spawned program runs within. This means that you can do things by sending character sequences to simulate keys. In particular, the EOF control sequence is done with Ctrl+D, which becomes the character U+000004. The terminal processes this to turn it into a true EOF.

There's a few ways to write it, depending on which escape sequence you prefer, but one of these will work:

```<code># Hexadecimal-encoded escape
send \x04
</code>```

```<code># Octal-encoded escape
send \004
</code>```

```<code># UNICODE escape (also hexadecimal)
send \u0004
</code>```

```<code># Generate by a command
send [format "%c" 4]
</code>```

When Expect is using Tcl 8.6, these all generate the same bytecode so use whichever you prefer.

Body:
Expect works (on non-Windows) by using a virtual terminal which the spawned program runs within. This means that you can do things by sending character sequences to simulate keys. In particular, the EOF control sequence is done with Ctrl+D, which becomes the character U+000004. The terminal processes this to turn it into a true EOF.

There's a few ways to write it, depending on which escape sequence you prefer, but one of these will work:

# Hexadecimal-encoded escape
send \x04

# Octal-encoded escape
send \004

# UNICODE escape (also hexadecimal)
send \u0004

# Generate by a command
send [format "%c" 4]

When Expect is using Tcl 8.6, these all generate the same bytecode so use whichever you prefer.


问:
Detecting drop into textarea with Javascript
All I need is to be able to detect when text is dropped into a Textarea.  I then take that text and do stuff with it and clear the textarea.  There may be many of these textareas and very high UI expectations, so polling is a last resort.

For IE, "onfocus" does the trick, since this event is fired after the user drops stuff into the textarea.

For Firefox, I can't find an event that works.  I've tried onmouseup and onchange.. don't know what else to try from there.  I'd hate to have to poll the textarea for content.  Help much appreciated.  Thanks.

Edit:  For clarification, "dropped" means the user selects text (usually) from the page, but it doesn't matter where, drags it, and drops it into the textarea.  This is not the same as Ctrl+V, or right click pasting (which take two different methods of detection, BTW), or (obviously) typing into the textarea.  Specifically, it is the "drop" aspect of drag and drop.  I really don't know how else to phrase it.

I feel this question was stated rather accurately.  To humor me, assume that I meant any of the other operations on a textarea that you all have chosen to share.  If I meant "pasting", don't you think I would have mentioned something about pasting in the title or content of my question?  Same goes for typing in a textarea.  But, perhaps, you all just don't know me well enough to know that I type what I mean, rather than mistakingly typing things only somewhat related to what I mean.

答:
For Firefox, this works for me:

```<code>window.addEventHandler("dragdrop", function(event) {alert("Drop it like it's hot!")}, true)
</code>```

Does not work in Safari, however. Haven't tried IE.

OwnerDisplayName: sam

LastEditorDisplayName: sam

Body:
For Firefox, this works for me:

window.addEventHandler("dragdrop", function(event) {alert("Drop it like it's hot!")}, true)

Does not work in Safari, however. Haven't tried IE.

OwnerDisplayName: Chuck

LastEditorDisplayName: Chuck


问:
Core-plot graph rendered upside-down in a different context
I'm using core-plot library to draw graphs. For some animation I have to take the image snapshot of the entire screen in order to make it smooth. The problem is that when I try to get image from the graph. The graph is always upside down. If I took only the graph itself as the snapshot, then it wouldn't be a problem - i could easily apply a transform on it. The problem is, I'm animating the whole screen, so that I take the snapshot of the entire UIWindow which consists the graph in one of its subviews.
I tried it with the coreplot 0.2.2 sample available in coreplot project on code.google. I simply added one button to the window (so that it is visible on each tab), when the button is pressed, I take the image from the window content and save is as an image in the Album library using this code:

```<code>
UIView *window = [[UIApplication sharedApplication] keyWindow];
UIGraphicsBeginImageContext(window.frame.size);
[window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(newImage, nil, NULL, NULL);
</code>```

The result is as described above. Graph in the generated image is rendered upside down compared to the one that is visible on the screen. Do I do sth wrong or that's core-plots bug?

答:
Momentarily changing transform would help only for my animation. Still when putting application to background, Apple does snapshot of the application and here it would still look weird.

What I have done and what worked for me:
I replaced lines:

```<code>self.layer.sublayerTransform = CATransform3DMakeScale(1.0, -1.0, 1.0);
</code>```

from -initWithFrame: and -awakeFromNib in file CPLayerHostingView.m
with the following one:

```<code>self.layer.transform = CATransform3DMakeScale(1.0, -1.0, 1.0);</code>```

Now it works and looks like a charm.

Body:
I'm using core-plot library to draw graphs. For some animation I have to take the image snapshot of the entire screen in order to make it smooth. The problem is that when I try to get image from the graph. The graph is always upside down. If I took only the graph itself as the snapshot, then it wouldn't be a problem - i could easily apply a transform on it. The problem is, I'm animating the whole screen, so that I take the snapshot of the entire UIWindow which consists the graph in one of its subviews.
I tried it with the coreplot 0.2.2 sample available in coreplot project on code.google. I simply added one button to the window (so that it is visible on each tab), when the button is pressed, I take the image from the window content and save is as an image in the Album library using this code:

UIView *window = [[UIApplication sharedApplication] keyWindow];
UIGraphicsBeginImageContext(window.frame.size);
[window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(newImage, nil, NULL, NULL);

The result is as described above. Graph in the generated image is rendered upside down compared to the one that is visible on the screen. Do I do sth wrong or that's core-plots bug?

Body:
Momentarily changing transform would help only for my animation. Still when putting application to background, Apple does snapshot of the application and here it would still look weird.

What I have done and what worked for me:
I replaced lines:

self.layer.sublayerTransform = CATransform3DMakeScale(1.0, -1.0, 1.0);

from -initWithFrame: and -awakeFromNib in file CPLayerHostingView.m
with the following one:

self.layer.transform = CATransform3DMakeScale(1.0, -1.0, 1.0);

Now it works and looks like a charm.


问:
Why doesn't C++ support range based for loop for dynamic arrays?
Why doesn't C++ support range based for loop over dynamic arrays?  That is, something like this:

```<code>int* array = new int[len];
for[] (int i : array) {};
</code>```

I just invented the for[] statement to rhyme with new[] and delete[].  As far as I understand, the runtime has the size of the array available (otherwise delete[] could not work) so in theory, range based for loop could also be made to work.  What is the reason that it's not made to work?

答:
When you have this:

```<code>int* array = new int[len];
</code>```

The problem here is that your variable called array is not an array at all. It is a pointer. That means it only contains the address of one object (in this case the first element of the array created using new).

For range based for to work the compiler needs two addresses, the beginning and the end of the array.

So the problem is the compiler does not have enough information to do this:

```<code>// array is only a pointer and does not have enough information
for(int i : array)
{
}
</code>```

Body:
Why doesn't C++ support range based for loop over dynamic arrays?  That is, something like this:

int* array = new int[len];
for[] (int i : array) {};

I just invented the for[] statement to rhyme with new[] and delete[].  As far as I understand, the runtime has the size of the array available (otherwise delete[] could not work) so in theory, range based for loop could also be made to work.  What is the reason that it's not made to work?

Body:
When you have this:

int* array = new int[len];

The problem here is that your variable called array is not an array at all. It is a pointer. That means it only contains the address of one object (in this case the first element of the array created using new).

For range based for to work the compiler needs two addresses, the beginning and the end of the array.

So the problem is the compiler does not have enough information to do this:

// array is only a pointer and does not have enough information
for(int i : array)
{
}


问:
Seperate a UILabel text to three different UILabels
i am not really sure if the title meets what i want, but i have a label with a bunch of sentences, i want to separate each one of them to a different UILabel

Here's my code

```<code>   var s: [String] = []
   for (i, pred) in results.enumerated() {
    let latLongArr = pred.0.components(separatedBy: "\t")
    myLatitude = latLongArr[1]
    myLongitude = latLongArr[2]
    s.append(String(format: "%d: %@ %@ (%3.2f%%)", i + 1, myLatitude, myLongitude, pred.1 * 100))
    places[i].title = String(i+1)
    places[i].coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(myLatitude)!, longitude: CLLocationDegrees(myLongitude)!)
}
predictionLabel.text = s.joined(separator: "\n") // one label
</code>```

and the UILabel text looks something like this

```<code>Prediction 1: latitude longitude // first sentence
(probability%)
Prediction 2: latitude longitude // second
(probability%)
Prediction 3: latitude longitude // third
(probability%)
</code>```

Thank you

EDIT

i've created three labels and tried this code, unfortunately it gives the first result

```<code>    self.predict1.text = s.joined(separator: "\n")
    self.predict2.text = s.joined(separator: "\n")
    self.predict3.text = s.joined(separator: "\n")
</code>```

答:
Either you set numberOfLines on the label to 0 and lineBreakMode to .byWordWrapping or you make a vertical statckview, instantiate a label for each string, and add the label to the stackview's arrangedSubviews.

EDIT
Now that I look at your code the real problem is the line let latLongArr = pred.0.components(separatedBy: "\t").  Most likely your data has trailing newlines in it and you need to kill the trailing newlines after the longitude.

```<code>   var s: [String] = []
   for (i, pred) in results.enumerated() {
    let latLongArr = pred.0.components(separatedBy: "\t").replacingOccurrences(of: "\n", with: "")
    myLatitude = latLongArr[1]
    myLongitude = latLongArr[2]
    s.append(String(format: "%d: %@ %@ (%3.2f%%)", i + 1, myLatitude, myLongitude, pred.1 * 100))
    places[i].title = String(i+1)
    places[i].coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(myLatitude)!, longitude: CLLocationDegrees(myLongitude)!)
}
</code>```

Body:
i am not really sure if the title meets what i want, but i have a label with a bunch of sentences, i want to separate each one of them to a different UILabel

Here's my code

   var s: [String] = []
   for (i, pred) in results.enumerated() {
    let latLongArr = pred.0.components(separatedBy: "\t")
    myLatitude = latLongArr[1]
    myLongitude = latLongArr[2]
    s.append(String(format: "%d: %@ %@ (%3.2f%%)", i + 1, myLatitude, myLongitude, pred.1 * 100))
    places[i].title = String(i+1)
    places[i].coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(myLatitude)!, longitude: CLLocationDegrees(myLongitude)!)
}
predictionLabel.text = s.joined(separator: "\n") // one label

and the UILabel text looks something like this

Prediction 1: latitude longitude // first sentence
(probability%)
Prediction 2: latitude longitude // second
(probability%)
Prediction 3: latitude longitude // third
(probability%)

Thank you

EDIT

i've created three labels and tried this code, unfortunately it gives the first result

    self.predict1.text = s.joined(separator: "\n")
    self.predict2.text = s.joined(separator: "\n")
    self.predict3.text = s.joined(separator: "\n")

Body:
Either you set numberOfLines on the label to 0 and lineBreakMode to .byWordWrapping or you make a vertical statckview, instantiate a label for each string, and add the label to the stackview's arrangedSubviews.

EDIT
Now that I look at your code the real problem is the line let latLongArr = pred.0.components(separatedBy: "\t").  Most likely your data has trailing newlines in it and you need to kill the trailing newlines after the longitude.

   var s: [String] = []
   for (i, pred) in results.enumerated() {
    let latLongArr = pred.0.components(separatedBy: "\t").replacingOccurrences(of: "\n", with: "")
    myLatitude = latLongArr[1]
    myLongitude = latLongArr[2]
    s.append(String(format: "%d: %@ %@ (%3.2f%%)", i + 1, myLatitude, myLongitude, pred.1 * 100))
    places[i].title = String(i+1)
    places[i].coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(myLatitude)!, longitude: CLLocationDegrees(myLongitude)!)
}


问:
How to validate multipart/form-data in Express-validator using Nodejs
A snippet of my code where i show my defined router,checking body param and checking for validation error.

My defined Post request:

```<code>router.post("/addEmployee",upload.any(), function(req, res, next) {

  /*I used multer because body data from multipart/form-data*/

var input = JSON.parse(req.body.data);
</code>```

Server validation: // validation not work because req.checkBody only get bodyData now i am using multipart/form-data (req.body.data)

```<code>req.checkBody('EMPID', "**EMPID must be Integer**").notEmpty().isNumeric();

req.checkBody('PAYROLLID', "**PAYROLLID must be Integer**").notEmpty().isNumeric();

.....

....
</code>```

Check validation error

```<code>var validationError = req.validationErrors(); //check error

// if (validationError) { //suppose get error -- throw that error

 res.json(validationError[0].msg);

 } else { //validation success

......strong text
</code>```

答:
Guys I find one solution</p>

```<code>router.post("/addEmployee",upload.any(), function(req, res, next) {

   /*I used multer because body data from multipart/form-data*/

   var input = JSON.parse(req.body.data);

   req.body = input;// solution this line
});
</code>```

Body:
A snippet of my code where i show my defined router,checking body param and checking for validation error.

My defined Post request:

router.post("/addEmployee",upload.any(), function(req, res, next) {

  /*I used multer because body data from multipart/form-data*/

var input = JSON.parse(req.body.data);

Server validation: // validation not work because req.checkBody only get bodyData now i am using multipart/form-data (req.body.data)

req.checkBody('EMPID', "**EMPID must be Integer**").notEmpty().isNumeric();

req.checkBody('PAYROLLID', "**PAYROLLID must be Integer**").notEmpty().isNumeric();

.....

....

Check validation error

var validationError = req.validationErrors(); //check error

// if (validationError) { //suppose get error -- throw that error

 res.json(validationError[0].msg);

 } else { //validation success

......strong text

Body:
Guys I find one solution

router.post("/addEmployee",upload.any(), function(req, res, next) {

   /*I used multer because body data from multipart/form-data*/

   var input = JSON.parse(req.body.data);

   req.body = input;// solution this line
});


问:
how to tune linux network buffer size
I'm reading "Kafka The Definitive Guide", in page 35 (networking section) it says :

... The first adjustment is to change the default and maximum amount of
  memory allocated for the send and receive buffers for each socket. This will significantly increase performance for large transfers. The relevant parameters for the send and receive buffer default size per socket are net.core.wmem_default and
  net.core.rmem_default......
  In addition to the socket settings, the send and receive buffer sizes for TCP sockets must be set separately using the net.ipv4.tcp_wmem and net.ipv4.tcp_rmem parameters.

why we should set both net.core.wmem and net.ipv4.tcp_wmem?

答:
Short answer - r/wmem_default are used for setting static socket buffer sizes, while tcp_r/wmem are used for controlling TCP send/receive window size and buffers dynamically.

More details:
By tracking the usages of r/wmem_default and tcp_r/wmem (kernel 4.14) we can see that r/wmem_default are only used in sock_init_data():

```<code>void sock_init_data(struct socket *sock, struct sock *sk)
{
        sk_init_common(sk);
        ...
        sk->sk_rcvbuf           =       sysctl_rmem_default;
        sk->sk_sndbuf           =       sysctl_wmem_default;
</code>```

This initializes the socket's buffers for sending and receiving packets and might be later overridden in set_sockopt:

```<code>int sock_setsockopt(struct socket *sock, int level, int optname,
                    char __user *optval, unsigned int optlen)
{
        struct sock *sk = sock->sk;
        ...
        sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
        ...
        sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
</code>```

Usages of tcp_rmem are found in these functions: tcp_select_initial_window() in tcp_output.c and __tcp_grow_window(), tcp_fixup_rcvbuf(), tcp_clamp_window() and tcp_rcv_space_adjust() in tcp_input.c. In all usages this value is used for controlling the receive window and/or the socket's receive buffer dynamically, meaning it would take the current traffic and the system parameters into consideration.
A similar search for tcp_wmem show that it is only used for dynamic changes in the socket's send buffer in tcp_init_sock() (tcp.c) and tcp_sndbuf_expand() (tcp_input.c).

So when you want the kernel to better tune your traffic, the most important values are tcp_r/wmem. The Socket's size is usually overridden by the user the default value doesn't really matter. For exact tuning operations, try reading the comments in tcp_input.c marked as "tuning". There's a lot of valuable information there.

Hope this helps.

Title: how to tune linux network buffer size

Body:
Short answer - r/wmem_default are used for setting static socket buffer sizes, while tcp_r/wmem are used for controlling TCP send/receive window size and buffers dynamically.

More details:
By tracking the usages of r/wmem_default and tcp_r/wmem (kernel 4.14) we can see that r/wmem_default are only used in sock_init_data():

void sock_init_data(struct socket *sock, struct sock *sk)
{
        sk_init_common(sk);
        ...
        sk->sk_rcvbuf           =       sysctl_rmem_default;
        sk->sk_sndbuf           =       sysctl_wmem_default;

This initializes the socket's buffers for sending and receiving packets and might be later overridden in set_sockopt:

int sock_setsockopt(struct socket *sock, int level, int optname,
                    char __user *optval, unsigned int optlen)
{
        struct sock *sk = sock->sk;
        ...
        sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
        ...
        sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);

Usages of tcp_rmem are found in these functions: tcp_select_initial_window() in tcp_output.c and __tcp_grow_window(), tcp_fixup_rcvbuf(), tcp_clamp_window() and tcp_rcv_space_adjust() in tcp_input.c. In all usages this value is used for controlling the receive window and/or the socket's receive buffer dynamically, meaning it would take the current traffic and the system parameters into consideration.
A similar search for tcp_wmem show that it is only used for dynamic changes in the socket's send buffer in tcp_init_sock() (tcp.c) and tcp_sndbuf_expand() (tcp_input.c).

So when you want the kernel to better tune your traffic, the most important values are tcp_r/wmem. The Socket's size is usually overridden by the user the default value doesn't really matter. For exact tuning operations, try reading the comments in tcp_input.c marked as "tuning". There's a lot of valuable information there.

Hope this helps.


问:
Spark Scala read csv file using s3a
I am trying to read a csv (native) file from an S3 bucket using a locally running Spark - Scala. I am able to read the file using the http protocol but I intend to use the s3a protocol.

Below is the configuration setup before the call.

```<code>    val awsId = System.getenv("AWS_ACCESS_KEY_ID")
    val awsKey = System.getenv("AWS_SECRET_ACCESS_KEY")
    sc.hadoopConfiguration.set("fs.s3a.access.key", awsId)
    sc.hadoopConfiguration.set("fs.s3a.secret.key", awsKey)
    sc.hadoopConfiguration.set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
    sc.hadoopConfiguration.set("fs.s3a.aws.credentials.provider","org.apache.hadoop.fs.s3a.BasicAWSCredentialsProvider");
    sc.hadoopConfiguration.set("com.amazonaws.services.s3.enableV4", "true")
    sc.hadoopConfiguration.set("fs.s3a.endpoint", "us-east-1.amazonaws.com")
    sc.hadoopConfiguration.set("fs.s3a.impl.disable.cache", "true")
 here
</code>```

Read the file and print the first 5 rows from the rdd/dataframe

```<code>    val fileAPath = Files.s3aPath(Files.input);
    println("reading file s3", fileAPath)
    // s3a://bucket-name/dataSets/policyoutput.csv
    val df = sc.textFile(fileAPath);
    df.take(5).foreach(println);
</code>```

I am getting the below exception

```<code>Exception in thread "main" com.amazonaws.services.s3.model.AmazonS3Exception: Status Code: 400, AWS Service: Amazon S3, AWS Request ID: FD92FDC175C64AA2, AWS Error Code: null, AWS Error Message: Bad Request, S3 Extended Request ID: IuloUEASgqnY4lrSMpbyJpwgFfCFbttxuxmJ9hGHMUgZTbO/UR/YyDgjix+3rBe0Y4MQHPzNvhA=
    at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:798)
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:421)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:232)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3528)
    at com.amazonaws.services.s3.AmazonS3Client.headBucket(AmazonS3Client.java:1031)
    at com.amazonaws.services.s3.AmazonS3Client.doesBucketExist(AmazonS3Client.java:994)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:154)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:370)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
    at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:258)
    at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:229)
    at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:315)
    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:194)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.rdd.RDD$$anonfun$take$1.apply(RDD.scala:1333)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.take(RDD.scala:1327)
</code>```

Any help / direction for further investigation will be much appreciated.

Thanks

答:
Anyone else struggling with this I had to update the version of hadoop-client

additionally the links below were quite helpful

https://hadoop.apache.org/docs/current/hadoop-aws/tools/hadoop-aws/index.html

https://disqus.com/by/cfeduke/?utm_source=reply&utm_medium=email&utm_content=comment_author

http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region

pom details below

```<code><properties>
    <spark.version>2.2.0</spark.version>
    <hadoop.version>2.8.0</hadoop.version>

</properties>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.11 -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>${spark.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>${spark.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>${hadoop.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-aws</artifactId>
        <version>${hadoop.version}</version>
    </dependency>
</code>```

Title: Spark Scala read csv file using s3a

Body:
I am trying to read a csv (native) file from an S3 bucket using a locally running Spark - Scala. I am able to read the file using the http protocol but I intend to use the s3a protocol.

Below is the configuration setup before the call.

    val awsId = System.getenv("AWS_ACCESS_KEY_ID")
    val awsKey = System.getenv("AWS_SECRET_ACCESS_KEY")
    sc.hadoopConfiguration.set("fs.s3a.access.key", awsId)
    sc.hadoopConfiguration.set("fs.s3a.secret.key", awsKey)
    sc.hadoopConfiguration.set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
    sc.hadoopConfiguration.set("fs.s3a.aws.credentials.provider","org.apache.hadoop.fs.s3a.BasicAWSCredentialsProvider");
    sc.hadoopConfiguration.set("com.amazonaws.services.s3.enableV4", "true")
    sc.hadoopConfiguration.set("fs.s3a.endpoint", "us-east-1.amazonaws.com")
    sc.hadoopConfiguration.set("fs.s3a.impl.disable.cache", "true")
 here

Read the file and print the first 5 rows from the rdd/dataframe

    val fileAPath = Files.s3aPath(Files.input);
    println("reading file s3", fileAPath)
    // s3a://bucket-name/dataSets/policyoutput.csv
    val df = sc.textFile(fileAPath);
    df.take(5).foreach(println);

I am getting the below exception

Exception in thread "main" com.amazonaws.services.s3.model.AmazonS3Exception: Status Code: 400, AWS Service: Amazon S3, AWS Request ID: FD92FDC175C64AA2, AWS Error Code: null, AWS Error Message: Bad Request, S3 Extended Request ID: IuloUEASgqnY4lrSMpbyJpwgFfCFbttxuxmJ9hGHMUgZTbO/UR/YyDgjix+3rBe0Y4MQHPzNvhA=
    at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:798)
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:421)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:232)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3528)
    at com.amazonaws.services.s3.AmazonS3Client.headBucket(AmazonS3Client.java:1031)
    at com.amazonaws.services.s3.AmazonS3Client.doesBucketExist(AmazonS3Client.java:994)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:154)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:370)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
    at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:258)
    at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:229)
    at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:315)
    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:194)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.rdd.RDD$$anonfun$take$1.apply(RDD.scala:1333)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.take(RDD.scala:1327)

Any help / direction for further investigation will be much appreciated.

Thanks

Body:
Anyone else struggling with this I had to update the version of hadoop-client

additionally the links below were quite helpful

https://hadoop.apache.org/docs/current/hadoop-aws/tools/hadoop-aws/index.html

https://disqus.com/by/cfeduke/?utm_source=reply&utm_medium=email&utm_content=comment_author

http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region

pom details below

<properties>
    <spark.version>2.2.0</spark.version>
    <hadoop.version>2.8.0</hadoop.version>

</properties>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.11 -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>${spark.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>${spark.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>${hadoop.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-aws</artifactId>
        <version>${hadoop.version}</version>
    </dependency>


问:
Xcode : How To Set App To Be iPhone Only?
We have set the following app settings to be iPhone only, but in the App Store the app is listed as iPhone/iPad compatible.

As you can see in the following image, the device family is set to be just iPhones:

Here is App: http://itunes.apple.com/us/app/carrom-pro/id525961441?mt=8.

Is there anything wrong with these settings?

答: Keep UIDeviceFamily property to 1 (for iPhone) in app plist file and also change the Targeted Device Family in Build settings to 1 (for iPhone). Keep 2 in the both cases if you want to support iPad only. These are tested in XCode 8.


问:
The plus logo does not change when the menu is unfolded
I added the following line to my style sheet, to display a plus when the mower is not unfolded.

```<code>#block-menuprincipal li.dropdown > a[aria-expanded=false] i:before {
  content: '\f055';
}
</code>```

The logo works but when I load my page, the first logo is a plus and the second is a "minus".
The menu is not unfolded, both logo should be "plus".

If I unfold the two menus and fold them, the logos are "plus".

Why is the second logo a "minus" if I reload the page?

After unfolding and folding the menu, it works. But if I reload the page I have the same problem.

Here is my menu block :

```<code><nav role="navigation" aria-labelledby="block-navigationprincipale-menu" id="block-navigationprincipale">
   <ul class="menu nav navbar-nav">
      <li class="expanded dropdown open">
         <a href="/boutique" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"><i class="fa fa-minus-circle fa-lg" aria-hidden="true"></i> Boutiques</a>
            <ul class="menu dropdown-menu">
               <li>
                  <a href="/boutique" data-drupal-link-system-path="boutique"><i class="fa fa-shopping-bag fa-lg" aria-hidden="true"></i> Boutiques</a>
               </li>
               <li>
                  <a href="/produit" data-drupal-link-system-path="produit"><i class="fa fa-gift fa-lg" aria-hidden="true"></i> Produits</a>
               </li>
               <li>
                  <a href="/service" data-drupal-link-system-path="service"><i class="fa fa-sign-language fa-lg" aria-hidden="true"></i> Services</a>
               </li>
            </ul>
      </li>
      <li class="expanded dropdown">
         <a href="/groupe" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-minus-circle fa-lg" aria-hidden="true"></i> Groupes</a>
            <ul class="menu dropdown-menu">
               <li>
                  <a href="/groupe" data-drupal-link-system-path="groupe"><i class="fa fa-users fa-mg" aria-hidden="true"></i> Groupes</a>
               </li>
               <li>
                  <a href="/annonce" data-drupal-link-system-path="annonce"><i class="fa fa-newspaper-o fa-lg" aria-hidden="true"></i> Annonces</a>
               </li>
               <li>
                  <a href="/article" data-drupal-link-system-path="article"><i class="fa fa-file-text-o fa-lg" aria-hidden="true"></i> Articles</a>
               </li>
               <li>
                  <a href="/discussion" data-drupal-link-system-path="discussion"><i class="fa fa-comments fa-lg" aria-hidden="true"></i> Discussions</a>
               </li>
               <li>
                  <a href="/recette" data-drupal-link-system-path="recette"><i class="fa fa-cutlery fa-lg" aria-hidden="true"></i> Recettes</a>
               </li>
               <li>
                  <a href="/itineraire" data-drupal-link-system-path="itineraire"><i class="fa fa-map-signs fa-lg" aria-hidden="true"></i> Itinéraires</a>
               </li>
               <li>
                  <a href="/evenement" data-drupal-link-system-path="evenement"><i class="fa fa-calendar fa-lg" aria-hidden="true"></i> Événements</a>
               </li>
            </ul>
      </li>
      <li>
         <a href="/profil" data-drupal-link-system-path="profil"><i class="fa fa-id-card-o fa-lg" aria-hidden="true"></i> Profils</a>
      </li>
   </ul>
</nav>
</code>```

答:
Ok, If you are using D8, then it will be a bit hard to add that attribute. So we should try to fix this by CSS only.
Can you replace your CSS with what I am providing below</p>

```<code>    #block-menuprincipal li.dropdown > a i:before {
       content: '\f055';
    }

    #block-menuprincipal li.dropdown > a[aria-expanded=true] i:before {
       content: '\f056';
    }
</code>```

Body:
I added the following line to my style sheet, to display a plus when the mower is not unfolded.

#block-menuprincipal li.dropdown > a[aria-expanded=false] i:before {
  content: '\f055';
}

The logo works but when I load my page, the first logo is a plus and the second is a "minus".
The menu is not unfolded, both logo should be "plus".

If I unfold the two menus and fold them, the logos are "plus".

Why is the second logo a "minus" if I reload the page?

After unfolding and folding the menu, it works. But if I reload the page I have the same problem.

Here is my menu block :

          Boutiques

                   Boutiques

                   Produits

                   Services

          Groupes

                   Groupes

                   Annonces

                   Articles

                   Discussions

                   Recettes

                   Itinéraires

                   Événements

          Profils

Body:
Ok, If you are using D8, then it will be a bit hard to add that attribute. So we should try to fix this by CSS only.
Can you replace your CSS with what I am providing below

    #block-menuprincipal li.dropdown > a i:before {
       content: '\f055';
    }

    #block-menuprincipal li.dropdown > a[aria-expanded=true] i:before {
       content: '\f056';
    }


问:
How to make my ion-searchbar (ion-input) sticky on the top nav bar in Ionic?
My html form shows a list from JSON API and a search input box for filtering the list.

I want this search to be sticky on the top. Below is my task.html code.

```<code><!--
  Generated template for the TaskgivenPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>taskgiven</ion-title>

  </ion-navbar>

</ion-header>

<ion-content padding>
  <ion-searchbar (ionInput)="getItems($event)" style="width:400px; float:right;  "></ion-searchbar>
  <ion-list  *ngFor="let list of displayList;">

    <ion-item class="desc" (click)="ind(list)" >{{list.TASKDESC}}  <br>
      <p style="color:#d2dce1; margin-top:10px" >{{list.PRIMARY}}</p>
      <p style="text-align:right; margin-top:-20px;" [style.color]="list.ENTDT > list.DEADLINE_DT ? 'red' : '#d2dce1'">{{list.DEADLINE_DT}}</p><hr>

    </ion-item>

    <!--<ion-item class="desc1" >{{list.PRIMARY}}</ion-item>-->
  </ion-list>

</ion-content>
</code>```

I want <ion-searchbar (ionInput)="getItems($event)" style="width:400px; float:right;  "></ion-searchbar> to be sticky on top

答:
Just place your search bar inside your ion-header. You can find the working version here</p>

```<code><ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
    <ion-searchbar [(ngModel)]="searchTerm" (ionInput)="setFilteredItems()"></ion-searchbar>
  </ion-navbar>
</ion-header>
</code>```

Body:
My html form shows a list from JSON API and a search input box for filtering the list.

I want this search to be sticky on the top. Below is my task.html code.

<ion-header>

  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>taskgiven</ion-title>

  </ion-navbar>

</ion-header>

<ion-content padding>
  <ion-searchbar (ionInput)="getItems($event)" style="width:400px; float:right;  "></ion-searchbar>
  <ion-list  *ngFor="let list of displayList;">

    <ion-item class="desc" (click)="ind(list)" >{{list.TASKDESC}}

{{list.PRIMARY}}

 list.DEADLINE_DT ? 'red' : '#d2dce1'">{{list.DEADLINE_DT}}

    </ion-item>

  </ion-list>

</ion-content>

I want <ion-searchbar (ionInput)="getItems($event)" style="width:400px; float:right;  "></ion-searchbar> to be sticky on top

Body:
Just place your search bar inside your ion-header. You can find the working version here

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
    <ion-searchbar [(ngModel)]="searchTerm" (ionInput)="setFilteredItems()"></ion-searchbar>
  </ion-navbar>
</ion-header>


问:
Extracting css from react component library
I have created react component library and I'm using style loader in component library

But at the place where I'm using that library, I need css in one file. Is there any way to do this with extract text plugin ?

答: Yes. From the library consumer, import/require the library's style sheet, and configure the consumer's Webpack configuration with the extract text plugin.</p>


问:
How to show a dynamic content in the same page using Angularjs 1.6?
I'm a newbie to Angular. I need to render a dynamic content from JSON file using AngularJS 1.6. Here is what I have.

News.json

```<code>   {
  "Articles": [
    {
      "Title": "News 1",
      "Abstract": "News 1 abstract ...",
      "Body": "News 1 starts here.... ",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here",
          "comment 3" : "Comment 3 goes here"
        }]
    },

    {
      "Title": "News 2",
      "Abstract": "News 2 abstract ... ",
      "Body": "News 2 starts here...",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here"
        }]
    }
  ]
}
</code>```

Script.js

```<code>app.config(function ($routeProvider) {
    $routeProvider
        .when("/News", {
            templateUrl: "NewsViewer.html",
            controller: "showNews"
        });
});

app.controller("showNews", ["$scope", "$http", function ($scope, $http) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data;
    });
}]);
</code>```

News.html

```<code><div class="container-fluid">

    <div class="row">

        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="NewsRendering">
                <div ng-repeat="NewsData in News.Articles">
                    <h3>{{NewsData.Title}}</h3>
                    <p>{{NewsData.Abstract}}</p>
                    <a data-ng-href="/AngularTask/NewsViewer.html">more</a>
                </div>
            </div>
        </div>

        <div class="col-md-4 questionnaire">
            <h3>Questionnaire of the day</h3>
        </div>

    </div>

</div>
</code>```

NewsViewer.html

```<code><div class="container-fluid">
    <div class="row">
        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="showNews">
                <div>
                    <h3>{{News.Articles[0].Title}}</h3>
                    <p>{{News.Articles[0].Abstract}}</p>
                    <p>{{News.Articles[0].Body}}</p>
                </div>

                <div class="comments">
                    <h4>Comments</h4>
                    <hr>
                    <p>{{News.Articles[0].Comments[0]}}</p>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

This code is working fine, but this code is not dynamic. My problem how to make it dynamic and can show whatever in json file. What should I do in JS code to pass the index of the array of the JSON File.

As you can see
{{News.Articles[0].Title}}
 is showing only the first Title of the JSON file. I need to write it to be
{{News.Articles[index of whatever].Title}}

Note: News.json has around 100,000 records. I make it two, just to show the code and describe the problem.

答:
Please find the working solution below

https://embed.plnkr.co/rbNAcVGtBvTjl9VhfFAl/

Let me know, if you need further info. Enjoy :)

Edited

First of all we need to define two separate routes, one for News and one for Article

```<code>$routeProvider.when("/News", {
    templateUrl: "News.html",
    controller: "NewsContoller"
}).when("/NewsViewer", {
    templateUrl: "NewsViewer.html",
    controller: "NewsViewerController"
})
</code>```

As you see, there are two separate controllers handling each route.

Then we need a value service to pass data between routes

```<code>angular.module('app').value('viewData', {})
</code>```

After that on click of more link, set the value of viewData to that specific article and redirect to /NewsViewer route. And, on NewsViewerController retrieve that value from viewData and pass it to $scope.

Template: News.html

```<code><div>
  <div ng-repeat="NewsData in News.Articles">
    <h3>{{NewsData.Title}}</h3>
    <p>{{NewsData.Abstract}}</p>
    <a href ng-click="showArticle(NewsData)">more</a>
  </div>
</div>
</code>```

Template: NewsViewer.html

```<code><div>
  <div>
    <h3>{{Article.Title}}</h3>
    <p>{{Article.Abstract}}</p>
    <p>{{Article.Body}}</p>
  </div>

  <div class="comments">
    <h4>Comments</h4>
    <hr>
    <p ng-repeat="(key, value) in Article.Comments[0]">
      {{value}}
    </p>
  </div>
</div>
<a ng-href="#!/News">All News</a>
</code>```

Controller: NewsController

```<code>angular.module('app').controller('NewsContoller', function($scope, $http, viewData, $location) {
  $http({
    method: 'GET',
    url: 'News.json'
  }).then(function success(response) {
    $scope.News = response.data;
  });
  $scope.showArticle = function(article) {
    viewData.article = article;
    $location.path("/NewsViewer");
  }
})
</code>```

Controller: NewsViewerController

```<code>angular.module('app').controller('NewsViewerController', function($scope, viewData) {
  $scope.Article = viewData.article;
})
</code>```

Link of plunker is above in original answer.

Body:
I'm a newbie to Angular. I need to render a dynamic content from JSON file using AngularJS 1.6. Here is what I have.

News.json

   {
  "Articles": [
    {
      "Title": "News 1",
      "Abstract": "News 1 abstract ...",
      "Body": "News 1 starts here.... ",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here",
          "comment 3" : "Comment 3 goes here"
        }]
    },

    {
      "Title": "News 2",
      "Abstract": "News 2 abstract ... ",
      "Body": "News 2 starts here...",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here"
        }]
    }
  ]
}

Script.js

app.config(function ($routeProvider) {
    $routeProvider
        .when("/News", {
            templateUrl: "NewsViewer.html",
            controller: "showNews"
        });
});

app.controller("showNews", ["$scope", "$http", function ($scope, $http) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data;
    });
}]);

News.html

{{NewsData.Title}}

{{NewsData.Abstract}}

                    more

Questionnaire of the day

NewsViewer.html

{{News.Articles[0].Title}}

{{News.Articles[0].Abstract}}

{{News.Articles[0].Body}}

Comments

{{News.Articles[0].Comments[0]}}

This code is working fine, but this code is not dynamic. My problem how to make it dynamic and can show whatever in json file. What should I do in JS code to pass the index of the array of the JSON File.

As you can see
{{News.Articles[0].Title}}
 is showing only the first Title of the JSON file. I need to write it to be
{{News.Articles[index of whatever].Title}}

Note: News.json has around 100,000 records. I make it two, just to show the code and describe the problem.

Body:
Please find the working solution below

https://embed.plnkr.co/rbNAcVGtBvTjl9VhfFAl/

Let me know, if you need further info. Enjoy :)

Edited

First of all we need to define two separate routes, one for News and one for Article

$routeProvider.when("/News", {
    templateUrl: "News.html",
    controller: "NewsContoller"
}).when("/NewsViewer", {
    templateUrl: "NewsViewer.html",
    controller: "NewsViewerController"
})

As you see, there are two separate controllers handling each route.

Then we need a value service to pass data between routes

angular.module('app').value('viewData', {})

After that on click of more link, set the value of viewData to that specific article and redirect to /NewsViewer route. And, on NewsViewerController retrieve that value from viewData and pass it to $scope.

Template: News.html

<div>
  <div ng-repeat="NewsData in News.Articles">
    <h3>{{NewsData.Title}}</h3>
    <p>{{NewsData.Abstract}}</p>
    <a href ng-click="showArticle(NewsData)">more</a>
  </div>
</div>

Template: NewsViewer.html

<div>
  <div>
    <h3>{{Article.Title}}</h3>
    <p>{{Article.Abstract}}</p>
    <p>{{Article.Body}}</p>
  </div>

  <div class="comments">
    <h4>Comments</h4>
    <hr>
    <p ng-repeat="(key, value) in Article.Comments[0]">
      {{value}}
    </p>
  </div>
</div>
<a ng-href="#!/News">All News</a>

Controller: NewsController

angular.module('app').controller('NewsContoller', function($scope, $http, viewData, $location) {
  $http({
    method: 'GET',
    url: 'News.json'
  }).then(function success(response) {
    $scope.News = response.data;
  });
  $scope.showArticle = function(article) {
    viewData.article = article;
    $location.path("/NewsViewer");
  }
})

Controller: NewsViewerController

angular.module('app').controller('NewsViewerController', function($scope, viewData) {
  $scope.Article = viewData.article;
})

Link of plunker is above in original answer.


问:
Android View shadow
I searched around, and I could not find a proper way to do this. I want to have the following shadow effects on my views:

To be honest, I do not know if this second one is done by applying shadow effect. Any ideas?

答:
Use the elevation property for shadow affect:</p>

```<code><YourView
    ...
    android:elevation="3dp"/>
</code>```

Title: Android View shadow

Body:
Use the elevation property for shadow affect:

<YourView
    ...
    android:elevation="3dp"/>


问:
can we move sql compact edition database to sql lite database in windows forms application
Currently I am using an SQL Server Compact Edition database in a Windows Forms application.

Now I have to move the database to SQLite. Is it possible to move the database from SQL Server Compact to SQLite? If it is possible, what are the steps we have to follow?

答: I have tools to export the SQL Server Compact file as a .sql script - that would get you half of the way - http://exportsqlce.codeplex.com</p>


问:
Camera image orientation
In my app I'm capturing images using the Camera.  These are being stored in an NSArray as an NSData representation.  When I convert the NSData back to the image, the orientation is now landscape instead of portrait as I took it.

```<code>    NSData *data = UIImagePNGRepresentation([arrayImage objectAtIndex:0]);
    UIImage *tmp = [UIImage imageWithData:data];
</code>```

Anyone have an explanation?  Thanks.

答:
```<code>//iOS Swift 3

func fixRotation(image: UIImage) -> UIImage
    {
        if (image.imageOrientation == .up)
        {
            return image
        }

        var transform: CGAffineTransform = .identity

        switch image.imageOrientation {
        case .down, .downMirrored:
            transform = transform.translatedBy(x: image.size.width, y: image.size.height)
            transform = transform.rotated(by: .pi)
        case .left, .leftMirrored:
            transform = transform.translatedBy(x: image.size.width, y: 0)
            transform = transform.rotated(by: .pi / 2)
        case .right, .rightMirrored:
            transform = transform.translatedBy(x: 0, y: image.size.height)
            transform = transform.rotated(by: -(.pi / 2))
        case .up, .upMirrored:
            break
        }

        switch image.imageOrientation {
        case .upMirrored, .downMirrored:
            transform = transform.translatedBy(x: image.size.width, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
        case .leftMirrored, .rightMirrored:
            transform = transform.translatedBy(x: image.size.height, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
        case .up, .down, .left, .right:
            break
        }

        // Now we draw the underlying CGImage into a new context, applying the transform
        // calculated above.

        let cgimage = image.cgImage
        let bitsPerComponent = cgimage?.bitsPerComponent
        let colorSpace = cgimage?.colorSpace
        let bitmapInfo = cgimage?.bitmapInfo

        let ctx = CGContext(data: nil, width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: bitsPerComponent! , bytesPerRow: 0, space: colorSpace!, bitmapInfo: bitmapInfo!.rawValue)

        ctx?.concatenate(transform)

        switch image.imageOrientation {
        case .left, .leftMirrored, .right, .rightMirrored:
            // Grr...
            ctx?.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width))
        default:
            ctx?.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
        }

        let cgimg: CGImage = ctx!.makeImage()!
        let img = UIImage(cgImage: cgimg)
        return img
    }
</code>```

Title: Camera image orientation

Body:
In my app I'm capturing images using the Camera.  These are being stored in an NSArray as an NSData representation.  When I convert the NSData back to the image, the orientation is now landscape instead of portrait as I took it.

    NSData *data = UIImagePNGRepresentation([arrayImage objectAtIndex:0]);
    UIImage *tmp = [UIImage imageWithData:data];

Anyone have an explanation?  Thanks.


问:
microservice not able to locate zipkin service using discovery-server
I have mircroservice environment based on spring-boot, where i am using zipkin server and discovery-server(eureka) and config-server. Now i have a rest-microservice which sends logs to zipkin server and this microservice is required to resolve where is zipkin server using discovery-server.

following is zipkin configuration i have in my rest-microservice's application.properties(pulled from config-server).

```<code>spring.zipkin.baseUrl=http://MTD-ZIPKIN-SERVER/
spring.zipkin.locator.discovery.enabled=true
spring.zipkin.enabled=true
...
</code>```

here MTD-ZIPKIN-SERVER is zipkin-server name in discovery-server.

discovery-server dashboard.

but it does not try to resolve zipkin from discovery-server, instead it tries to connect directly using spring.zipkin.baseUrl, and i get below exception.

Dropped 1 spans due to ResourceAccessException(I/O error on POST request for "http://MTD-ZIPKIN-SERVER/api/v1/spans":
  MTD-ZIPKIN-SERVER; nested exception is java.net.UnknownHostException:
  MTD-ZIPKIN-SERVER)

org.springframework.web.client.ResourceAccessException: I/O error on
  POST request for "http://MTD-ZIPKIN-SERVER/api/v1/spans":
  MTD-ZIPKIN-SERVER; nested exception is java.net.UnknownHostException:
  MTD-ZIPKIN-SERVER     at
  org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:666)
    at
  org.springframework.web.client.RestTemplate.execute(RestTemplate.java:628)
    at
  org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:590)
    at
  org.springframework.cloud.sleuth.zipkin.RestTemplateSender.post(RestTemplateSender.java:73)
    at
  org.springframework.cloud.sleuth.zipkin.RestTemplateSender.sendSpans(RestTemplateSender.java:46)
    at
  zipkin.reporter.AsyncReporter$BoundedAsyncReporter.flush(AsyncReporter.java:245)
    at
  zipkin.reporter.AsyncReporter$Builder.lambda$build$0(AsyncReporter.java:166)
    at zipkin.reporter.AsyncReporter$Builder$$Lambda$1.run(Unknown
  Source)   at java.lang.Thread.run(Thread.java:745) Caused by:
  java.net.UnknownHostException: MTD-ZIPKIN-SERVER  at
  java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)

if i provide exact zipkin url in property spring.zipkin.baseUrl like below

```<code>spring.zipkin.baseUrl=http://localhost:5555/
</code>```

then my rest-microservice is able to connect to zipkin-server.

My goal here is to read zipkin-server location from discovery-srever. What am i doing wrong? Do i need to add some zipkin enabling annotation on my spring-boot rest-microservice?

答: This feature is available in edgware release train. That corresponds to version 1.3.x of sleuth </p>

Body:
I have mircroservice environment based on spring-boot, where i am using zipkin server and discovery-server(eureka) and config-server. Now i have a rest-microservice which sends logs to zipkin server and this microservice is required to resolve where is zipkin server using discovery-server.

following is zipkin configuration i have in my rest-microservice's application.properties(pulled from config-server).

spring.zipkin.baseUrl=http://MTD-ZIPKIN-SERVER/
spring.zipkin.locator.discovery.enabled=true
spring.zipkin.enabled=true
...

here MTD-ZIPKIN-SERVER is zipkin-server name in discovery-server.

discovery-server dashboard.

but it does not try to resolve zipkin from discovery-server, instead it tries to connect directly using spring.zipkin.baseUrl, and i get below exception.

Dropped 1 spans due to ResourceAccessException(I/O error on POST request for "http://MTD-ZIPKIN-SERVER/api/v1/spans":
  MTD-ZIPKIN-SERVER; nested exception is java.net.UnknownHostException:
  MTD-ZIPKIN-SERVER)

org.springframework.web.client.ResourceAccessException: I/O error on
  POST request for "http://MTD-ZIPKIN-SERVER/api/v1/spans":
  MTD-ZIPKIN-SERVER; nested exception is java.net.UnknownHostException:
  MTD-ZIPKIN-SERVER     at
  org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:666)
    at
  org.springframework.web.client.RestTemplate.execute(RestTemplate.java:628)
    at
  org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:590)
    at
  org.springframework.cloud.sleuth.zipkin.RestTemplateSender.post(RestTemplateSender.java:73)
    at
  org.springframework.cloud.sleuth.zipkin.RestTemplateSender.sendSpans(RestTemplateSender.java:46)
    at
  zipkin.reporter.AsyncReporter$BoundedAsyncReporter.flush(AsyncReporter.java:245)
    at
  zipkin.reporter.AsyncReporter$Builder.lambda$build$0(AsyncReporter.java:166)
    at zipkin.reporter.AsyncReporter$Builder$$Lambda$1.run(Unknown
  Source)   at java.lang.Thread.run(Thread.java:745) Caused by:
  java.net.UnknownHostException: MTD-ZIPKIN-SERVER  at
  java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)

if i provide exact zipkin url in property spring.zipkin.baseUrl like below

spring.zipkin.baseUrl=http://localhost:5555/

then my rest-microservice is able to connect to zipkin-server.

My goal here is to read zipkin-server location from discovery-srever. What am i doing wrong? Do i need to add some zipkin enabling annotation on my spring-boot rest-microservice?


问:
You need to use a Theme.AppCompat theme (or descendant) with this activity
Android Studio 0.4.5

Android documentation for creating custom dialog boxes: http://developer.android.com/guide/topics/ui/dialogs.html

If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in
the <activity> manifest element:

```<code><activity android:theme="@android:style/Theme.Holo.Dialog" >
</code>```

However, when I tried this I get the following exception:

```<code>java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity
</code>```

I am supporting the following, and I can't using something greater than 10 for the min:

```<code>minSdkVersion 10
targetSdkVersion 19
</code>```

In my styles I have the following:

```<code><!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</code>```

And in my manifest I have this for the activity:

```<code> <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:theme="@android:style/Theme.Holo.Light.Dialog"
            android:name="com.ssd.register.Dialog_update"
            android:label="@string/title_activity_dialog_update" >
        </activity>
</code>```

Creating the dialog box like this was something I was hopping to do, as I have already completed the layout.

Can anyone tell me how I can get around this problem?

答:
I was getting this same problem. Because i was creating custom navigation drawer. But i forget to mention theme in my manifest like this

```<code>android:theme="@style/Theme.AppCompat.NoActionBar"
</code>```

As soon i added the above the theme to my manifest it resolved the problem.

Body:
Android Studio 0.4.5

Android documentation for creating custom dialog boxes: http://developer.android.com/guide/topics/ui/dialogs.html

If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in
the <activity> manifest element:

<activity android:theme="@android:style/Theme.Holo.Dialog" >

However, when I tried this I get the following exception:

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity

I am supporting the following, and I can't using something greater than 10 for the min:

minSdkVersion 10
targetSdkVersion 19

In my styles I have the following:

Body:
I was getting this same problem. Because i was creating custom navigation drawer. But i forget to mention theme in my manifest like this

android:theme="@style/Theme.AppCompat.NoActionBar"

As soon i added the above the theme to my manifest it resolved the problem.


问:
Server Wait file save complete in Asp.net C#
I save image file into folder in Form_Load and used that image in client side.
sometimes does not show image . but after refresh page image show.
I want server wait till image saved complete.

```<code>  System.Drawing.Image barcodeImage = b.Encode(BarcodeLib.TYPE.CODE128, lstTicket[0].Barcode.ToString(), 250, 100);
   barcodeImage.Save(Server.MapPath("~/temp/") + lstTicket[0].Barcode.ToString() + ".jpg");
</code>```

and Client Side

```<code>  <div id="Barcode" style="text-align: center; margin-top: 10px;">
      <img src="/temp/<%=item.Barcode + ".jpg"%>" style="width: 200px; height: 40px;" />
  </div>
</code>```

答:
I'm amazed that the server can't write this image in time, but perhaps you should change the way it's done, rather than filling up the server hard disk with images of barcodes, write a handler that you put into the HTML as the img src e.g <img src="barcode generator.ashx?id=12345" ... and when the client browser calls to that handler to get the barcode, generate it as a png (not jpg, jpg should never be used for barcodes) and send it

See something like this:
Display Image using ashx Handler

Here the guy is getting his avatar image out of db based on primary key supplies in URL - your situation is less complex - you can just generate the barcode data directly (put the barcode value you want to generate into the URL in the HTML , as a parameter

If you need more code samples etc google for something like "generate image dynamically ashx"

Body:
I save image file into folder in Form_Load and used that image in client side.
sometimes does not show image . but after refresh page image show.
I want server wait till image saved complete.

  System.Drawing.Image barcodeImage = b.Encode(BarcodeLib.TYPE.CODE128, lstTicket[0].Barcode.ToString(), 250, 100);
   barcodeImage.Save(Server.MapPath("~/temp/") + lstTicket[0].Barcode.ToString() + ".jpg");

and Client Side

      <img src="/temp/<%=item.Barcode + ".jpg"%>" style="width: 200px; height: 40px;" />


问:
YouTube Upload Error - Upload failed: Can't process file
I am using this sample application for uploading a video on to YouTube. Initially I can able to upload the videos successfully without any issue, but after few days suddenly I have been facing the below error.

https://github.com/youtube/api-samples/tree/master/java

After completing upload, when I check the video in the Videos list of my channel, there it is showing an error(Upload failed: Can't process file) like below

The class I am using is

https://github.com/youtube/api-samples/blob/master/java/src/main/java/com/google/api/services/samples/youtube/cmdline/data/UploadVideo.java

And while executing, the messages in the console are as in the below.

```<code>Jul 15, 2017 2:02:59 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\Krishna\.oauth-credentials
Jul 15, 2017 2:02:59 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\Krishna\.oauth-credentials

is is not empty
Initiation Started
Initiation Completed
Upload in progress
Upload percentage: 10485760
Upload Completed!

================== Returned Video ==================

  - Id: wYB8OfEe9jU
  - Title: ex
  - Tags: [video, file]
  - Privacy Status: public
  - Video Count: 0
</code>```

答:
In situations like these the best thing is to try different little changes:

Change the file extension of your video a few times

Clear your internet cache/files using for example CCleaner

Change your browser

Try using a real Google account to log in to YouTube, as your sample account may have reached an upload limit

I hope these propositions help you. I think the problem you are having is occuring during the conversion or the encoding. Maybe this link could help you.

Body:
I am using this sample application for uploading a video on to YouTube. Initially I can able to upload the videos successfully without any issue, but after few days suddenly I have been facing the below error.

https://github.com/youtube/api-samples/tree/master/java

After completing upload, when I check the video in the Videos list of my channel, there it is showing an error(Upload failed: Can't process file) like below

The class I am using is

https://github.com/youtube/api-samples/blob/master/java/src/main/java/com/google/api/services/samples/youtube/cmdline/data/UploadVideo.java

And while executing, the messages in the console are as in the below.

Jul 15, 2017 2:02:59 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\Krishna\.oauth-credentials
Jul 15, 2017 2:02:59 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\Krishna\.oauth-credentials

is is not empty
Initiation Started
Initiation Completed
Upload in progress
Upload percentage: 10485760
Upload Completed!

================== Returned Video ==================

  - Id: wYB8OfEe9jU
  - Title: ex
  - Tags: [video, file]
  - Privacy Status: public
  - Video Count: 0


问:
java replaceAll with founded value
I want to replace all occurences of insensitive phrase in text with another expression, that contains founded phrase. Example:

```<code>String searchQuery = "word";
String source = "I want find WORD case insensitive, and change fonts of this word";
System.out.println(source.replaceAll("(?i)" + searchQuery, "<font color='red'>" + searchQuery + "</font>"));
</code>```

And I want to get "I want find WORD case insensitive, and change fonts of this word".
But actually the first "WORD" becomes "word", because I replace it wrong.
How can I replace it with original word.

答:
You can use $0 in the replacement string to refer to the matched value:

```<code>source.replaceAll("(?i)" + searchQuery, "<font color='red'>$0</font>")
</code>```

Title: java replaceAll with founded value

Body:
I want to replace all occurences of insensitive phrase in text with another expression, that contains founded phrase. Example:

String searchQuery = "word";
String source = "I want find WORD case insensitive, and change fonts of this word";
System.out.println(source.replaceAll("(?i)" + searchQuery, "" + searchQuery + ""));

And I want to get "I want find WORD case insensitive, and change fonts of this word".
But actually the first "WORD" becomes "word", because I replace it wrong.
How can I replace it with original word.

Body:
You can use $0 in the replacement string to refer to the matched value:

source.replaceAll("(?i)" + searchQuery, "<font color='red'>$0</font>")