问:
creating XML file with LINQ to XML
I need to write linq to xml query of such kind of below xml data

```<code><PRODUCT>
<ID>34169</ID>
<D1>good</D1>
<D2>well</D2>
<L1>lame</L1>
<L2>killer</L2>
<BR>IOMEGA</BR>
<KDV>18</KDV>
<IMG>34169.JPG</IMG>
<EAN>data1</EAN>
<ATP>50+</ATP>
<DM3>0,51</DM3>
<S>
  <L>Tip</L>
  <V>HARICI</V>
</S>
<S>
  <L>Renk</L>
  <V>METALIK GRI</V>
</S>
<S>
  <L>Kapasite (GB)</L>
  <V>500</V>
</S>
<S>
  <L>Dönüş Hızı (Rpm)</L>
  <V>5400,0</V>
</S>
<S>
  <L>Arabirim</L>
  <V>USB 2.0</V>
</S>
<S>
  <L>Form Faktörü (Inch)</L>
  <V>2,5</V>
</S>
<S>
  <L>Ön Bellek (Kb/mb)</L>
  <V>8,0</V>
</S>
<S>
  <L>Satış Garanti Süresi (ay)</L>
  <V>36</V>
</S>
</code>```

my problems are

get only the first image when there
is several images in the
database(img holds the path of an
image as a string in my database
table)

handle the <S> part

I am new to LINQ to XML please help, thanks.

答:
Hope this helps..</p>

```<code>        var productElement = XDocument.Load("product.xml").Root;

        var firstImagePath  = productElement.Element("IMG").Value;
        var sElements = productElement.Elements("S");

        //if you want an object instead of XElements, you can do
        var sElementObjects = sElements.Select(xe => new
                                        {
                                              L = xe.Element("L").Value,
                                              V = xe.Element("V").Value,
                                         });
</code>```

Title: creating XML file with LINQ to XML

Body:
I need to write linq to xml query of such kind of below xml data

<PRODUCT>
<ID>34169</ID>
<D1>good</D1>
<D2>well</D2>
<L1>lame</L1>
<L2>killer</L2>

IOMEGA

<KDV>18</KDV>
34169.JPG
<EAN>data1</EAN>
<ATP>50+</ATP>
<DM3>0,51</DM3>
<S>
  <L>Tip</L>
  <V>HARICI</V>
</S>
<S>
  <L>Renk</L>
  <V>METALIK GRI</V>
</S>
<S>
  <L>Kapasite (GB)</L>
  <V>500</V>
</S>
<S>
  <L>Dönüş Hızı (Rpm)</L>
  <V>5400,0</V>
</S>
<S>
  <L>Arabirim</L>
  <V>USB 2.0</V>
</S>
<S>
  <L>Form Faktörü (Inch)</L>
  <V>2,5</V>
</S>
<S>
  <L>Ön Bellek (Kb/mb)</L>
  <V>8,0</V>
</S>
<S>
  <L>Satış Garanti Süresi (ay)</L>
  <V>36</V>
</S>

my problems are

get only the first image when there
is several images in the
database(img holds the path of an
image as a string in my database
table)

handle the <S> part

I am new to LINQ to XML please help, thanks.

Body:
Hope this helps..

        var productElement = XDocument.Load("product.xml").Root;

        var firstImagePath  = productElement.Element("IMG").Value;
        var sElements = productElement.Elements("S");

        //if you want an object instead of XElements, you can do
        var sElementObjects = sElements.Select(xe => new
                                        {
                                              L = xe.Element("L").Value,
                                              V = xe.Element("V").Value,
                                         });


来源: stackexchange

问:
Unknown BigQuery Google Ads Data Transfer Service error: Non-manager account doesn't exist (or account is not active), so data will not be imported
I have just tried to set up the Google Ads data transfer service for BigQuery. I followed the instructions here and my account has the necessary permissions in both the GCP project and the Google Ads account.

The result was an error message which reads Non-manager account doesn't exist (or account is not active), so data will not be imported.

What is this error message and how can I fix this error?

答: Make sure that the person who created the transfer have necessary permissions then try to recreate the transfer. If the issue persist it might be an issue with Google Ads reports or permissions and if this is the case you would need to contact their support as indicated in the BQ documentation</p>

ContentLicense: CC BY-SA 4.0


问:
Can't select iOS simulator in Xcode
I updated Xcode to the 6.1 version and now I don't understand why I can't select the simulator in the top left corner like in the previous version when I want to run my application. The only choice that appear is a general "iOS device".</p>

答: Go to Window -> Devices and Simulators, check whether there is any Simulator listed. If no, add by clicking over "-" over the lower left corner. Or if devices are there but you are not able to see them in devices to be choose from, then check for deployment target that might not be compatible with Xcode simulators, set target according to your Xcode support and you will see the simulators list.</p>

Title: Can't select iOS simulator in Xcode


问:
Changing CSS of a property via JQuery when toggling sidebar does not work
In my rails application, I am trying to change the margin of my div depending if sidebar is collapsed or not. I am using the .css() method of JQuery and I can't seem to make it work.

Here is my JS snippet:

```<code>document.addEventListener('turbolinks:load', function(){
  $('.openbtn').on('click', function() {
    // This toggles my sidebar
    $('.collapsed-sidebar').toggleClass('displaynone');

    // Checks if the sidebar is collapsed
    if($('.collapsed-sidebar').is(":visible")){

      // So far I have verified that it triggers this alert
      // when I collapse my sidebar
      alert("collapsed sidebar is visible");

      // Class that I am trying to change the CSS Property
      $('.signedin').css({
        'margin-right': '50px !important'
      });
    }

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

Here is my HTML structure:

```<code><body>
    <div class="ui sidebar vertical left menu visible very thin icon">
        <div class="collapsed-sidebar displaynone"> // This is the element that I toggle
             // Sidebar content here
        </div>
    </div>
    <div class="pusher">
        <div class="row content">
            <div class="signedin"> // Element that I am trying to change the property
            </div>
        </div>
    </div>
</body
</code>```

Here is the CSS of my sidebar:

```<code>.displaynone {
  display: none !important;
}

.ui.sidebar.vertical.menu {
  -webkit-transition-duration: 0.1s;
  transition-duration: 0.1s;
}
</code>```

答:
Try this:</p>

```<code>$('.signedin').css("margin-right","50px !important");
</code>```

Body:
In my rails application, I am trying to change the margin of my div depending if sidebar is collapsed or not. I am using the .css() method of JQuery and I can't seem to make it work.

Here is my JS snippet:

document.addEventListener('turbolinks:load', function(){
  $('.openbtn').on('click', function() {
    // This toggles my sidebar
    $('.collapsed-sidebar').toggleClass('displaynone');

    // Checks if the sidebar is collapsed
    if($('.collapsed-sidebar').is(":visible")){

      // So far I have verified that it triggers this alert
      // when I collapse my sidebar
      alert("collapsed sidebar is visible");

      // Class that I am trying to change the CSS Property
      $('.signedin').css({
        'margin-right': '50px !important'
      });
    }

  });
});

Here is my HTML structure:

 // This is the element that I toggle
             // Sidebar content here

 // Element that I am trying to change the property

</body

Here is the CSS of my sidebar:

.displaynone {
  display: none !important;
}

.ui.sidebar.vertical.menu {
  -webkit-transition-duration: 0.1s;
  transition-duration: 0.1s;
}

Body:
Try this:

$('.signedin').css("margin-right","50px !important");


问:
how to get a member with maximum (or minimum ) score from redis sorted set given a subset of members?
I am writing a algo for deducing the user with the least amount of work load. Based on the type/complexity of the tasks being created, i narrow down on the list of the users that are capable of performing it. Now, I need to find the user who has the least number tasks currently assigned to him/her.
I am using redis sorted set to store the members/users along the score indicating the number of the tasks assigned to them.
Is there a way to get a member with least score given a subset of members?</p>

答:
Sorted set element with lowest score:

ZRANGE key 0 0 WITHSCORES

Sorted set element with highest score:

ZREVRANGE key 0 0 WITHSCORES

Time complexity: O(log(N)+M) with N being the number of elements in
  the sorted set and M the number of elements returned.

Docs: https://redis.io/commands/zrange; https://redis.io/commands/zrevrange

ContentLicense: CC BY-SA 3.0


问:
How to integrate QT internationalization to CMake?
Greetings all,

I am trying to use QT internationalization with CMake.
I have configured my cmake file as follows :

```<code>#Internalization - this should generate core_jp.ts ?
SET(rinzo_core_TRANSLATIONS
   i18n/core_jp.ts
   )

#these are my source files in the project
SET(FILES_TO_TRANSLATE
   ${rinzo_core_srcs}
   ${rinzo_core_moh_srcs}
 )

QT4_CREATE_TRANSLATION(QM_FILES ${FILES_TO_TRANSLATE} ${rinzo_core_TRANSLATIONS})
QT4_ADD_TRANSLATION(QM ${rinzo_core_TRANSLATIONS})
</code>```

But it doesnt genereate any TS nor QM files.

My questions -

1.Does Cmake(by using QT tools) generate TS files automatically extracting "tr()" methods from the source ? (that means I dont have to create any TS file and above i18n/core_jp.ts will be genereated automatically)

2.What exacly are QM files ?

Thanks in advance

答:
Translation binary files (*.qm) according to http://itk.org/Wiki/CMake:How_To_Build_Qt4_Software

Also from the bottom of that website

```<code>Usage - Updating the .ts files
</code>```

When you want it to process all your
  source files (looking for new texts to
  translate), configure cmake to turn on
  UPDATE_TRANSLATIONS, and then make
  your project. CMake will modify your
  .ts files in your SOURCE folders in
  addition to generating the .qm files.
  WARNING: Be aware that CMake will be updating the source .ts files, which means that if > you do a make clean, it will DELETE your source .ts files!!! So it would be a good idea > to switch off UPDATE_TRANSLATIONS as soon as possible.

Body:
Greetings all,

I am trying to use QT internationalization with CMake.
I have configured my cmake file as follows :

#Internalization - this should generate core_jp.ts ?
SET(rinzo_core_TRANSLATIONS
   i18n/core_jp.ts
   )

#these are my source files in the project
SET(FILES_TO_TRANSLATE
   ${rinzo_core_srcs}
   ${rinzo_core_moh_srcs}
 )

QT4_CREATE_TRANSLATION(QM_FILES ${FILES_TO_TRANSLATE} ${rinzo_core_TRANSLATIONS})
QT4_ADD_TRANSLATION(QM ${rinzo_core_TRANSLATIONS})

But it doesnt genereate any TS nor QM files.

My questions -

1.Does Cmake(by using QT tools) generate TS files automatically extracting "tr()" methods from the source ? (that means I dont have to create any TS file and above i18n/core_jp.ts will be genereated automatically)

2.What exacly are QM files ?

Thanks in advance

Body:
Translation binary files (*.qm) according to http://itk.org/Wiki/CMake:How_To_Build_Qt4_Software

Also from the bottom of that website

Usage - Updating the .ts files

When you want it to process all your
  source files (looking for new texts to
  translate), configure cmake to turn on
  UPDATE_TRANSLATIONS, and then make
  your project. CMake will modify your
  .ts files in your SOURCE folders in
  addition to generating the .qm files.
  WARNING: Be aware that CMake will be updating the source .ts files, which means that if > you do a make clean, it will DELETE your source .ts files!!! So it would be a good idea > to switch off UPDATE_TRANSLATIONS as soon as possible.


问:
How To Set Ajax Url with Variable
i want to add some string to the url in ajax process, but fail every time i access the function.
when i submit the form it only access this url 'Master_data/' </p>

```<code>var jenis_submit = document.getElementById('jenis_submit');
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}

$.ajax({
    url: '<?php echo base_url();?>Master_data/' + submit_url,
    method: 'POST',
    data: dataKirim,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
        // console.log(data);
        $('#notif').html(data);
    }
});
</code>```

答:
First, get value by id with javascript like this,

```<code>//var number = document.getElementById("number").value; //in your code `.value` is missing

var jenis_submit = document.getElementById('jenis_submit').value;
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}
</code>```

then
Replace your code with this

```<code>url: "<?php echo base_url('master_data/'); ?>" + submit_url,
</code>```

Title: How To Set Ajax Url with Variable

Body:
i want to add some string to the url in ajax process, but fail every time i access the function.
when i submit the form it only access this url 'Master_data/'

var jenis_submit = document.getElementById('jenis_submit');
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}

$.ajax({
    url: '<?php echo base_url();?>Master_data/' + submit_url,
    method: 'POST',
    data: dataKirim,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
        // console.log(data);
        $('#notif').html(data);
    }
});

Body:
First, get value by id with javascript like this,

//var number = document.getElementById("number").value; //in your code `.value` is missing

var jenis_submit = document.getElementById('jenis_submit').value;
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}

then
Replace your code with this

url: "<?php echo base_url('master_data/'); ?>" + submit_url,


问:
Can't connect to MongoDB Atlas (queryTxt ETIMEOUT)
I can't connect to MongoDB Atlas either via driver, mongoshell, or MongoDB compass. Get to error: queryTxt ETIMEOUT

```<code>Error:  { Error: queryTxt ETIMEOUT clustermasjeed1-ekpfe.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:197:19)
  errno: 'ETIMEOUT',
  code: 'ETIMEOUT',
  syscall: 'queryTxt',
  hostname: 'clustermasjeed1-ekpfe.mongodb.net' }
</code>```

I followed the guide from mongodb atlas (mongodb.cloud) on how to connect:

```<code>const MongoClient = require(‘mongodb’).MongoClient;
const uri = "mongodb+srv://<username>:<password>@clustermasjeed1-ekpfe.mongodb.net/test?retryWrites=true";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});
</code>```

with username and password replaced with real string value. I have strong feeling the cause is +srv part. When using mlab before, the connection is only mongodb:// (without the +srv)

答:
Resolved the issue by contacting MongoDB support. The string URI should be changed to:

```<code>mongodb://<username>:<password>@clustermasjeed1-shard-00-00-ekpfe.mongodb.net:27017,clustermasjeed1-shard-00-01-ekpfe.mongodb.net:27017,clustermasjeed1-shard-00-02-ekpfe.mongodb.net:27017/test?ssl=true&replicaSet=ClusterMasjeed1-shard-0&authSource=admin&retryWrites=true
</code>```

These are all the hostnames (primary and secondary) that you can see on the metrics tab of the cluster

Body:
I can't connect to MongoDB Atlas either via driver, mongoshell, or MongoDB compass. Get to error: queryTxt ETIMEOUT

Error:  { Error: queryTxt ETIMEOUT clustermasjeed1-ekpfe.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:197:19)
  errno: 'ETIMEOUT',
  code: 'ETIMEOUT',
  syscall: 'queryTxt',
  hostname: 'clustermasjeed1-ekpfe.mongodb.net' }

I followed the guide from mongodb atlas (mongodb.cloud) on how to connect:

const MongoClient = require(‘mongodb’).MongoClient;
const uri = "mongodb+srv://<username>:<password>@clustermasjeed1-ekpfe.mongodb.net/test?retryWrites=true";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

with username and password replaced with real string value. I have strong feeling the cause is +srv part. When using mlab before, the connection is only mongodb:// (without the +srv)

Body:
Resolved the issue by contacting MongoDB support. The string URI should be changed to:

mongodb://<username>:<password>@clustermasjeed1-shard-00-00-ekpfe.mongodb.net:27017,clustermasjeed1-shard-00-01-ekpfe.mongodb.net:27017,clustermasjeed1-shard-00-02-ekpfe.mongodb.net:27017/test?ssl=true&replicaSet=ClusterMasjeed1-shard-0&authSource=admin&retryWrites=true

These are all the hostnames (primary and secondary) that you can see on the metrics tab of the cluster


问:
Xampp-mysql - "Table doesn't exist in engine" #1932
Xampp error after moving xampp folder:

Apache is running fine:

as given below image i'm sucess to run apache but unable to run mysql if in case i moved and run xampp both apache and mysql but its shows error which is fresh and it show the error like "Table doesn't exist in engine" #1932 as given up image. please solve the issue anyone help pls

答:
stop mysql

copy xampp\mysql\data\ib* from old server to new server

start mysql


问:
Write a python code to create a new csv column from existing column using conditional statements
I'm new to python coding and wanted to create a new column based on the condition statement on existing columns.

I use python 2.7 version and run the code on CentOs.

```<code>import pandas as pd
file1 = pd.read_csv("/root/Documents/temp_file_{}.csv".format(timestr))
file1['FileName'] = ''
file1['FileName'] = file1['FileType'].apply(lambda x: df['Path'].str.extract('[^/]+$', expand=False) if x=='f' else '')
file1.to_csv('/root/Documents/temp1_file_{}.csv'.format(timestr),index = False)
</code>```

Below is my CSV file:

```<code>FileType,Path

d,/

f,/documents/csv/.zip

d,/documents/images

d,/hive/28374849

f,/hadoop/jdjdjd/dnejfn.img
</code>```

Required CSV file:

```<code>FileType,Path,FileName

d,/,

f,/documents/csv/.zip,.zip

d,/documents/images,

d,/hive/28374849,

f,/hadoop/jdjdjd/dnejfn.img,dnejfn.img
</code>```

I want to create a new column FileName where the data in that column should be extracted from Path column only when column Filetype=='f' else the data in that column should be a null value or no data

答:
Try using this approach to get the last part from the paths. Split the string from the rightmost side one time using "/" as a separator and fetch the last element (which is basically the filename) using the negative indexing:

```<code>
file1['FileName'] = ''
file1['FileName'] = file1.apply(lambda x: x['Path'].rsplit("/", 1)[-1]  if x["FileType"]=='f' else '' , axis=1)

file1

FileType    Path    FileName
0   d   /
1   f   /documents/csv/.zip .zip
2   d   /documents/images
3   d   /hive/28374849
4   f   /hadoop/jdjdjd/dnejfn.img   dnejfn.img
</code>```

using numpy's where which is faster than the apply function because of the vectorization:

```<code>file1['FileName'] = np.where(file1["FileType"]=='f', file1['Path'].str.rsplit("/", n=1).str[-1], '')

FileType    Path    FileName
0   d   /
1   f   /documents/csv/.zip .zip
2   d   /documents/images
3   d   /hive/28374849
4   f   /hadoop/jdjdjd/dnejfn.img   dnejfn.img

</code>```

Body:
I'm new to python coding and wanted to create a new column based on the condition statement on existing columns.

I use python 2.7 version and run the code on CentOs.

import pandas as pd
file1 = pd.read_csv("/root/Documents/temp_file_{}.csv".format(timestr))
file1['FileName'] = ''
file1['FileName'] = file1['FileType'].apply(lambda x: df['Path'].str.extract('[^/]+$', expand=False) if x=='f' else '')
file1.to_csv('/root/Documents/temp1_file_{}.csv'.format(timestr),index = False)

Below is my CSV file:

FileType,Path

d,/

f,/documents/csv/.zip

d,/documents/images

d,/hive/28374849

f,/hadoop/jdjdjd/dnejfn.img

Required CSV file:

FileType,Path,FileName

d,/,

f,/documents/csv/.zip,.zip

d,/documents/images,

d,/hive/28374849,

f,/hadoop/jdjdjd/dnejfn.img,dnejfn.img

I want to create a new column FileName where the data in that column should be extracted from Path column only when column Filetype=='f' else the data in that column should be a null value or no data

Body:
Try using this approach to get the last part from the paths. Split the string from the rightmost side one time using "/" as a separator and fetch the last element (which is basically the filename) using the negative indexing:

file1['FileName'] = ''
file1['FileName'] = file1.apply(lambda x: x['Path'].rsplit("/", 1)[-1]  if x["FileType"]=='f' else '' , axis=1)

file1

FileType    Path    FileName
0   d   /
1   f   /documents/csv/.zip .zip
2   d   /documents/images
3   d   /hive/28374849
4   f   /hadoop/jdjdjd/dnejfn.img   dnejfn.img

using numpy's where which is faster than the apply function because of the vectorization:

file1['FileName'] = np.where(file1["FileType"]=='f', file1['Path'].str.rsplit("/", n=1).str[-1], '')

FileType    Path    FileName
0   d   /
1   f   /documents/csv/.zip .zip
2   d   /documents/images
3   d   /hive/28374849
4   f   /hadoop/jdjdjd/dnejfn.img   dnejfn.img


问:
Bundle.js is not in any folder of my application despite devtool saying the opposite
first I am NOT using webpack, its a full MERN stack application.

I run Lighthouse to test my app performance and it says to minify Bundle.js, it has been two hours or more...and still can't find it.

in my index.html there is a line that I am NOT seeing it in my code but appear in the inspector (devtool)

```<code><script type="text/javascript" src="/static/js/bundle.js"> </script>
</code>```

i tried to add my workspace to chrome dev tools to locate it, but still doesn't work

enter image description here

答:
I found it,

When you run npm start in any of the examples, an Express server will start which will use Webpack to server /static/bundle.js in development.

here it is ...
https://github.com/reduxjs/redux/issues/1137

Body:
first I am NOT using webpack, its a full MERN stack application.

I run Lighthouse to test my app performance and it says to minify Bundle.js, it has been two hours or more...and still can't find it.

in my index.html there is a line that I am NOT seeing it in my code but appear in the inspector (devtool)

i tried to add my workspace to chrome dev tools to locate it, but still doesn't work

enter image description here


问:
Add a volume to Docker, but exclude a sub-folder
Supposed I have a Docker container and a folder on my host /hostFolder. Now if I want to add this folder to the Docker container as a volume, then I can do this either by using ADD in the Dockerfile or mounting it as a volume.

So far, so good.

Now /hostFolder contains a sub-folder, /hostFolder/subFolder.

I want to mount /hostFolder into the Docker container (whether as read-write or read-only does not matter, works both for me), but I do NOT want to have it included /hostFolder/subFolder. I want to exclude this, and I also want the Docker container be able to make changes to this sub-folder, without the consequence of having it changed on the host as well.

Is this possible? If so, how?

答:
With the docker command line:

```<code>docker run \
    --mount type=bind,src=/hostFolder,dst=/containerFolder \
    --mount type=volume,dst=/containerFolder/subFolder \
    ...other-args...
</code>```

The -v option may also be used (credit to Bogdan Mart), but --mount is clearer and recommended.

Body:
With the docker command line:

docker run \
    --mount type=bind,src=/hostFolder,dst=/containerFolder \
    --mount type=volume,dst=/containerFolder/subFolder \
    ...other-args...

The -v option may also be used (credit to Bogdan Mart), but --mount is clearer and recommended.


问:
Reset screen point to the top of screen in Windows & Linux console
I have a little routine that's run under Linux and Windows written in C and displays output on the console. I'm not linking in any form of curses or anything like that.

Currently I clear the screen using

```<code>#ifdef __WIN32
  system( "cls" );
#else
  system( "clear" );
#endif
</code>```

Then I have a bunch of printf statements to update the status. What I'd like just reset the screenpointer to 0,0 so I can then just overlay my printfs. I'd rather avoid compiling in any more extensions especially since I'm coding for 2 different OS'.

答:
Looks like I may have found a windows specific way of doing it SetConsoleCursorPosition

Ansi escape sequence  \033[0;0H for Linux - just printf that to the console.

OwnerDisplayName: Paul Hargreaves

ContentLicense: CC BY-SA 2.5

Body:
I have a little routine that's run under Linux and Windows written in C and displays output on the console. I'm not linking in any form of curses or anything like that.

Currently I clear the screen using

#ifdef __WIN32
  system( "cls" );
#else
  system( "clear" );
#endif

Then I have a bunch of printf statements to update the status. What I'd like just reset the screenpointer to 0,0 so I can then just overlay my printfs. I'd rather avoid compiling in any more extensions especially since I'm coding for 2 different OS'.

LastEditorDisplayName: Paul Hargreaves


问:
PHP Function pt_register
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

```<code>function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}
</code>```

Can anyone walk through this in English for me?

答:
Too many useful answers to comment on all of them so I'll just answer my own questions with a big THANKS.

In my newer forms I wrote my own processing script with the format as suggest by Ferdinand.

$value = $_POST['value'];

I was looking at some older stuff, still in use, and was trying to figure out what it did, and why, to determine if I was taking an unsafe shortcut in my new code. In fact, the opposite is true and I need to update the old code to use the same approach as I use now... and whatever breaks needs to be fixed in some other way. The security issues of Globals are not lost on me.

It's very surprising that in 20 pages of Google results for "pt_register" I found TONS of people using the exact same function (I wonder where it originally came from) and no mention of it's inherent risks/evilness.

Thanks to everyone for the instantaneous answers and useful information. This site has a new fan.

OwnerDisplayName: HaArD

Title: PHP Function pt_register

Body:
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}

Can anyone walk through this in English for me?

LastEditorDisplayName: RoBorg


问:
Wordpress: how to fire a function (myTheme/functions.php) when cron es executed?
I just reformulated this question here: Linux + Wordpress: how to fired a function from a Linux Cron job?

Should I close or delete this question?

Just this,how to fire a function (myTheme/functions.php) when cron es executed?

Do I need a hook or action.

I created a real cron job in my Linux server and disabled the Worpress native cron with this line define('DISABLE_WP_CRON', true);

I will be executed at 00hs every day.

Then, every time the cron is executed I want to execute some taks inside a function.

I read that this function could be useful, but not sure...

```<code>function fac_all_crons(){
 here my tasks...
}
</code>```

答:
In your cron job, you can include wordpress environment by the following :

```<code><?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
?>
</code>```

This will enable you to call any function from your functions.php in your code where you want.

Body:
I just reformulated this question here: Linux + Wordpress: how to fired a function from a Linux Cron job?

Should I close or delete this question?

Just this,how to fire a function (myTheme/functions.php) when cron es executed?

Do I need a hook or action.

I created a real cron job in my Linux server and disabled the Worpress native cron with this line define('DISABLE_WP_CRON', true);

I will be executed at 00hs every day.

Then, every time the cron is executed I want to execute some taks inside a function.

I read that this function could be useful, but not sure...

function fac_all_crons(){
 here my tasks...
}

Body:
In your cron job, you can include wordpress environment by the following :

<?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
?>

This will enable you to call any function from your functions.php in your code where you want.


问:
How to Highlight the `Selected row` in a `Listview` using Fragments
I created a listview that is acting as a menu. When the user chooses a specific menu, another fragment will show up on the right portion.

Please see this image:

The problem is, the icon and the title are only highlighted and not the whole selected row. How can I highlight the selected row instead of the icon and title only?

This is my code:

fragment_inventory_list.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".InventoryListFragment"
    android:layout_marginTop="@dimen/padding_50"
    android:orientation="vertical"
    android:background="?android:attr/activatedBackgroundIndicator">

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

       <ListView
           android:id="@+id/inventorylist_listview"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:choiceMode="singleChoice"
           android:listSelector="@color/light_gray"/>

   </LinearLayout>

</LinearLayout>
</code>```

InventoryListFragment.java

```<code>package com.example.devcash;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.devcash.CustomAdapters.InventoryListAdapter;
import com.example.devcash.Fragments.CategoriesFragment;
import com.example.devcash.Fragments.DiscountsFragment;
import com.example.devcash.Fragments.ProductsFragment;
import com.example.devcash.Fragments.ServicesFragment;
import com.example.devcash.Lists.InventoryList;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class InventoryListFragment extends Fragment implements AdapterView.OnItemClickListener {

    ListView lvinventory;
    ArrayList<InventoryList> list = new ArrayList<InventoryList>();
    InventoryListAdapter adapter;

    public InventoryListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_inventory_list, container, false);

        lvinventory = (ListView) view.findViewById(R.id.inventorylist_listview);
        adapter = new InventoryListAdapter(getActivity(),list);

        list.add(new InventoryList(R.drawable.ic_product,"Products"));
        list.add(new InventoryList(R.drawable.ic_services,"Services"));
        list.add(new InventoryList(R.drawable.ic_category, "Categories"));
        list.add(new InventoryList(R.drawable.ic_local_offer,"Discounts"));

        lvinventory.setAdapter(adapter);
        lvinventory.setOnItemClickListener(this);

        return view;
    }

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

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InventoryList selectedList = this.list.get(position);

        int icon = selectedList.getIcon();
        String title = selectedList.getInventory_title();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (position){
            case 0:
                ProductsFragment productsFragment = new ProductsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, productsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 1:
                ServicesFragment servicesFragment = new ServicesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, servicesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case  2:
                CategoriesFragment categoriesFragment = new CategoriesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, categoriesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 3:
                DiscountsFragment discountsFragment = new DiscountsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, discountsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
        }
    }
}
</code>```

答:
in your adapter getView()  , just add a click listener and set the background color

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
       ....
       ....

 view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           view.setBackgroundColor(Color.GREY);
        }
    });
     ....
     ....

    return view;
  }
</code>```

Body:
I created a listview that is acting as a menu. When the user chooses a specific menu, another fragment will show up on the right portion.

Please see this image:

The problem is, the icon and the title are only highlighted and not the whole selected row. How can I highlight the selected row instead of the icon and title only?

This is my code:

fragment_inventory_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".InventoryListFragment"
    android:layout_marginTop="@dimen/padding_50"
    android:orientation="vertical"
    android:background="?android:attr/activatedBackgroundIndicator">

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

       <ListView
           android:id="@+id/inventorylist_listview"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:choiceMode="singleChoice"
           android:listSelector="@color/light_gray"/>

   </LinearLayout>

</LinearLayout>

InventoryListFragment.java

package com.example.devcash;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.devcash.CustomAdapters.InventoryListAdapter;
import com.example.devcash.Fragments.CategoriesFragment;
import com.example.devcash.Fragments.DiscountsFragment;
import com.example.devcash.Fragments.ProductsFragment;
import com.example.devcash.Fragments.ServicesFragment;
import com.example.devcash.Lists.InventoryList;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class InventoryListFragment extends Fragment implements AdapterView.OnItemClickListener {

    ListView lvinventory;
    ArrayList<InventoryList> list = new ArrayList<InventoryList>();
    InventoryListAdapter adapter;

    public InventoryListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_inventory_list, container, false);

        lvinventory = (ListView) view.findViewById(R.id.inventorylist_listview);
        adapter = new InventoryListAdapter(getActivity(),list);

        list.add(new InventoryList(R.drawable.ic_product,"Products"));
        list.add(new InventoryList(R.drawable.ic_services,"Services"));
        list.add(new InventoryList(R.drawable.ic_category, "Categories"));
        list.add(new InventoryList(R.drawable.ic_local_offer,"Discounts"));

        lvinventory.setAdapter(adapter);
        lvinventory.setOnItemClickListener(this);

        return view;
    }

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

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InventoryList selectedList = this.list.get(position);

        int icon = selectedList.getIcon();
        String title = selectedList.getInventory_title();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (position){
            case 0:
                ProductsFragment productsFragment = new ProductsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, productsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 1:
                ServicesFragment servicesFragment = new ServicesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, servicesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case  2:
                CategoriesFragment categoriesFragment = new CategoriesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, categoriesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 3:
                DiscountsFragment discountsFragment = new DiscountsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, discountsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
        }
    }
}

Body:
in your adapter getView()  , just add a click listener and set the background color

@Override
public View getView(int position, View convertView, ViewGroup parent) {
       ....
       ....

 view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           view.setBackgroundColor(Color.GREY);
        }
    });
     ....
     ....

    return view;
  }


问:
How to sort strings in java , order shoud display Capital Strings first
Need to sort strings in java in a case sensitive, but Capital letters should display first.

What I tried:

```<code>List<String> l = Arrays.asList("aaa","AAA","AAA","aaa","BBB","ccc","CCC");
l.stream().sorted(String.CASE_INSENSITIVE_ORDER);
System.out.println(l);`
</code>```

Output:

```<code>[aaa, AAA, AAA, aaa, BBB, ccc, CCC]
</code>```

Expecting Output:

```<code>[AAA,AAA,aaa,aaa,BBB,CCC,ccc]
</code>```

答:
You can add a second comparator to decide on the ordering after you have compared them ignoring the case. The second comparator orders based on the casing of the characters.

```<code>List<String> l = Arrays.asList("a","A","A","a","B","c","C");
l.sort(String.CASE_INSENSITIVE_ORDER
          .thenComparing(Comparator.comparing(YourClass::isUpperCase)
             .reversed()));

private static boolean isUpperCase(String s) {
    return Character.isUpperCase(s.charAt(0));
}
</code>```

The Comparator.comparing uses a helper method to determine if a string is upper cased. The return type of this method is a boolean. The natural ordering of boolean is false followed by true. Hence, you have to reverse it to get the upper-cased characters (strings) first.

Note: You should have used characters rather than strings here (if all the Strings have just one character). The helper method here just checks for the first character in this String which sounds odd!.

Alternatively, if you have a method for checking for lower case, you can simplify this as

```<code>l.sort(String.CASE_INSENSITIVE_ORDER
      .thenComparing(YourClass::isLowerCase));

private static boolean isLowerCase(String s) {
    return Character.isLowerCase(s.charAt(0));
}
</code>```

UPDATE: (as per OP update of the question).

If the string has multi characters and if you want to order based on the condition that upper-cased strings must come first before others, you can do like.

```<code>l.sort(String.CASE_INSENSITIVE_ORDER
        .thenComparing(YourClass::areAllCharactersLowerCase));

private static boolean areAllCharactersLowerCase(String s) {
    return s.chars()
            .mapToObj(c -> (char)c)
            .allMatch(Character::isLowerCase);
}
</code>```

Note: With this, string like CCc and Ccc will be treated equal as per the first comparator and the second comparator will return false for both (treating them equal again). So, they appear in the same order as appeared in the input.

EDIT 2: Based on the OP comment

What if it has strings like AAa or aAA or AaA?

@user7 then AAa,AaA,aAA should be the order.

I guess your intention is to order the strings by comparing character by character and the string that has the most consecutive upper-cased character will be considered to be listed before others.

The below code compares char-by-char and handles the following scenarios

If the current char of String a is upper-cased and the current char of String bis lower-cased, then String a comes before b.

If the current char of String a is lower-cased and the current char of String bis upper-cased, then String b comes before a

Else, both have same char.. Keep searching.

For equal strings, we return 0 at the end.

```<code> l.sort(String.CASE_INSENSITIVE_ORDER
        .thenComparing((a, b) -> {
            //String a and b are equal when compared ignoring case (and hence same length)
            for (int i = 0; i < a.length(); i++) {
                if (Character.isUpperCase(a.charAt(i)) && Character.isLowerCase(b.charAt(i))) {
                    return -1;
                } else if (Character.isLowerCase(a.charAt(i)) && Character.isUpperCase(b.charAt(i))) {
                    return 1;
                }
            }
            return 0;
        }));
</code>```

Body:
Need to sort strings in java in a case sensitive, but Capital letters should display first.

What I tried:

List<String> l = Arrays.asList("aaa","AAA","AAA","aaa","BBB","ccc","CCC");
l.stream().sorted(String.CASE_INSENSITIVE_ORDER);
System.out.println(l);`

Output:

[aaa, AAA, AAA, aaa, BBB, ccc, CCC]

Expecting Output:

[AAA,AAA,aaa,aaa,BBB,CCC,ccc]

Body:
You can add a second comparator to decide on the ordering after you have compared them ignoring the case. The second comparator orders based on the casing of the characters.

List<String> l = Arrays.asList("a","A","A","a","B","c","C");
l.sort(String.CASE_INSENSITIVE_ORDER
          .thenComparing(Comparator.comparing(YourClass::isUpperCase)
             .reversed()));

private static boolean isUpperCase(String s) {
    return Character.isUpperCase(s.charAt(0));
}

The Comparator.comparing uses a helper method to determine if a string is upper cased. The return type of this method is a boolean. The natural ordering of boolean is false followed by true. Hence, you have to reverse it to get the upper-cased characters (strings) first.

Note: You should have used characters rather than strings here (if all the Strings have just one character). The helper method here just checks for the first character in this String which sounds odd!.

Alternatively, if you have a method for checking for lower case, you can simplify this as

l.sort(String.CASE_INSENSITIVE_ORDER
      .thenComparing(YourClass::isLowerCase));

private static boolean isLowerCase(String s) {
    return Character.isLowerCase(s.charAt(0));
}

UPDATE: (as per OP update of the question).

If the string has multi characters and if you want to order based on the condition that upper-cased strings must come first before others, you can do like.

l.sort(String.CASE_INSENSITIVE_ORDER
        .thenComparing(YourClass::areAllCharactersLowerCase));

private static boolean areAllCharactersLowerCase(String s) {
    return s.chars()
            .mapToObj(c -> (char)c)
            .allMatch(Character::isLowerCase);
}

Note: With this, string like CCc and Ccc will be treated equal as per the first comparator and the second comparator will return false for both (treating them equal again). So, they appear in the same order as appeared in the input.

EDIT 2: Based on the OP comment

What if it has strings like AAa or aAA or AaA?

@user7 then AAa,AaA,aAA should be the order.

I guess your intention is to order the strings by comparing character by character and the string that has the most consecutive upper-cased character will be considered to be listed before others.

The below code compares char-by-char and handles the following scenarios

If the current char of String a is upper-cased and the current char of String bis lower-cased, then String a comes before b.

If the current char of String a is lower-cased and the current char of String bis upper-cased, then String b comes before a

Else, both have same char.. Keep searching.

For equal strings, we return 0 at the end.

 l.sort(String.CASE_INSENSITIVE_ORDER
        .thenComparing((a, b) -> {
            //String a and b are equal when compared ignoring case (and hence same length)
            for (int i = 0; i < a.length(); i++) {
                if (Character.isUpperCase(a.charAt(i)) && Character.isLowerCase(b.charAt(i))) {
                    return -1;
                } else if (Character.isLowerCase(a.charAt(i)) && Character.isUpperCase(b.charAt(i))) {
                    return 1;
                }
            }
            return 0;
        }));


问:
These lines should change all objects in the list into integers, but they're still showing up as strings
So I have a list, playerlocation, which I am using as coordinates. The coordinates are entered with an input() command, so they appear as strings rather than integers. I thought this block of code would solve it,

playerlocation =(input("Player location?"))
playerlocation = list(playerlocation.split(","))

for x in playerlocation:
try:
     x = int(x)
     coordsareintegers = True
     print(playerlocation)
except:
     coordsareintegers = False
```

but print(playerlocation) is returning something like ['1','1'], meaning they're still strings.

I've tried using an int() command wherever the coordinates are used, but that's really tedious.

答:
You can use map on your input. Something like:

```<code>>>> coords = '1,2'
>>> split = coords.split(',')
>>> split
['1', '2']
>>> ints = map(int, split)
>>> ints
<map object at 0x0000000002476978>
>>> list(ints)
[1, 2]
</code>```

Apply accordingly to your code.

Body:
So I have a list, playerlocation, which I am using as coordinates. The coordinates are entered with an input() command, so they appear as strings rather than integers. I thought this block of code would solve it,

playerlocation =(input("Player location?"))
playerlocation = list(playerlocation.split(","))

for x in playerlocation:
try:
     x = int(x)
     coordsareintegers = True
     print(playerlocation)
except:
     coordsareintegers = False

but print(playerlocation) is returning something like ['1','1'], meaning they're still strings.

I've tried using an int() command wherever the coordinates are used, but that's really tedious.

Body:
You can use map on your input. Something like:

>>> coords = '1,2'
>>> split = coords.split(',')
>>> split
['1', '2']
>>> ints = map(int, split)
>>> ints
<map object at 0x0000000002476978>
>>> list(ints)
[1, 2]

Apply accordingly to your code.


问:
Greying out certain parts of html until a radio button is checked
I have a weird request i havent had before and im not sure how to go about it.

Basically i have an online application form, each question is contained in its own div, at first i want the first div shown and the rest of the questions to be 'greyed' out, then when someone clicks a radio button for the first question, the second question then ungreys itself and so on.

The code for the HTML i have so far is below, i was wondering if someone could help me out with this.

```<code><div class="line">
    <label><span>1.</span>This is a first question?</label>
    <div class="right-box small">
        <input type="radio" name="" value=""><label style="padding-left: 3px; padding-right: 24px;">No</label><input type="radio" name="" value=""><label style="padding-left: 3px;">Yes</label>
    </div>
</div>
<div class="line">
    <label><span>2.</span>This is a second question?</label>
    <div class="right-box small">
        <input type="radio" name="" value=""><label style="padding-left: 3px; padding-right: 24px;">No</label><input type="radio" name="" value=""><label style="padding-left: 3px;">Yes</label>
    </div>
</div>

<div class="line">
    <label><span>3.</span>This is a third question?</label>
    <div class="right-box small">
        <input type="radio" name="" value=""><label style="padding-left: 3px; padding-right: 24px;">No</label><input type="radio" name="" value=""><label style="padding-left: 3px;">Yes</label>
    </div>
</div>
</code>```

答:
Use Jquery and a combination of show / hide or adding and removing disabled attributes.

Show / hide:

```<code>$('.line').show(); // would show all
$('.line').hide(); // would hide all

$('#yourId').show(); // would show one element
$('#yourId').hide(); // would hide one element
</code>```

Disabled / enabled:

```<code>$('#yourId').attr('disabled',true); // would disable
$('#yourId')..removeAttr('disabled'); // would enable
</code>```

Click event:

```<code>$('#yourId').click(function() {
  // Do action for the clicked input show next element, enabled etc
});
</code>```

Opacity to a div:

```<code>$("#yourId").css({ opacity: 0.5 });
</code>```

This should give you an idea of how to go about this. Hope it helps

Body:
I have a weird request i havent had before and im not sure how to go about it.

Basically i have an online application form, each question is contained in its own div, at first i want the first div shown and the rest of the questions to be 'greyed' out, then when someone clicks a radio button for the first question, the second question then ungreys itself and so on.

The code for the HTML i have so far is below, i was wondering if someone could help me out with this.

    1.This is a first question?

        <input type="radio" name="" value="">No<input type="radio" name="" value="">Yes

    2.This is a second question?

        <input type="radio" name="" value="">No<input type="radio" name="" value="">Yes

    3.This is a third question?

        <input type="radio" name="" value="">No<input type="radio" name="" value="">Yes

Body:
Use Jquery and a combination of show / hide or adding and removing disabled attributes.

Show / hide:

$('.line').show(); // would show all
$('.line').hide(); // would hide all

$('#yourId').show(); // would show one element
$('#yourId').hide(); // would hide one element

Disabled / enabled:

$('#yourId').attr('disabled',true); // would disable
$('#yourId')..removeAttr('disabled'); // would enable

Click event:

$('#yourId').click(function() {
  // Do action for the clicked input show next element, enabled etc
});

Opacity to a div:

$("#yourId").css({ opacity: 0.5 });

This should give you an idea of how to go about this. Hope it helps


问:
render a div conditionally using props in ReactJS
I'm very new to react and I'm trying to show a message after I have submitted a post response, but it's not showing it.

Note: the POST response is working correctly. The message needs to show when the status in the app.js gets updated. It looks like the value of status is getting passed down only once when the pages renders for the first time.

APP.JS

```<code>class App extends Component {
  status = null;
  submit = async values => {
    const response = await providers.post('/providers/', {
      params: {
        values
      }
    });
    this.status = response.status;
    if (this.status === 200) {
      this.getInitialValues();
      this.myFormRef.reset();
    } else {
      console.log('ERROR: There was an error creating a new Provider');
    }
  };

  render() {
    return (
      <div className='registration-form ui container'>
        <img src={logo} alt={logo} />
        <h1>New Provider Form</h1>
        <Form
          onSubmit={this.submit}
          initialValues={this.getInitialValues()}
          ref={el => (this.myFormRef = el)}
        />
        <Status status={this.status} />
      </div>
    );
  }
</code>```

STATUS.JS

```<code>import React from 'react';
const Status = props => {
  console.log(props.status);
  if (props.status === 200) {
    return <div className='status'>Provider Successfully Registered!</div>;
  } else if (props.status > 200) {
    return <div className='status'>ERROR: Couldn't register new provider</div>;
  } else {
    return null;
  }
};

export default Status;
</code>```

答:
Use state for re-render</p>

```<code>class App extends Component {
  state = {
    status: '',
  };
  submit = async values => {
    const response = await providers.post('/providers/', {
      params: {
        values
      }
    });
    this.setState({
      status: response.status,
    });
    //this.status = response.status;
    if (response.status === 200) {
      this.getInitialValues();
      this.myFormRef.reset();
    } else {
      console.log('ERROR: There was an error creating a new Provider');
    }
  };
  render() {
    return (
     ...
     <Status status = {this.state.status}/>
     ...
    );
  }
</code>```

Body:
I'm very new to react and I'm trying to show a message after I have submitted a post response, but it's not showing it.

Note: the POST response is working correctly. The message needs to show when the status in the app.js gets updated. It looks like the value of status is getting passed down only once when the pages renders for the first time.

APP.JS

class App extends Component {
  status = null;
  submit = async values => {
    const response = await providers.post('/providers/', {
      params: {
        values
      }
    });
    this.status = response.status;
    if (this.status === 200) {
      this.getInitialValues();
      this.myFormRef.reset();
    } else {
      console.log('ERROR: There was an error creating a new Provider');
    }
  };

  render() {
    return (

New Provider Form

        <Form
          onSubmit={this.submit}
          initialValues={this.getInitialValues()}
          ref={el => (this.myFormRef = el)}
        />
        <Status status={this.status} />

    );
  }

STATUS.JS

import React from 'react';
const Status = props => {
  console.log(props.status);
  if (props.status === 200) {
    return
Provider Successfully Registered!
;
  } else if (props.status > 200) {
    return
ERROR: Couldn't register new provider
;
  } else {
    return null;
  }
};

export default Status;

Body:
Use state for re-render

class App extends Component {
  state = {
    status: '',
  };
  submit = async values => {
    const response = await providers.post('/providers/', {
      params: {
        values
      }
    });
    this.setState({
      status: response.status,
    });
    //this.status = response.status;
    if (response.status === 200) {
      this.getInitialValues();
      this.myFormRef.reset();
    } else {
      console.log('ERROR: There was an error creating a new Provider');
    }
  };
  render() {
    return (
     ...
     <Status status = {this.state.status}/>
     ...
    );
  }


问:
Vagrant VirtualBox Cisco AnyConnect routing issues with VPN
So I'm having what I believe is a common issue with Cisco AnyConnect and Vagrant/VirtualBox, i'm using host-only networking so that I can stand up a virtual server at an ip such as 10.10.10.11 and then I can map this in my /etc/hosts to :

```<code># IP to hostname mapping
10.10.10.10 vagrant.dev
</code>```

And then I can pull a webpage from curl vagrant.dev for example.  Real standard stuff.

Things go awry when I connect to my work VPN which makes this nice little dev box kind of useless as I can no longer hit it by hostname or ip any longer.  I can still do a vagrant ssh to the box but there is no other way to hit it.

I tried taking a look at the routing table and it appears that my pre-vbox route entry (netstat -rn):

```<code>Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
</code>```

PreVPN

```<code>10.10.10/24        link#11            UCS             1        0 vboxnet
10.10.10.11        8:0:27:96:91:84    UHLWIi          1       70 vboxnet   1197
</code>```

PostVPN

```<code>10.10.10/24        link#19            UCS             1        0   utun1
10.10.10.11        link#19            UHW3I           0        4   utun1     62
</code>```

Route Flag Description

```<code>|PRE|POST|           Flag Description                    |
|---|----|-----------------------------------------------|
| U |  U | Route usable                                  |
| H |  H | Host entry (net otherwise)                    |
| L |    | Valid protocol to link address translation    |
| W |  W | Route was generated as a result of cloning    |
|   |  3 | Protocol specified route flag #3              |
| I |  I | Route is assocaited with an interface scope   |
| i |    | Route is a holding reference to the interface |
</code>```

Question

Is it possible to restore the routes changed by VPN in order to make my vagrant connections work again? And if-so how?

Other Data

Full Route Table (PRE) (IP4 only)

```<code>Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            192.168.2.1        UGSc           23        1     en0
10.10.10/24        link#11            UCS             1        0 vboxnet
10.10.10.11        8:0:27:96:91:84    UHLWIi          1       70 vboxnet   1197
127                127.0.0.1          UCS             0        7     lo0
127.0.0.1          127.0.0.1          UH             11   128344     lo0
169.254            link#4             UCS             0        0     en0
192.168.2          link#4             UCS             0        0     en0
192.168.2.1        68:7f:74:81:8b:b0  UHLSr          27      126     en0
192.168.2.106/32   link#4             UCS             0        0     en0
</code>```

Full Route Table (POST) (IP4 only)

```<code>Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            link#19            UCS             9        0   utun1
default            192.168.2.1        UGScI           3        0     en0
10.10.10/24        link#19            UCS             1        0   utun1
10.10.10.11        link#19            UHW3I           0        4   utun1     62
17.158.10.25       link#19            UHW3I           0        1   utun1     62
17.158.10.42       link#19            UHW3I           0       20   utun1     62
17.158.10.46       link#19            UHW3I           0        1   utun1     62
127                127.0.0.1          UCS             0        7     lo0
127.0.0.1          127.0.0.1          UH             15   128507     lo0
128.29.154.114     link#19            UHWIi          31      117   utun1
129.83.20.9        link#19            UHW3I           0       20   utun1     61
129.83.26.209      link#19            UHWIi           2        2   utun1
129.83.100.38      link#19            UHW3I           0       46   utun1     62
169.254            link#19            UCS             0        0   utun1
172.31.160/19      link#19            UCS             0        0   utun1
172.31.163.172/32  127.0.0.1          UGSc            3       67     lo0
192.80.55.9/32     192.168.2.1        UGSc            1        0     en0
192.168.2          link#19            UCS             0        0   utun1
192.168.2.1        68:7f:74:81:8b:b0  UHLSr           7        8     en0
192.168.2.1/32     link#19            UCS             0        0   utun1
192.168.2.106/32   link#4             UCS             0        0     en0
216.58.217.132     link#19            UHW3I           0        2   utun1     59
239.255.255.250    link#19            UHmW3I          0       17   utun1     62
</code>```

Components

OSX

Cisco Any Connect

VirtualBox 5.0.8

答: When facing this exact same problem what worked for us is to change the address of the Vagrant box to 11.0.0.100</p>

Body:
So I'm having what I believe is a common issue with Cisco AnyConnect and Vagrant/VirtualBox, i'm using host-only networking so that I can stand up a virtual server at an ip such as 10.10.10.11 and then I can map this in my /etc/hosts to :

# IP to hostname mapping
10.10.10.10 vagrant.dev

And then I can pull a webpage from curl vagrant.dev for example.  Real standard stuff.

Things go awry when I connect to my work VPN which makes this nice little dev box kind of useless as I can no longer hit it by hostname or ip any longer.  I can still do a vagrant ssh to the box but there is no other way to hit it.

I tried taking a look at the routing table and it appears that my pre-vbox route entry (netstat -rn):

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire

PreVPN

10.10.10/24        link#11            UCS             1        0 vboxnet
10.10.10.11        8:0:27:96:91:84    UHLWIi          1       70 vboxnet   1197

PostVPN

10.10.10/24        link#19            UCS             1        0   utun1
10.10.10.11        link#19            UHW3I           0        4   utun1     62

Route Flag Description

|PRE|POST|           Flag Description                    |
|---|----|-----------------------------------------------|
| U |  U | Route usable                                  |
| H |  H | Host entry (net otherwise)                    |
| L |    | Valid protocol to link address translation    |
| W |  W | Route was generated as a result of cloning    |
|   |  3 | Protocol specified route flag #3              |
| I |  I | Route is assocaited with an interface scope   |
| i |    | Route is a holding reference to the interface |

Question

Is it possible to restore the routes changed by VPN in order to make my vagrant connections work again? And if-so how?

Other Data

Full Route Table (PRE) (IP4 only)

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            192.168.2.1        UGSc           23        1     en0
10.10.10/24        link#11            UCS             1        0 vboxnet
10.10.10.11        8:0:27:96:91:84    UHLWIi          1       70 vboxnet   1197
127                127.0.0.1          UCS             0        7     lo0
127.0.0.1          127.0.0.1          UH             11   128344     lo0
169.254            link#4             UCS             0        0     en0
192.168.2          link#4             UCS             0        0     en0
192.168.2.1        68:7f:74:81:8b:b0  UHLSr          27      126     en0
192.168.2.106/32   link#4             UCS             0        0     en0

Full Route Table (POST) (IP4 only)

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            link#19            UCS             9        0   utun1
default            192.168.2.1        UGScI           3        0     en0
10.10.10/24        link#19            UCS             1        0   utun1
10.10.10.11        link#19            UHW3I           0        4   utun1     62
17.158.10.25       link#19            UHW3I           0        1   utun1     62
17.158.10.42       link#19            UHW3I           0       20   utun1     62
17.158.10.46       link#19            UHW3I           0        1   utun1     62
127                127.0.0.1          UCS             0        7     lo0
127.0.0.1          127.0.0.1          UH             15   128507     lo0
128.29.154.114     link#19            UHWIi          31      117   utun1
129.83.20.9        link#19            UHW3I           0       20   utun1     61
129.83.26.209      link#19            UHWIi           2        2   utun1
129.83.100.38      link#19            UHW3I           0       46   utun1     62
169.254            link#19            UCS             0        0   utun1
172.31.160/19      link#19            UCS             0        0   utun1
172.31.163.172/32  127.0.0.1          UGSc            3       67     lo0
192.80.55.9/32     192.168.2.1        UGSc            1        0     en0
192.168.2          link#19            UCS             0        0   utun1
192.168.2.1        68:7f:74:81:8b:b0  UHLSr           7        8     en0
192.168.2.1/32     link#19            UCS             0        0   utun1
192.168.2.106/32   link#4             UCS             0        0     en0
216.58.217.132     link#19            UHW3I           0        2   utun1     59
239.255.255.250    link#19            UHmW3I          0       17   utun1     62

Components

OSX

Cisco Any Connect

VirtualBox 5.0.8


问:
Hide toolbar behaviour like medium android application
I am trying to achieve this effect (like medium android app toolbar), I want to hide a custom view, unfortunately I am not able to do. This is my layout.

https://i.ibb.co/KNp1zfV/2019-05-27-14-23-47.gif

```<code><com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    app:elevation="0dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/filtersContainerLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/left_rectangle_edge_view_size"
        android:background="@drawable/custom_rectangle_ripple_background"
        android:paddingBottom="@dimen/default_padding_extra_small"
        android:orientation="vertical"
        app:layout_scrollFlags="scroll|enterAlways">

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/resultMessageTextView"
            style="@style/DefaultTextStyle.Black"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/separator_gray"
            android:drawableEnd="@drawable/ic_pencil_edit"
            android:drawablePadding="@dimen/default_margin_small"
            android:paddingStart="@dimen/default_margin_medium"
            android:paddingTop="@dimen/default_padding"
            android:paddingEnd="@dimen/default_padding_large"
            android:paddingBottom="@dimen/default_padding"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Searching for family medicine near Montevideo" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/filtersHeaderTextView"
            style="@style/DefaultTextStyle.Black"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/default_margin_medium"
            android:layout_marginTop="@dimen/default_margin_extra_small"
            android:text="@string/filters"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/resultMessageTextView" />

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/expandCollapseFilterOptionsImageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?actionBarItemBackground"
            android:padding="@dimen/default_margin_small"
            app:layout_constraintBottom_toBottomOf="@+id/filtersHeaderTextView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@+id/filtersHeaderTextView"
            android:layout_marginEnd="@dimen/default_margin"
            app:srcCompat="@drawable/ic_add"
            app:tint="@color/colorPrimaryDark" />

        <LinearLayout
            android:id="@+id/filtersButtonsLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/default_margin_small"
            android:orientation="horizontal"
            android:visibility="gone"
            app:layout_constraintBottom_toBottomOf="@+id/filtersHeaderTextView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/expandCollapseFilterOptionsImageView"
            app:layout_constraintTop_toTopOf="@+id/filtersHeaderTextView"
            tools:visibility="visible">

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/applyFilterButton"
                style="@style/SmallTextStyle.Bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="@dimen/default_padding_small"
                android:text="@string/apply"
                android:textColor="@drawable/text_selector_primary_dark" />

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/clearFiltersButton"
                style="@style/SmallTextStyle.Bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/default_margin_small"
                android:padding="@dimen/default_padding_small"
                android:text="@string/clear"
                android:textColor="@drawable/text_selector_primary_dark" />
        </LinearLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>

    <View
        android:id="@+id/topSeparatorView"
        android:layout_width="match_parent"
        android:layout_height="@dimen/separator_height"
        android:layout_marginStart="@dimen/left_rectangle_edge_view_size"
        android:background="@color/separator_gray"
        app:layout_scrollFlags="snap" />
</com.google.android.material.appbar.AppBarLayout>

<androidx.core.widget.NestedScrollView
    android:id="@+id/resultContainerScrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:overScrollMode="never"
    app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

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

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/providersResultRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/providers_result_margin_start"
            android:overScrollMode="never" />
    </LinearLayout>
</androidx.core.widget.NestedScrollView>
</code>```

答:
This thread on medium might serve exactly what you need, and here's another one  if you want to dig deeper in the custom behaviors

Now to the answer:

1. main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <!-- call the content xml file-->
    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>
</code>```

1. content_main.xml

```<code><android.support.v4.widget.NestedScrollView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:id="@+id/textview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="hello world"/>

            <!-- your content goes here-->

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>
</code>```

3. Important note

content_main.xml use :  android.support.v4.widget.NestedScrollView instead of ScrollView.

use app:layout_behavior="@string/appbar_scrolling_view_behavior" inside android.support.v4.widget.NestedScrollView like below.

if and only if you migrated to AndroidX make sure to change the design support library, if you still using android.support keep everything as it is.

UPDATE

Try the following changes:

1. add this to your ToolBar

```<code>app:layout_scrollFlags="scroll|enterAlways"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
</code>```

2. add this to your NestedScrollLayout

```<code>android:fillViewport="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
</code>```

Body:
I am trying to achieve this effect (like medium android app toolbar), I want to hide a custom view, unfortunately I am not able to do. This is my layout.

https://i.ibb.co/KNp1zfV/2019-05-27-14-23-47.gif

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    app:elevation="0dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/filtersContainerLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/left_rectangle_edge_view_size"
        android:background="@drawable/custom_rectangle_ripple_background"
        android:paddingBottom="@dimen/default_padding_extra_small"
        android:orientation="vertical"
        app:layout_scrollFlags="scroll|enterAlways">

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/resultMessageTextView"
            style="@style/DefaultTextStyle.Black"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/separator_gray"
            android:drawableEnd="@drawable/ic_pencil_edit"
            android:drawablePadding="@dimen/default_margin_small"
            android:paddingStart="@dimen/default_margin_medium"
            android:paddingTop="@dimen/default_padding"
            android:paddingEnd="@dimen/default_padding_large"
            android:paddingBottom="@dimen/default_padding"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Searching for family medicine near Montevideo" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/filtersHeaderTextView"
            style="@style/DefaultTextStyle.Black"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/default_margin_medium"
            android:layout_marginTop="@dimen/default_margin_extra_small"
            android:text="@string/filters"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/resultMessageTextView" />

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/expandCollapseFilterOptionsImageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?actionBarItemBackground"
            android:padding="@dimen/default_margin_small"
            app:layout_constraintBottom_toBottomOf="@+id/filtersHeaderTextView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@+id/filtersHeaderTextView"
            android:layout_marginEnd="@dimen/default_margin"
            app:srcCompat="@drawable/ic_add"
            app:tint="@color/colorPrimaryDark" />

        <LinearLayout
            android:id="@+id/filtersButtonsLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/default_margin_small"
            android:orientation="horizontal"
            android:visibility="gone"
            app:layout_constraintBottom_toBottomOf="@+id/filtersHeaderTextView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/expandCollapseFilterOptionsImageView"
            app:layout_constraintTop_toTopOf="@+id/filtersHeaderTextView"
            tools:visibility="visible">

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/applyFilterButton"
                style="@style/SmallTextStyle.Bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="@dimen/default_padding_small"
                android:text="@string/apply"
                android:textColor="@drawable/text_selector_primary_dark" />

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/clearFiltersButton"
                style="@style/SmallTextStyle.Bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/default_margin_small"
                android:padding="@dimen/default_padding_small"
                android:text="@string/clear"
                android:textColor="@drawable/text_selector_primary_dark" />
        </LinearLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>

    <View
        android:id="@+id/topSeparatorView"
        android:layout_width="match_parent"
        android:layout_height="@dimen/separator_height"
        android:layout_marginStart="@dimen/left_rectangle_edge_view_size"
        android:background="@color/separator_gray"
        app:layout_scrollFlags="snap" />
</com.google.android.material.appbar.AppBarLayout>

<androidx.core.widget.NestedScrollView
    android:id="@+id/resultContainerScrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:overScrollMode="never"
    app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

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

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/providersResultRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/providers_result_margin_start"
            android:overScrollMode="never" />
    </LinearLayout>
</androidx.core.widget.NestedScrollView>

Body:
This thread on medium might serve exactly what you need, and here's another one  if you want to dig deeper in the custom behaviors

Now to the answer:

1. main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <!-- call the content xml file-->
    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

1. content_main.xml

<android.support.v4.widget.NestedScrollView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:id="@+id/textview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="hello world"/>

            <!-- your content goes here-->

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

3. Important note

content_main.xml use :  android.support.v4.widget.NestedScrollView instead of ScrollView.

use app:layout_behavior="@string/appbar_scrolling_view_behavior" inside android.support.v4.widget.NestedScrollView like below.

if and only if you migrated to AndroidX make sure to change the design support library, if you still using android.support keep everything as it is.

UPDATE

Try the following changes:

1. add this to your ToolBar

app:layout_scrollFlags="scroll|enterAlways"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"

2. add this to your NestedScrollLayout

android:fillViewport="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior"


问:
Laravel - User class not found exception
I've been trying to understand how to implement the separation of concerns in the Laravel documentation on the Models & Libraries page. I renamed my models folder into 'malice' (my pc's computer name) to simulate a rename like it says on the site.

I understand that the class can't be found but this is my first time using Laravel and first time to ever hear of "separation of concerns" so please be patient with me. :)

Here's what I have:

```<code>// application/malice/entities/user.php
<?php namespace Malice\Entities;

class User {

    public $name;

    public function __construct($name){
        $this->name = $name;
    }

}

// application/malice/services/user_doit.php
<?php namespace Malice\Services;

use Malice\Entities\User;

class User_Doit {

    public static function introduce(User $name){
        return "Hi, I'm {$name}";
    }

}
</code>```

When I run in my controller:

```<code>$user = new User();
krumo($user); // I'm using krumo isntead of print_r
</code>```

This is all I get:

```<code>Unhandled Exception

Message:

Class 'User' not found
Location:

D:\xampp\virtual\laravel\application\controllers\test.php on line 29
</code>```

Update:

This is what my start.php currently looks like:

```<code>Autoloader::directories(array(
    // path('app').'models',
    path('app').'libraries',
));

Autoloader::namespaces(array(
    'Malice' => path('app').'malice'
));
</code>```

答:
In your controller, add the User class like this.

```<code>use Malice\Entities\User;

$user = new User();
krumo($user);
</code>```

Body:
I've been trying to understand how to implement the separation of concerns in the Laravel documentation on the Models & Libraries page. I renamed my models folder into 'malice' (my pc's computer name) to simulate a rename like it says on the site.

I understand that the class can't be found but this is my first time using Laravel and first time to ever hear of "separation of concerns" so please be patient with me. :)

Here's what I have:

// application/malice/entities/user.php
<?php namespace Malice\Entities;

class User {

    public $name;

    public function __construct($name){
        $this->name = $name;
    }

}

// application/malice/services/user_doit.php
<?php namespace Malice\Services;

use Malice\Entities\User;

class User_Doit {

    public static function introduce(User $name){
        return "Hi, I'm {$name}";
    }

}

When I run in my controller:

$user = new User();
krumo($user); // I'm using krumo isntead of print_r

This is all I get:

Unhandled Exception

Message:

Class 'User' not found
Location:

D:\xampp\virtual\laravel\application\controllers\test.php on line 29

Update:

This is what my start.php currently looks like:

Autoloader::directories(array(
    // path('app').'models',
    path('app').'libraries',
));

Autoloader::namespaces(array(
    'Malice' => path('app').'malice'
));

Body:
In your controller, add the User class like this.

use Malice\Entities\User;

$user = new User();
krumo($user);


问:
Display arraylist object using javabeans
I'm making a webscraping application so I'm not using any database just javabeans to store the data and xhtml pages to display it, now I have an arraylist objects in which every object there's data I need to display in xhtml page, but I don't know how to.
I know it is posible with jsp using jstl but some days ago I heard that almost nobody uses jsp these days,... So I don't wan't to use it for this project.

javabeans

```<code>@ManagedBean(name = "login")
@SessionScoped
public class Login implements Serializable{
    private boolean isLoged=false;
    PortalUDB portaludb;
    Estudiante estudiante; // This is the object tha has the array list
</code>```

Class that contains the two arraylist of objects

```<code>public final class Estudiante{
    private Document document;
    private int uv_carrera;
    private int uv_actuales;
    private final Connection.Response loginForm;
    public List<MateriaPensum> materia_pensum = new ArrayList<>();
    public List<MateriaExpediente> materia_expediente = new ArrayList<>();
</code>```

I've already achieved it using ui:repeat

```<code><ui:repeat var="materia" value="#{login.estudiante.materia_expediente}"> <h1>#{materia.asignatura}</h1> </ui:repeat>
</code>```

Just I don't know why I can use every variable in the class MateriaExpediente when they are private.

```<code>public class MateriaExpediente extends MateriaPensum{
    int anio;
    String ciclo;
    String asignatura;
    String matricula;
    float nota;
    String resultado;
</code>```

Maybe because I use getter and setter methods?

答:
If you know Javascript/JQuery you can do it. Just send your data-list as JSON string format to client. In client side, read the list data from response and then populate the list using loop iterating the list(for that, you can fetch data by ajax request from client side).

For that, set a parent Class/Id for that xhtml area where you want to populate the data and use that as reference.

I know this is generic solution(but it will help I hope), but it would help us to help more if you try a specific way and tell us what are you facing. For further reference you can read this

Body:
I'm making a webscraping application so I'm not using any database just javabeans to store the data and xhtml pages to display it, now I have an arraylist objects in which every object there's data I need to display in xhtml page, but I don't know how to.
I know it is posible with jsp using jstl but some days ago I heard that almost nobody uses jsp these days,... So I don't wan't to use it for this project.

javabeans

@ManagedBean(name = "login")
@SessionScoped
public class Login implements Serializable{
    private boolean isLoged=false;
    PortalUDB portaludb;
    Estudiante estudiante; // This is the object tha has the array list

Class that contains the two arraylist of objects

public final class Estudiante{
    private Document document;
    private int uv_carrera;
    private int uv_actuales;
    private final Connection.Response loginForm;
    public List<MateriaPensum> materia_pensum = new ArrayList<>();
    public List<MateriaExpediente> materia_expediente = new ArrayList<>();

I've already achieved it using ui:repeat

<ui:repeat var="materia" value="#{login.estudiante.materia_expediente}">
#{materia.asignatura}
 </ui:repeat>

Just I don't know why I can use every variable in the class MateriaExpediente when they are private.

public class MateriaExpediente extends MateriaPensum{
    int anio;
    String ciclo;
    String asignatura;
    String matricula;
    float nota;
    String resultado;

Maybe because I use getter and setter methods?


答:
```<code>import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortStrings {

    public static void main(String[] args) {
        Comparator<String> comparator = new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if(o1 == null) {
                    return 1;
                }
                if(o2 == null) {
                    return -1;
                }
                int result = o1.compareToIgnoreCase(o2);
                if(result != 0) {
                    return result;
                }
                return o1.compareTo(o2);
            }
        };

        List<String> list = Arrays.asList("A","a","A","a", "B", "c","C");
        Collections.sort(list, comparator);
        System.out.println(list);
        // [A, A, a, a, B, C, c]

        List<String> list2 = Arrays.asList("Ab","a","AB", "A", "AbB", "a","B","c","C");
        Collections.sort(list2, comparator);
        System.out.println(list2);
        // compare length first
        // [A, a, a, AB, Ab, AbB, B, C, c]

        List<String> list3 = Arrays.asList("aaa","AAA","AAA","aaa","BBB","ccc","CCC");
        Collections.sort(list3, comparator);
        System.out.println(list3);
        // [AAA, AAA, aaa, aaa, BBB, CCC, ccc]
    }
}
</code>```

Title: How to sort strings in java , order shoud display Capital Strings first