问:
How to discover what Linux distribution is in use
Sometimes I need to access some servers running Linux (or maybe another Unix-like SO), but I don't know how to verify which distribution is in use on the server (there are times that even the "responsible" person for the server doesn't know).

Is there an easy and reliable way to discover that, one that is uniform and consistent across all of them?

答:
There are different commands you can use to check which distribution is in use. Here I am mentioning only 5 of them.

lsb_relase -a

lsb_release provides distribution-specific information. Whereas -a display all information about the distribution. You can also use -d which only shows the description.

uname -a

uname also provides system information. Whereas -a display all information. You can use man uname for other options.

cat /etc/*release

You can also use cat command to print out all specific release information from etc folder. This command actually reads the lsb-release and os-release files from the /etc folder.

cat /etc/issue

This command reads the issue file from the /etc folder.

cat /proc/version

This command reads the version file from the /proc folder. /proc folder contains information about system process.

OwnerDisplayName: Seiti


来源: stackexchange

问:
How to get current url in view in asp.net core 1.0
In previous versions of asp.net, we could use

```<code>@Request.Url.AbsoluteUri
</code>```

But it seems it's changed.  How can we do that in asp.net core 1.0?

答:
If you're looking to also get the port number out of the request you'll need to access it through the Request.Host property for AspNet Core.

The Request.Host property is not simply a string but, instead, an object that holds both the host domain and the port number. If the port number is specifically written out in the URL (i.e. "https://example.com:8080/path/to/resource"), then calling Request.Host will give you the host domain and the port number like so: "example.com:8080".

If you only want the value for the host domain or only want the value for the port number then you can access those properties individually (i.e. Request.Host.Host or Request.Host.Port).

ContentLicense: CC BY-SA 3.0

Body:
In previous versions of asp.net, we could use

@Request.Url.AbsoluteUri

But it seems it's changed.  How can we do that in asp.net core 1.0?


问:
How can i get background colour decimals?

I'm trying to read background color which i set in decimals e.g rgb(44.9, 19.373737, 255)
using this code

```<code>$("p").css("background-color")
</code>```

but when used it keeps rounding it into rgb(45, 19, 255)

all i want to achieve is to get it in decimals

This is the sample code:

```<code><script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Background color = " + $("p").css("background-color"));
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:rgb(44.9, 19.373737, 255)">This is a paragraph.</p>

<button>Return background-color of p</button>
</code>```

答:
RGB values are composed of three 8-bit integers (byte), for red, green and blue respectively ranges from 0 to 255. There are no fractional part allowed in those values. Hence your style is not working.

$(document).ready(function(){
    $("button").click(function(){
        alert("Background color = " + $("p").css("background-color"));
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2>This is a heading</h2>

<p style="background-color:rgb(44, 19, 255)">This is a paragraph.</p>

<button>Return background-color of p</button></code>```

Body:
I'm trying to read background color which i set in decimals e.g rgb(44.9, 19.373737, 255)
using this code

$("p").css("background-color")

but when used it keeps rounding it into rgb(45, 19, 255)

all i want to achieve is to get it in decimals

This is the sample code:

This is a heading

This is a paragraph.

<button>Return background-color of p</button>

Body:
RGB values are composed of three 8-bit integers (byte), for red, green and blue respectively ranges from 0 to 255. There are no fractional part allowed in those values. Hence your style is not working.

$(document).ready(function(){
    $("button").click(function(){
        alert("Background color = " + $("p").css("background-color"));
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2>This is a heading</h2>

<p style="background-color:rgb(44, 19, 255)">This is a paragraph.</p>

<button>Return background-color of p</button>


问:
Test report is not creating while running from XMLRunner
I am running Unit TestCases from Python Using XMLTestRunner.

This is my main file:

```<code>#LoggingService.py
class LoggerWriter:
    # used to redirect console msgs to the log
    def write(self, message):
        log_event('warning', 'Console', message)

def direct_console_to_log():
    global console_redirected
    # This function can be called several times. Avoid redirecting more than once
    if not console_redirected:
        console_output = LoggerWriter()
        sys.stderr = console_output
        sys.stdout = console_output
        console_redirected = True

def log_event(level, _id, event_details):
    # log the event
    pass
</code>```

This is my one of the testing file:

```<code>#LoggingServiceTest.py
import unittest
import LoggingService
from LoggingService import direct_console_to_log
class Test(unittest.TestCase):
    @patch('LoggingService.log_event')
    def test_log_writer(self,log_mock):
        direct_console_to_log()
        print ('console msg')
        self.assertTrue(log_mock.called)

if __name__ == "__main__":
    unittest.main()
</code>```

I used to run all the test file from XMLRunner.py:

```<code>#XMLRunner.py
from xmlrunner import XMLTestRunner
import unittest

test_modules = [file1.Test, file2.Test, LoggingServiceTest.py, .... file25.Test]
suite = unittest.TestSuite()

for test_module in test_modules:
    tests = unittest.TestLoader().loadTestsFromTestCase(test_module)
    suite.addTests(tests)

if __name__ == '__main__':
    # import xmlrunner
    # unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
    XMLTestRunner(output='test-reports').run(suite)
</code>```

When I am trying to run LoggingServiceTest.py file from "XMLRunner.py", then the test report does not generate.But when I try without "LoggingServiceTest.py", then the report generates successfully.

And I am not sure, what is happening with the test case function
(test_log_writer(self,log_mock)) in LoggingServiceTest.py running.
Can anyone clear me

I use the following command to run the test case:

```<code>Python2.7.14\python.exe -m coverage run -p --branch --source=. --omit=Unit_Tests/*.py Unit_Tests/Testing.py
</code>```

答:
Finally I got the solution after debugging more.

When start test case from XMLRunner, It is creating some file objects for to write stderr and stdout and it is defined in sys.stderr, sys.stdout variable

And my test case is overwrite the sys.stderr, sys.stdout variable.

So XMLRunner try to fetching file objects from sys.stderr, sys.stdout, but it is not there, then it is not generating report.

Body:
I am running Unit TestCases from Python Using XMLTestRunner.

This is my main file:

#LoggingService.py
class LoggerWriter:
    # used to redirect console msgs to the log
    def write(self, message):
        log_event('warning', 'Console', message)

def direct_console_to_log():
    global console_redirected
    # This function can be called several times. Avoid redirecting more than once
    if not console_redirected:
        console_output = LoggerWriter()
        sys.stderr = console_output
        sys.stdout = console_output
        console_redirected = True

def log_event(level, _id, event_details):
    # log the event
    pass

This is my one of the testing file:

#LoggingServiceTest.py
import unittest
import LoggingService
from LoggingService import direct_console_to_log
class Test(unittest.TestCase):
    @patch('LoggingService.log_event')
    def test_log_writer(self,log_mock):
        direct_console_to_log()
        print ('console msg')
        self.assertTrue(log_mock.called)

if __name__ == "__main__":
    unittest.main()

I used to run all the test file from XMLRunner.py:

#XMLRunner.py
from xmlrunner import XMLTestRunner
import unittest

test_modules = [file1.Test, file2.Test, LoggingServiceTest.py, .... file25.Test]
suite = unittest.TestSuite()

for test_module in test_modules:
    tests = unittest.TestLoader().loadTestsFromTestCase(test_module)
    suite.addTests(tests)

if __name__ == '__main__':
    # import xmlrunner
    # unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
    XMLTestRunner(output='test-reports').run(suite)

When I am trying to run LoggingServiceTest.py file from "XMLRunner.py", then the test report does not generate.But when I try without "LoggingServiceTest.py", then the report generates successfully.

And I am not sure, what is happening with the test case function
(test_log_writer(self,log_mock)) in LoggingServiceTest.py running.
Can anyone clear me

I use the following command to run the test case:

Python2.7.14\python.exe -m coverage run -p --branch --source=. --omit=Unit_Tests/*.py Unit_Tests/Testing.py


答: I don't think the decimal values make any sense. rather round of it and use it in RGB.</p>

Title: How can i get background colour decimals?


问:
Binding the checked value of a checkbox to boolean attribute of an object in angular
I am trying to bind the value of a checkbox to a boolean variable in an object. The checkbox is used inside
of a table. The functionality that I am trying to achieve is that when I click the checkbox, it should toggle the
boolean variable in the object and the result of which would be shown on the html.

I am using the below code to achieve the same:

HTML:

```<code><tr *ngFor="let item of getListOfItems(); let i = index">
  <td>{{ i+1 }}</td>
  <td>{{ item.action }}</td>
  <td><input name="chk" type="checkbox" [(ngModel)]="item.isComplete" /></td>
  <td [ngSwitch]="item.isComplete">
    <span *ngSwitchCase="true">Yes</span>
    <span *ngSwitchDefault>No</span>
  </td>
</tr>
</code>```

Component:

```<code>getListOfItems() {
  var items = [
    new TodoItem('Buy Flowers', false),
    new TodoItem('Get Shoes', false),
    new TodoItem('Collect Tickets', true),
    new TodoItem('Call Joe', false),
  ];

  return items;
}
</code>```

TodoItem Class

```<code>export class TodoItem {
    action: string;
    isComplete: boolean;

    constructor(action: string, isComplete) {
        this.action = action;
        this.isComplete = isComplete;
    }
}
</code>```

However, when I run the app, the browser keeps on loading the page and freezes after a period of time.
When I comment this checkbox , everything comes back to normal and the code works fine. Could not figure out a solution. Any help would be appreciated.

答:
It has been a while  so i may be rusty,but the below should work.

```<code>  <td><input  type="checkbox"  [checked]="item.isComplete" (change)="item.isComplete= !item.isComplete"  /></td>
</code>```

Make sure you have explicitly decalred isComplete in your TodoItem as boolean

EDIT:
It was just one way binding, It does not suit your use case.
Coming to your original code.

The actual problem is,

```<code>getListOfItems() {
  var items = [
    new TodoItem('Buy Flowers', false),
    new TodoItem('Get Shoes', false),
    new TodoItem('Collect Tickets', true),
    new TodoItem('Call Joe', false),
  ];

  return items;
}
</code>```

On each call
of

the method is being called and it will return a new array containing the same items. The result is a never ending for loop.
The best way to avoid this is initialize the array once outside this method and return just the instance in this method like below

```<code>items = [
    new TodoItem('Buy Flowers', false),
    new TodoItem('Get Shoes', false),
    new TodoItem('Collect Tickets', true),
    new TodoItem('Call Joe', false),
  ];

  getListOfItems() {

  return this.items;
}
</code>```

I am sure this is just for testing, you will eventually get the data from server in a service class.
For now, this will solve the problem
And you original binding will work

```<code><td><input name="chk" type="checkbox" [(ngModel)]="item.isComplete" /></td>
</code>```

Note: if you are using form group, better to have a different name for each checkbox

Body:
I am trying to bind the value of a checkbox to a boolean variable in an object. The checkbox is used inside
of a table. The functionality that I am trying to achieve is that when I click the checkbox, it should toggle the
boolean variable in the object and the result of which would be shown on the html.

I am using the below code to achieve the same:

HTML:

  {{ i+1 }}
  {{ item.action }}
  <input name="chk" type="checkbox" [(ngModel)]="item.isComplete" />

    Yes
    No

Component:

getListOfItems() {
  var items = [
    new TodoItem('Buy Flowers', false),
    new TodoItem('Get Shoes', false),
    new TodoItem('Collect Tickets', true),
    new TodoItem('Call Joe', false),
  ];

  return items;
}

TodoItem Class

export class TodoItem {
    action: string;
    isComplete: boolean;

    constructor(action: string, isComplete) {
        this.action = action;
        this.isComplete = isComplete;
    }
}

However, when I run the app, the browser keeps on loading the page and freezes after a period of time.
When I comment this checkbox , everything comes back to normal and the code works fine. Could not figure out a solution. Any help would be appreciated.

Body:
It has been a while  so i may be rusty,but the below should work.

  <td><input  type="checkbox"  [checked]="item.isComplete" (change)="item.isComplete= !item.isComplete"  /></td>

Make sure you have explicitly decalred isComplete in your TodoItem as boolean

EDIT:
It was just one way binding, It does not suit your use case.
Coming to your original code.

The actual problem is,

getListOfItems() {
  var items = [
    new TodoItem('Buy Flowers', false),
    new TodoItem('Get Shoes', false),
    new TodoItem('Collect Tickets', true),
    new TodoItem('Call Joe', false),
  ];

  return items;
}

On each call
of <tr *ngFor="let item of getListOfItems(); let i = index">
the method is being called and it will return a new array containing the same items. The result is a never ending for loop.
The best way to avoid this is initialize the array once outside this method and return just the instance in this method like below

items = [
    new TodoItem('Buy Flowers', false),
    new TodoItem('Get Shoes', false),
    new TodoItem('Collect Tickets', true),
    new TodoItem('Call Joe', false),
  ];

  getListOfItems() {

  return this.items;
}

I am sure this is just for testing, you will eventually get the data from server in a service class.
For now, this will solve the problem
And you original binding will work

<td><input name="chk" type="checkbox" [(ngModel)]="item.isComplete" /></td>

Note: if you are using form group, better to have a different name for each checkbox


问:
ASPX page with a User Control not working with localization
I have a project that is using ASPX and C#.  All of the pages support localization through the overridden InitializeCulture method.  Everything works very well with the exception of one page.  This page has UserControl that is used for searching.  I have noticed something odd with this page.  If I execute a search, all of the French characters show up incorrectly.  However, if I change the language to English and then back to French they show up as they should.  The text is coming from a global resx file.
First display:

```Nous avons Ã©galement effectuÃ©```

After changing language and then back:

```Nous avons également effectué```

Any ideas why this is happening?  It affects the entire page too, even parts that work properly on all other pages.  The web.config file has the default encoding set to utf-8:

<globalization requestEncoding="utf-8" responseEncoding="utf-8" />

答:
I found several references to problems with French characters in UTF-8 in apparently unrelated apps:

http://www.dotnet247.com/247reference/msgs/37/189336.aspx

http://forums.mysql.com/read.php?103,220789,220789

Maybe give UTF-16 a try?

ContentLicense: CC BY-SA 2.5

Body:
I have a project that is using ASPX and C#.  All of the pages support localization through the overridden InitializeCulture method.  Everything works very well with the exception of one page.  This page has UserControl that is used for searching.  I have noticed something odd with this page.  If I execute a search, all of the French characters show up incorrectly.  However, if I change the language to English and then back to French they show up as they should.  The text is coming from a global resx file.
First display:

Nous avons Ã©galement effectuÃ©

After changing language and then back:

Nous avons également effectué

Any ideas why this is happening?  It affects the entire page too, even parts that work properly on all other pages.  The web.config file has the default encoding set to utf-8:

<globalization requestEncoding="utf-8" responseEncoding="utf-8" />


问:
Django - referencing static files in templates
I'm having difficulty referencing static files in my templates. I am using Twitter Bootstrap and have the bootstrap files (css, img, js) sitting at mysite/static.

I have set the STATIC_URL, STATIC_ROOT and TEMPLATE_CONTEXT_PROCESSORS according to this tutorial. I have run ./manage.py collectstatic which copied 72 files over. I have also added the below template tag to my template (index.html) file but this hasn't worked.

```<code>{% load staticfiles %}
<link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen"/>
</code>```

Any help on how to reference the files so that the bootstrap styling returns to the templates would be much appreciated!

答:
When you set static_root, for example:

```<code>STATIC_ROOT = os.path.join(BASE_DIR, "static_root/")
</code>```

, all files are copied there, instead of in project_root/static. It is a new mechanism introduced in Django 1.3, to easy the static file processing: it will collect all files in each STATICFILES_DIR and all static dir under each installed app, so you copy them once in all.

Refer the css/js files with static_root path.

Body:
I'm having difficulty referencing static files in my templates. I am using Twitter Bootstrap and have the bootstrap files (css, img, js) sitting at mysite/static.

I have set the STATIC_URL, STATIC_ROOT and TEMPLATE_CONTEXT_PROCESSORS according to this tutorial. I have run ./manage.py collectstatic which copied 72 files over. I have also added the below template tag to my template (index.html) file but this hasn't worked.

{% load staticfiles %}
<link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen"/>

Any help on how to reference the files so that the bootstrap styling returns to the templates would be much appreciated!

Body:
When you set static_root, for example:

STATIC_ROOT = os.path.join(BASE_DIR, "static_root/")

, all files are copied there, instead of in project_root/static. It is a new mechanism introduced in Django 1.3, to easy the static file processing: it will collect all files in each STATICFILES_DIR and all static dir under each installed app, so you copy them once in all.

Refer the css/js files with static_root path.


问:
OOP - inheritance [Java]
bb refers Derived  class, when i call show() method,  but when i print bb.b  - is prints Base class property .
Why is this happening?

```<code>class Base {
    int b=10;
    public void show() {

        System.out.println("Base show() called");

    }
}

class Derived extends Base {

    int b=20;
    public void show() {

        System.out.println("Derived show() called");

    }

}

public class MainClass {

    public static void main(String[] args) {

        Base bb = new Derived();;

        bb.show();
        System.out.println(bb.b);

    }

}
</code>```

output :

Derived show() called

10

答:
This is because the compiler implements special run time polymorphism for methods only. This is also called method overriding.

For variables, the value will always be from the Base class, because that is the type of bb object regardless of the class with with it is instantiated.

Title: OOP - inheritance [Java]

Body:
bb refers Derived  class, when i call show() method,  but when i print bb.b  - is prints Base class property .
Why is this happening?

class Base {
    int b=10;
    public void show() {

        System.out.println("Base show() called");

    }
}

class Derived extends Base {

    int b=20;
    public void show() {

        System.out.println("Derived show() called");

    }

}

public class MainClass {

    public static void main(String[] args) {

        Base bb = new Derived();;

        bb.show();
        System.out.println(bb.b);

    }

}

output :

Derived show() called

10


问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
Try
    WHERE tags.name IN ('tag1') and tags.name IN ('tag2');

Not super efficient, but probably one of many ways.

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.


问:
How to write a MySQL before insert trigger to insert data in a table?
I need to create a trigger for when I insert data in the first table to be able to insert in the second some data related to the first one.

```<code>CREATE TRIGGER test1
ON Telegramas
BEFORE INSERT
AS
BEGIN
    INSERT INTO Dispositivos SET Dispositivos.GrupoOrigen = Telegramas.GrupoOrigen;
  END;
</code>```

I have created that but there is a syntax error that I can not see. Some help? or another way to make the relationship easier?

答:
You have to change the delimiter, like this :

```<code>delimiter |
CREATE TRIGGER test1

 [...]
END |
delimiter ;
</code>```

But there is a problem in your trigger :

```<code> delimiter |
    CREATE TRIGGER test1  BEFORE INSERT ON Telegramas
    FOR EACH ROW
    BEGIN
        INSERT INTO Dispositivos SET GrupoOrigen = NEW.GrupoOrigen;
    END |
 delimiter ;
</code>```

Body:
I need to create a trigger for when I insert data in the first table to be able to insert in the second some data related to the first one.

CREATE TRIGGER test1
ON Telegramas
BEFORE INSERT
AS
BEGIN
    INSERT INTO Dispositivos SET Dispositivos.GrupoOrigen = Telegramas.GrupoOrigen;
  END;

I have created that but there is a syntax error that I can not see. Some help? or another way to make the relationship easier?

Body:
You have to change the delimiter, like this :

delimiter |
CREATE TRIGGER test1

 [...]
END |
delimiter ;

But there is a problem in your trigger :

 delimiter |
    CREATE TRIGGER test1  BEFORE INSERT ON Telegramas
    FOR EACH ROW
    BEGIN
        INSERT INTO Dispositivos SET GrupoOrigen = NEW.GrupoOrigen;
    END |
 delimiter ;


问:
Converting ng-repeat table to card
i was woundering how i can convert this type of complex ng-repeat from using table to repeat  in AngularJS material design.

My markup looks like this now:

```<code><div class="table-responsive">
                <table class="table">
                    <thead>
                    <tr>
                        <th>AccountName</th>
                        <th>AccountID</th>
                        <th>ContainerID</th>
                        <th>ContainerName</th>
                        <th>Path</th>
                        <th>Favorite</th>
                        <th>Hide</th>
                        <th>Count</th>

                    </tr>
                    </thead>

                    <tbody ng-repeat="(k,v) in containers">
                    <tr ng-repeat="(k1,v1) in v" ng-if="v1.accountId!= null || v1.accountId == ''">
                        <td><a href="{{v1.tagManagerUrl}}">{{ k }}</a></td>
                        <td>{{ v1.accountId }}</td>
                        <td>{{ v1.containerId }}</td>
                        <td>{{ v1.name }}</td>
                        <td><a href="/gui/tags/{{v1.path}}">View Container</a></td>
                    </tr>
                    </tbody>
                </table>
</code>```

Ive tried using this markup for md-cards but it gets all wrong:

```<code><md-card ng-repeat="(k,v) in containers">
    <md-card-content ng-repeat="(k1,v1) in v">
        <h2 class="md-title">{{ v1.name }}</h2>
        <p>
            {{ v1.accountId }}
        </p>
    </md-card-content>
</md-card>
</code>```

If you can see the images the request and the ng-repeat it dont look like a table where you have each row for each account/container:

答:
I got it working with this code:</p>

```<code><div class='md-padding' layout="row" flex>
    <div layout="row" flex>
        <div class="parent" layout="column" ng-repeat="(k,v) in containers">
            <md-card ng-repeat="(k1,v1) in v" ng-if="v1.accountId!= null || v1.accountId == ''">
                <md-card-content>
                    AccountName: {{k}}<br>
                    Accountid: {{ v1.accountId }} <br>
                    ContainerName: {{ v1.name }}
                </md-card-content>
                <div class="md-actions" layout="row" layout-align="end center">
                    <md-button>Save</md-button>
                    <md-button>View</md-button>
                </div>
            </md-card>
        </div>
    </div>
</div>
</code>```

Title: Converting ng-repeat table to card

Body:
i was woundering how i can convert this type of complex ng-repeat from using table to repeat  in AngularJS material design.

My markup looks like this now:

                        AccountName
                        AccountID
                        ContainerID
                        ContainerName
                        Path
                        Favorite
                        Hide
                        Count

                        {{ k }}
                        {{ v1.accountId }}
                        {{ v1.containerId }}
                        {{ v1.name }}
                        View Container

Ive tried using this markup for md-cards but it gets all wrong:

<md-card ng-repeat="(k,v) in containers">
    <md-card-content ng-repeat="(k1,v1) in v">

{{ v1.name }}

            {{ v1.accountId }}

    </md-card-content>
</md-card>

If you can see the images the request and the ng-repeat it dont look like a table where you have each row for each account/container:

Body:
I got it working with this code:

<div class='md-padding' layout="row" flex>
    <div layout="row" flex>
        <div class="parent" layout="column" ng-repeat="(k,v) in containers">
            <md-card ng-repeat="(k1,v1) in v" ng-if="v1.accountId!= null || v1.accountId == ''">
                <md-card-content>
                    AccountName: {{k}}<br>
                    Accountid: {{ v1.accountId }} <br>
                    ContainerName: {{ v1.name }}
                </md-card-content>
                <div class="md-actions" layout="row" layout-align="end center">
                    <md-button>Save</md-button>
                    <md-button>View</md-button>
                </div>
            </md-card>
        </div>
    </div>
</div>


问:
Segmentation fault - sending object over server to client
I am trying to create a client server application in linux. Server sends object to client but client write Segmentation fault. Here is the code.
Snake is class where is two-dimensional array.

Client send message "p" and server is creating object witch will be send to client.

Server side:

```<code>  int main(int argc, char *argv[])
  {

int sockfd, newsockfd;
socklen_t cli_len;
struct sockaddr_in serv_addr, cli_addr;
int n;
char buffer[256];

if (argc < 2)
{
    fprintf(stderr,"usage %s port\n", argv[0]);
    return 1;
}

bzero((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(atoi(argv[1]));

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
    perror("Error creating socket");
    return 1;
}

if (bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
     perror("Error binding socket address");
     return 2;
}
while(sockfd){
listen(sockfd, 5);
cli_len = sizeof(cli_addr);

newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &cli_len);

if (newsockfd < 0)
{
    perror("ERROR on accept");
    return 3;
}

bzero(buffer,256);
n = read(newsockfd, buffer, 255);
if (n < 0)
{
    perror("Error reading from socket");
    return 4;
}

// if client send 'p'
if(*buffer == 'p'   ){
        Snake *snake = new Snake();

    send(newsockfd,reinterpret_cast<const char*>(&snake), sizeof(snake),0);
  }
}

//printf("Here is the message: %s\n", buffer);

const char* msg = "I got your message";
n = write(newsockfd, msg, strlen(msg)+1);
if (n < 0)
{
    perror("Error writing to socket");
    return 5;
}

close(newsockfd);

close(sockfd);

}
</code>```

Client side:

```<code> int main(int argc, char *argv[])
 {
int sockfd = 0,newsockfd, n;
struct sockaddr_in serv_addr;
struct hostent* server;
socklen_t cli_len, serv_len;

char buffer[999999];
struct sockaddr_in cli_addr;

if (argc < 3)
{
    fprintf(stderr,"usage %s hostname port\n", argv[0]);
    return 1;
}

server = gethostbyname(argv[1]);
if (server == NULL)
{
    fprintf(stderr, "Error, no such host\n");
    return 2;
}

bzero((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy(
    (char*)server->h_addr,
    (char*)&serv_addr.sin_addr.s_addr,
    server->h_length
);
serv_addr.sin_port = htons(atoi(argv[2]));
//while(sockfd >= 0){
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
    perror("Error creating socket");
    return 3;
}

if(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
     perror("Error connecting to socket");
     return 4;
}

printf("Please enter a message: ");
bzero(buffer,256);
fgets(buffer, 255, stdin);

n = write(sockfd, buffer, strlen(buffer));

if (n < 0)
{
     perror("Error writing to socket");
     return 5;
}

 Snake *snake ;

recv(sockfd,reinterpret_cast<char*>(&snake), sizeof(snake),0);

if (n < 0)
{
     perror("Error reading from socket");
     return 6;
}

printf("%s\n",buffer);

close(sockfd);
close(newsockfd);
return 0;
 }
</code>```

Thank you for your answers.

答:
On the client side

```<code> Snake *snake ;

recv(sockfd,reinterpret_cast<char*>(&snake), sizeof(snake),0);
</code>```

tries to read into a Snake, but you haven't created any. So the uninitialized pointer gives you the segmentation fault.

Also, sizeof(snake) is the size of a pointer (like 4 bytes), not the size of the object pointed to. This occurs both in the server and in the client.

Body:
I am trying to create a client server application in linux. Server sends object to client but client write Segmentation fault. Here is the code.
Snake is class where is two-dimensional array.

Client send message "p" and server is creating object witch will be send to client.

Server side:

  int main(int argc, char *argv[])
  {

int sockfd, newsockfd;
socklen_t cli_len;
struct sockaddr_in serv_addr, cli_addr;
int n;
char buffer[256];

if (argc < 2)
{
    fprintf(stderr,"usage %s port\n", argv[0]);
    return 1;
}

bzero((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(atoi(argv[1]));

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
    perror("Error creating socket");
    return 1;
}

if (bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
     perror("Error binding socket address");
     return 2;
}
while(sockfd){
listen(sockfd, 5);
cli_len = sizeof(cli_addr);

newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &cli_len);

if (newsockfd < 0)
{
    perror("ERROR on accept");
    return 3;
}

bzero(buffer,256);
n = read(newsockfd, buffer, 255);
if (n < 0)
{
    perror("Error reading from socket");
    return 4;
}

// if client send 'p'
if(*buffer == 'p'   ){
        Snake *snake = new Snake();

    send(newsockfd,reinterpret_cast<const char*>(&snake), sizeof(snake),0);
  }
}

//printf("Here is the message: %s\n", buffer);

const char* msg = "I got your message";
n = write(newsockfd, msg, strlen(msg)+1);
if (n < 0)
{
    perror("Error writing to socket");
    return 5;
}

close(newsockfd);

close(sockfd);

}

Client side:

 int main(int argc, char *argv[])
 {
int sockfd = 0,newsockfd, n;
struct sockaddr_in serv_addr;
struct hostent* server;
socklen_t cli_len, serv_len;

char buffer[999999];
struct sockaddr_in cli_addr;

if (argc < 3)
{
    fprintf(stderr,"usage %s hostname port\n", argv[0]);
    return 1;
}

server = gethostbyname(argv[1]);
if (server == NULL)
{
    fprintf(stderr, "Error, no such host\n");
    return 2;
}

bzero((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy(
    (char*)server->h_addr,
    (char*)&serv_addr.sin_addr.s_addr,
    server->h_length
);
serv_addr.sin_port = htons(atoi(argv[2]));
//while(sockfd >= 0){
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
    perror("Error creating socket");
    return 3;
}

if(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
     perror("Error connecting to socket");
     return 4;
}

printf("Please enter a message: ");
bzero(buffer,256);
fgets(buffer, 255, stdin);

n = write(sockfd, buffer, strlen(buffer));

if (n < 0)
{
     perror("Error writing to socket");
     return 5;
}

 Snake *snake ;

recv(sockfd,reinterpret_cast<char*>(&snake), sizeof(snake),0);

if (n < 0)
{
     perror("Error reading from socket");
     return 6;
}

printf("%s\n",buffer);

close(sockfd);
close(newsockfd);
return 0;
 }

Thank you for your answers.

Body:
On the client side

 Snake *snake ;

recv(sockfd,reinterpret_cast<char*>(&snake), sizeof(snake),0);

tries to read into a Snake, but you haven't created any. So the uninitialized pointer gives you the segmentation fault.

Also, sizeof(snake) is the size of a pointer (like 4 bytes), not the size of the object pointed to. This occurs both in the server and in the client.


答:
Try the following:

```<code>SELECT *
FROM users u, tags t1, tags t2
WHERE t1.user_id = t2.user_id
AND t1.name = 'tag1'
AND t2.name = 'tag2'
AND t1.user_id = u.id
</code>```

Obviously, for a large number of tags, the performance of this query will be severely degraded.

Title: SQL for applying conditions to multiple rows in a join

Body:
Try the following:

SELECT *
FROM users u, tags t1, tags t2
WHERE t1.user_id = t2.user_id
AND t1.name = 'tag1'
AND t2.name = 'tag2'
AND t1.user_id = u.id

Obviously, for a large number of tags, the performance of this query will be severely degraded.


问:
Application.run with more than 30 arguments
I am using Excel VBA. Does anyone know about a way to overcome the argument length limit of Application.Run()? (Or please suggest other function that can do the same job.)

Specific to my situation some of my constraints are:

I need to specify the called function as a string

The function is within a standard module

It is a function, the return value is needed, so Call() will not work.

In any case, I do not want the parameter list of the called function to be changed (e.g. to variant array or ParamArray) since I have written some other functionalities which depend on the function declaration.

EDIT: In response to some of the comments below I can provide a simplified version of my project here (could be off the original question though). In fact the whole design is established and running smooth except for the 30-arg constrain.

The very ultimate goal is to enable the following spreadsheet function which can be called like =mySpreadSheetFn("calledFn", "para1=abc", "para2=2002", ...). This will invoke the function calledFn() whose declaration may be:

Function calledFn(Optional para1 As String = "P1", _
Optional para2 As Integer = 202, _
Optional para3 As Boolean = True)

and the default argument will be replaced accordingly as specified in the ParamArray in the mySpreadSheetFn() call. Similarly there will be calledFn2() etc which an end user can use. So, there has to be an Application.Run() inside mySpreadSheetFn() .

And here are the function definitions:

```<code>Type paramInfo
    Val As Variant
    dataType As String 'can be Enum but let's forget it for this purpose
End Type

Function mySpreadSheetFunction(fnName As String, ParamArray otherParams())

Dim fnParams As Scripting.Dictionary
' getFnDefaultParams(fn): return the defaults and data types of fn's params
'   as a Dictionary. Each item is of type paramInfo (see above)
Set fnParams = getFnParams(fnName)

' For each specified arg check whether it exists for the function.
' If so, replaces the default value with the input value.
' If not exist, then just ignore it
' The problem is really not with this part so just know
'    we have all the parameters resolved after the for-loop
For i = LBound(otherParams) To UBound(otherParams)
    Dim myKey As String
    myKey = Split(otherParams(i), "=")(0)
    If fnParams.Exists(myKey) Then
        ' parseParam() converts the input string into required data type
        fnParams(myKey).Val = parseParam(Split(otherParams(i), "=", 2)(1), _
                              fnParams(myKey).DataType _
                              )
    End If
Next

' Here is the issue since the call cannot go beyond 30 args
Dim lb As Integer: lb = LBound(fnParams)
Select Case UBound(fnParams) - LBound(fnParams) + 1
Case 1: Application.Run fnName, fnParams(lb).Val
Case 2: Application.Run fnName, fnParams(lb).Val, fnParams(lb + 1).Val
' Omitted, goes until Case 30
' What to do with Case 31??
End Select

' Some other operations for each call

End Function

' An example of function that can be called by the above mySpreadSheetFn()
Function calledFn(Optional para1 As String = "P1", _
    Optional para2 As Integer = 202, _
    Optional para3 As Boolean = True)

' needs to return value
calledFn = para1 & para2 * 1000

 End Function
</code>```

There is hardly any room to change the front-end since this is how the user interface is desired.

Any thoughts?

答:
Probably a bit late, but if you transfer the method to a class, everything becomes much easier:

Class "c1"

```<code>Public Sub IHaveTooManyArguments(ParamArray params())
    Debug.Print "Refactor me!"
End Sub
</code>```

Module "Main"

```<code>Public Sub CallIHaveTooManyArguments(fnName As String, ParamArray params())
    Dim o as new c1
    CallByName o, fnName, VbMethod, params
End Sub
</code>```

Body:
I am using Excel VBA. Does anyone know about a way to overcome the argument length limit of Application.Run()? (Or please suggest other function that can do the same job.)

Specific to my situation some of my constraints are:

I need to specify the called function as a string

The function is within a standard module

It is a function, the return value is needed, so Call() will not work.

In any case, I do not want the parameter list of the called function to be changed (e.g. to variant array or ParamArray) since I have written some other functionalities which depend on the function declaration.

EDIT: In response to some of the comments below I can provide a simplified version of my project here (could be off the original question though). In fact the whole design is established and running smooth except for the 30-arg constrain.

The very ultimate goal is to enable the following spreadsheet function which can be called like =mySpreadSheetFn("calledFn", "para1=abc", "para2=2002", ...). This will invoke the function calledFn() whose declaration may be:

Function calledFn(Optional para1 As String = "P1", _
Optional para2 As Integer = 202, _
Optional para3 As Boolean = True)

and the default argument will be replaced accordingly as specified in the ParamArray in the mySpreadSheetFn() call. Similarly there will be calledFn2() etc which an end user can use. So, there has to be an Application.Run() inside mySpreadSheetFn() .

And here are the function definitions:

Type paramInfo
    Val As Variant
    dataType As String 'can be Enum but let's forget it for this purpose
End Type

Function mySpreadSheetFunction(fnName As String, ParamArray otherParams())

Dim fnParams As Scripting.Dictionary
' getFnDefaultParams(fn): return the defaults and data types of fn's params
'   as a Dictionary. Each item is of type paramInfo (see above)
Set fnParams = getFnParams(fnName)

' For each specified arg check whether it exists for the function.
' If so, replaces the default value with the input value.
' If not exist, then just ignore it
' The problem is really not with this part so just know
'    we have all the parameters resolved after the for-loop
For i = LBound(otherParams) To UBound(otherParams)
    Dim myKey As String
    myKey = Split(otherParams(i), "=")(0)
    If fnParams.Exists(myKey) Then
        ' parseParam() converts the input string into required data type
        fnParams(myKey).Val = parseParam(Split(otherParams(i), "=", 2)(1), _
                              fnParams(myKey).DataType _
                              )
    End If
Next

' Here is the issue since the call cannot go beyond 30 args
Dim lb As Integer: lb = LBound(fnParams)
Select Case UBound(fnParams) - LBound(fnParams) + 1
Case 1: Application.Run fnName, fnParams(lb).Val
Case 2: Application.Run fnName, fnParams(lb).Val, fnParams(lb + 1).Val
' Omitted, goes until Case 30
' What to do with Case 31??
End Select

' Some other operations for each call

End Function

' An example of function that can be called by the above mySpreadSheetFn()
Function calledFn(Optional para1 As String = "P1", _
    Optional para2 As Integer = 202, _
    Optional para3 As Boolean = True)

' needs to return value
calledFn = para1 & para2 * 1000

 End Function

There is hardly any room to change the front-end since this is how the user interface is desired.

Any thoughts?

Body:
Probably a bit late, but if you transfer the method to a class, everything becomes much easier:

Class "c1"

Public Sub IHaveTooManyArguments(ParamArray params())
    Debug.Print "Refactor me!"
End Sub

Module "Main"

Public Sub CallIHaveTooManyArguments(fnName As String, ParamArray params())
    Dim o as new c1
    CallByName o, fnName, VbMethod, params
End Sub


问:
Order object by enum in custom order
I'm trying to rearrange a list of animals in order from medium, large, small. I've been trying to do this with IComparable.CompareTo but I can't figure out how to order it in this specific way. I can only find ways to order by Ascending or Descending values.

My enum:

```<code>public enum AnimalSize
    {
        Small = 1, Medium = 3, Large = 5,
    }
</code>```

My Animal class:

```<code>public class Animal : IComparable<Animal>
{
    public bool IsCarnivore;
    public AnimalSize Size;

    public Animal(bool isCarnivore, AnimalSize size)
    {
        this.IsCarnivore = isCarnivore;
        this.Size = size;
    }

    public int CompareTo(Animal other)
    {
        return this.Size.CompareTo(other.Size);
    }
</code>```

I call the CompareTo from another class where I have a private list of animals.

How can I arrange the animals in order of Medium, Large, Small?

答:
I would not implement IComparable<T> for a non-scalar object such as an animal. What if you want to sort by height instead of size? Or by name? IComparable implies that the object can be converted to a one-dimensional quantity.

Instead, define the sort order you need in an array, and use a simple LINQ query to sort.

```<code>public static void Main()
{
    var sampleData = new List<Animal>
    {
        new Animal(false, AnimalSize.Small),
        new Animal(false, AnimalSize.Large),
        new Animal(false, AnimalSize.Medium)
    };

    AnimalSize[] customSortOrder = new[]
    {
        AnimalSize.Small,
        AnimalSize.Medium,
        AnimalSize.Large
    };

    var results = sampleData.OrderBy( a => Array.IndexOf(customSortOrder, a.Size ));

    foreach (var a in results)
    {
        Console.WriteLine(a.Size);
    }
</code>```

Output:

```<code>Small
Medium
Large
</code>```

Code on DotNetFiddle

Title: Order object by enum in custom order

Body:
I'm trying to rearrange a list of animals in order from medium, large, small. I've been trying to do this with IComparable.CompareTo but I can't figure out how to order it in this specific way. I can only find ways to order by Ascending or Descending values.

My enum:

public enum AnimalSize
    {
        Small = 1, Medium = 3, Large = 5,
    }

My Animal class:

public class Animal : IComparable<Animal>
{
    public bool IsCarnivore;
    public AnimalSize Size;

    public Animal(bool isCarnivore, AnimalSize size)
    {
        this.IsCarnivore = isCarnivore;
        this.Size = size;
    }

    public int CompareTo(Animal other)
    {
        return this.Size.CompareTo(other.Size);
    }

I call the CompareTo from another class where I have a private list of animals.

How can I arrange the animals in order of Medium, Large, Small?

Body:
I would not implement IComparable<T> for a non-scalar object such as an animal. What if you want to sort by height instead of size? Or by name? IComparable implies that the object can be converted to a one-dimensional quantity.

Instead, define the sort order you need in an array, and use a simple LINQ query to sort.

public static void Main()
{
    var sampleData = new List<Animal>
    {
        new Animal(false, AnimalSize.Small),
        new Animal(false, AnimalSize.Large),
        new Animal(false, AnimalSize.Medium)
    };

    AnimalSize[] customSortOrder = new[]
    {
        AnimalSize.Small,
        AnimalSize.Medium,
        AnimalSize.Large
    };

    var results = sampleData.OrderBy( a => Array.IndexOf(customSortOrder, a.Size ));

    foreach (var a in results)
    {
        Console.WriteLine(a.Size);
    }

Output:

Small
Medium
Large

Code on DotNetFiddle


问:
TTS init lag after onInit()
I'm writing an application which uses GoogleTextToSpeech for French language, the problem is that after onInit when I use setLanguage to change the tts language to French the tts object won't work for like 10-15 seconds. I have tried other languages (English, Deutsch) and there is no such problem. I wanna know if there is anyway to know that the tts object has actually started  for the selected language (after onInit)

答:
Well, Just found a solution to this problem hope it helps others as well.
There is a method setOnUtteranceProgressListener(UtteranceProgressListener) which takes a listener and calls it for different events of TTS. so if you register your listener here, and also assign an utteranceId when calling speak method (See how to assign UtteranceId). OnStart method gets called when the tts has actually started to speak. so you can show a progress or whatever from the time you call speak method until when onStart has not been called.

Title: TTS init lag after onInit()


问:
Why isn't Google Maps reloading with new coordinates, with the rest of list detail?
I have a list of events, and each event has a click function that displays the details of that event. Each detail holds a google map which takes the latlng coordinates found inside the clicked event object.

My problem is this: when I click on an event for the first time, the detail comes out correctly, with the correct title, location name and map. But then, the second click renders the new detail of the new event with the correct title, location name BUT the map doesn't change.

Why isn't the map being reloaded with the new coordinates?

here is the code for the 'event list' container:

```<code>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { selectEvent } from '../actions/index.js';

class EventsList extends React.Component {
    render() {
        var createEventsList = this.props.events.map((event, i) => {
            return <li key={i} onClick={() => this.props.selectEvent(event)}>{event.title}</li>
        });
        return(
            <ul>{createEventsList}</ul>
        );
    }
}

function mapStateToProps(state) {
    return {
        events: state.events
    };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ selectEvent: selectEvent }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(EventsList);
</code>```

the code for the 'event detail' container:

```<code>import React from 'react';
import { connect } from 'react-redux';
import GoogleMap from '../components/google_map.js';

class EventDetail extends React.Component{
    render() {
        if(!this.props.event) {
            return <div>Pick an Event</div>
        }
        const latcoord = parseFloat(this.props.event.locationLat);
        const longcoord = parseFloat(this.props.event.locationLong);

        return(
            <div>
                <div>details for:</div>
                <div>{ this.props.event.title }</div>
                <div>{ this.props.event.location }</div>
                <GoogleMap long={longcoord} lat={latcoord}/>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        event: state.eventDetail
    };
}

export default connect(mapStateToProps)(EventDetail);
</code>```

and here is the code for the Google Map component:

```<code>import React from 'react';

export default class GoogleMap extends React.Component{
    componentDidMount() {
        new google.maps.Map(this.refs.map, {
            zoom: 15,
            center: {
                lat: this.props.lat,
                lng: this.props.long
            }
        });
    }
    render() {
        return(
            <div className="google-map" ref="map"></div>
        );
    }
}
</code>```

答:
Since componentDidMount gets called only once when the component is mounted, when you click on an event for the second time, the map is not getting updated. To correct this you will need to implement componentDidUpdate() function. Also you should save the map in a state or in this context. You wouldn't want to create a new map always.

```<code>componentDidMount() {
        this.map = new google.maps.Map(this.refs.map, {
            zoom: 15,
            center: {
                lat: this.props.lat,
                lng: this.props.long
            }
        });
}

componentDidUpdate() {
       this.map.panTo(new google.maps.LatLng(this.props.lat, this.props.lng));
}
</code>```

Hope it helps. :)

Body:
I have a list of events, and each event has a click function that displays the details of that event. Each detail holds a google map which takes the latlng coordinates found inside the clicked event object.

My problem is this: when I click on an event for the first time, the detail comes out correctly, with the correct title, location name and map. But then, the second click renders the new detail of the new event with the correct title, location name BUT the map doesn't change.

Why isn't the map being reloaded with the new coordinates?

here is the code for the 'event list' container:

import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { selectEvent } from '../actions/index.js';

class EventsList extends React.Component {
    render() {
        var createEventsList = this.props.events.map((event, i) => {
            return
 this.props.selectEvent(event)}>{event.title}

        });
        return(

{createEventsList}

        );
    }
}

function mapStateToProps(state) {
    return {
        events: state.events
    };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ selectEvent: selectEvent }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(EventsList);

the code for the 'event detail' container:

import React from 'react';
import { connect } from 'react-redux';
import GoogleMap from '../components/google_map.js';

class EventDetail extends React.Component{
    render() {
        if(!this.props.event) {
            return
Pick an Event

        }
        const latcoord = parseFloat(this.props.event.locationLat);
        const longcoord = parseFloat(this.props.event.locationLong);

        return(

details for:

{ this.props.event.title }

{ this.props.event.location }

                <GoogleMap long={longcoord} lat={latcoord}/>

        );
    }
}

function mapStateToProps(state) {
    return {
        event: state.eventDetail
    };
}

export default connect(mapStateToProps)(EventDetail);

and here is the code for the Google Map component:

import React from 'react';

export default class GoogleMap extends React.Component{
    componentDidMount() {
        new google.maps.Map(this.refs.map, {
            zoom: 15,
            center: {
                lat: this.props.lat,
                lng: this.props.long
            }
        });
    }
    render() {
        return(

        );
    }
}

Body:
Since componentDidMount gets called only once when the component is mounted, when you click on an event for the second time, the map is not getting updated. To correct this you will need to implement componentDidUpdate() function. Also you should save the map in a state or in this context. You wouldn't want to create a new map always.

componentDidMount() {
        this.map = new google.maps.Map(this.refs.map, {
            zoom: 15,
            center: {
                lat: this.props.lat,
                lng: this.props.long
            }
        });
}

componentDidUpdate() {
       this.map.panTo(new google.maps.LatLng(this.props.lat, this.props.lng));
}

Hope it helps. :)


问:
Android ListView - onListItemClick does not work properly
I created a ListView in Android, and a corresponding ListActivity. Each individual item in the ListView has just one TextView (I plan to add an image and a CheckBox later).The ListActivity overrides the  onListItemClick to perform certain tasks on click of any item on the list.

Heres whats happening -

When I first tried clicking on any item, nothing happened.

I then tried setting the properties "Focusable" and "Focusable in Touch Mode" to false for the TextView, as mentioned here, here and here. The List items started recognizing clicks, but only when I clicked somewhere away from the TextView. Whenever I tried clicking on the TextView or anywhere near it, it did not work.

I also tried changing various attributes like Clickable, but nothing has worked so far.

Any idea what I could be doing wrong ?

Thanks

答: After playing around with virtually every attribute in my TextView, I finally found the reason why it was not working. It was because of the attribute android:inputType="text" in my TextView. I'm not sure why I added that piece of code (I probably copied the TextView from one of my other applications), but removing it solves my problem.</p>


问:
Skills bar with jQuery and Sass
I am making a portfolio page and I am trying to include a skills bar that animates the width with jQuery but something is going wrong - nothing happens.

HTML

```<code><div class="skillbar clearfix" data-percent="89%">
              <div class="skillbar-title"><span>HTML5</span></div>
              <div class="skillbar-bar"></div>
              <div class="skill-bar-percent">89%</div>
            </div>

            <div class="skillbar clearfix" data-percent="87%">
              <div class="skillbar-title"><span>CSS3</span></div>
              <div class="skillbar-bar"></div>
              <div class="skill-bar-percent">87%</div>
            </div>

            <div class="skillbar clearfix" data-percent="58%">
              <div class="skillbar-title"><span>JavaScript</span></div>
              <div class="skillbar-bar"></div>
              <div class="skill-bar-percent">58%</div>
            </div>

            <div class="skillbar clearfix" data-percent="68%">
              <div class="skillbar-title"><span>jQuery</span></div>
              <div class="skillbar-bar"></div>
              <div class="skill-bar-percent">68%</div>
            </div>

            <div class="skillbar clearfix" data-percent="73%">
              <div class="skillbar-title"><span>Sass</span></div>
              <div class="skillbar-bar"></div>
              <div class="skill-bar-percent">73%</div>
            </div>

            <div class="skillbar clearfix" data-percent="82%">
              <div class="skillbar-title"><span>Bootstrap</span></div>
              <div class="skillbar-bar"></div>
              <div class="skill-bar-percent">82%</div>
            </div>
</code>```

SASS

.skillbar
  position: relative
  display: block
  margin: 1.4rem auto
  width: 85%
  background: $col-gray
  height: 2.4rem
  border-radius: 3px
  transition: 0.1s linear
  transition-property: width, background-color
.skillbar-title
  position: absolute
  top: 0
  left: 0
  width: 110px
  font-weight: bold
  font-size: 1rem
  color: #ffffff
  background: $col-darkgray
  border-top-left-radius: 3px
  border-bottom-left-radius: 3px
.skillbar-title span
  display: block
  background: rgba(0, 0, 0, 0.1)
  padding: 0 20px
  height: 2.4rem
  line-height: 35px
  text-align: center
  border-top-left-radius: 3px
  border-bottom-left-radius: 3px
.skillbar-bar
  height: 2.4rem
  width: 0px
  background: $col-aqua
  border-radius: 3px
.skill-bar-percent
  position: absolute
  right: 10px
  top: .3rem
  font-size: 1rem
  height: 1.4rem
  line-height: 1.5
  color: $col-light
```

<p><strong>jQuery</strong></p>

<pre class="lang-js prettyprint-override"><code>$(document).ready(function(){
    $('.skillbar').each(function(){
        $(this).find('.skillbar-bar').animate({
            width:$(this).attr('data-percent')
        },4000);
    });
});
</code>```

The div should go from 0px (defined in .skillbar-bar) to the value of data-percent (defined in the HTML).

My problem is that absolutely nothing happens when I load the page.

答: After all, it turned out it was a bad jQuery CND link. I console.log-ed separate elements of the jQuery snippet but everything worked fine so I did not bother checking the console. Sorry for the unnecessary question and thank you for your help!</p>

Title: Skills bar with jQuery and Sass

Body:
I am making a portfolio page and I am trying to include a skills bar that animates the width with jQuery but something is going wrong - nothing happens.

HTML

HTML5

89%

CSS3

87%

JavaScript

58%

jQuery

68%

Sass

73%

Bootstrap

82%

SASS

.skillbar
  position: relative
  display: block
  margin: 1.4rem auto
  width: 85%
  background: $col-gray
  height: 2.4rem
  border-radius: 3px
  transition: 0.1s linear
  transition-property: width, background-color
.skillbar-title
  position: absolute
  top: 0
  left: 0
  width: 110px
  font-weight: bold
  font-size: 1rem
  color: #ffffff
  background: $col-darkgray
  border-top-left-radius: 3px
  border-bottom-left-radius: 3px
.skillbar-title span
  display: block
  background: rgba(0, 0, 0, 0.1)
  padding: 0 20px
  height: 2.4rem
  line-height: 35px
  text-align: center
  border-top-left-radius: 3px
  border-bottom-left-radius: 3px
.skillbar-bar
  height: 2.4rem
  width: 0px
  background: $col-aqua
  border-radius: 3px
.skill-bar-percent
  position: absolute
  right: 10px
  top: .3rem
  font-size: 1rem
  height: 1.4rem
  line-height: 1.5
  color: $col-light

jQuery

$(document).ready(function(){
    $('.skillbar').each(function(){
        $(this).find('.skillbar-bar').animate({
            width:$(this).attr('data-percent')
        },4000);
    });
});

The div should go from 0px (defined in .skillbar-bar) to the value of data-percent (defined in the HTML).

My problem is that absolutely nothing happens when I load the page.


问:
Cost of developing a Google Assistant App?
What costs are involved with developing and/or releasing a Google Assistant App? </p>

<p>eg: Can you develop an app using DialogFlow and a backend (say Firebase) without having to pay while you learn? </p>

答:
As an addition to shortQuestion's answer:

The free plan in Firebase should be enough if you're just using it for learning and developing apps for personal use. If you want to go a bit further you'll need to upgrade the plan.

You can sign up with a free trial for actions on Google to get 300$ of credits during a 12 month period which would be more than enough to do anything you want.

The costs of Firebase/Actions on Google on a higher plan aren't anything to worry about though, you'd be talking about a few cent per multiple hundred thousand requests.

Body:
What costs are involved with developing and/or releasing a Google Assistant App?

eg: Can you develop an app using DialogFlow and a backend (say Firebase) without having to pay while you learn?


问:
How to install an app in MI Note 4?
When i  pressed “Install via USB” in MI Note 4 then the message “The device is temporarily restricted” poped up.Can anyone  tell me how to run android app in MI Note 4 through Android Studio?</p>

答:
In MI devices there are some more restriction because of which Install via usb doesn't work, do this

here's solution that helped me:
1. Settings ->  Additional Settings -> Developer options -> Turn off Miui Optimizations -> Restart
2. Security -> Permissions -> Gear Icon at top right corner -> Turn On "Install via USB"
3. Settings ->  Additional Settings -> Developer options -> Turn On/Off "USB Debugging" -> Turn On "Install vis USB"

Title: How to install an app in MI Note 4?


问:
ESP8266 RTOS SDK pin 16 declaration not found
I am working on a firmware project using ESP-WROOM-02 and a modified custom board with an ESP-WROOM-02 on it. On the custom board, I have pin IO16 connected to a hardware ON/OFF subcircuit and therefore I have to set pin IO16 in GPIO/OUTPUT mode.

However, I cannot find a declaration for pin IO16 in ESP8266 RTOS SDKS's pin_mux_register.h and I cannot set up this pin. Why is pin IO16 excluded from the ESP8266 RTOS SDK? Here is a partial schematic with pin IO16 labeled as FAN:

答:
The pin is badly commented in ESP8266 RTOS SDK and other documentation, however, I've managed to set it up via:

```<code>void ICACHE_FLASH_ATTR gpio16_output_conf(void)
{
    WRITE_PERI_REG(PAD_XPD_DCDC_CONF,
                   (READ_PERI_REG(PAD_XPD_DCDC_CONF) & 0xffffffbc) | (uint32)0x1);      // mux configuration for XPD_DCDC to output rtc_gpio0

    WRITE_PERI_REG(RTC_GPIO_CONF,
                   (READ_PERI_REG(RTC_GPIO_CONF) & (uint32)0xfffffffe) | (uint32)0x0);      // mux configuration for out enable

    WRITE_PERI_REG(RTC_GPIO_ENABLE,
                   (READ_PERI_REG(RTC_GPIO_ENABLE) & (uint32)0xfffffffe) | (uint32)0x1);    //out enable
}
</code>```

taken from IoT Demo GPIO16.c implementation file.

Body:
The pin is badly commented in ESP8266 RTOS SDK and other documentation, however, I've managed to set it up via:

void ICACHE_FLASH_ATTR gpio16_output_conf(void)
{
    WRITE_PERI_REG(PAD_XPD_DCDC_CONF,
                   (READ_PERI_REG(PAD_XPD_DCDC_CONF) & 0xffffffbc) | (uint32)0x1);      // mux configuration for XPD_DCDC to output rtc_gpio0

    WRITE_PERI_REG(RTC_GPIO_CONF,
                   (READ_PERI_REG(RTC_GPIO_CONF) & (uint32)0xfffffffe) | (uint32)0x0);      // mux configuration for out enable

    WRITE_PERI_REG(RTC_GPIO_ENABLE,
                   (READ_PERI_REG(RTC_GPIO_ENABLE) & (uint32)0xfffffffe) | (uint32)0x1);    //out enable
}

taken from IoT Demo GPIO16.c implementation file.


问:
How to display only desired columns for data table?
I am trying to figure out how to display only desired columns for my data table when I am substracting observation on the plot, here is my code:

```<code>library(shiny)
library(dplyr)
library(DT)
library(plotly)

# 1) Prepare layout

hair = starwars %>%
  select(hair_color) %>%
  arrange(hair_color) %>%
  distinct()

spec = starwars %>%
  select(species) %>%
  arrange(species) %>%
  distinct()

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput('hair', 'Hair', hair, multiple = TRUE),
      selectInput('spec', 'Species', spec, multiple = TRUE),
      htmlOutput('txt')
    ),
    mainPanel(
      plotlyOutput('plot'),
      dataTableOutput('table')
    )
  )
)

# 2) Prepare data

srv <- function(input, output){

  starwars_data <- reactive({
    starwars_data_as_table <- as.data.frame(starwars)
    starwars_data_as_table = starwars_data_as_table %>%
      tibble::rownames_to_column(var = 'ID')

    starwars_data_as_table$gender[is.na(starwars_data_as_table$gender)] <- 'not applicable'
    starwars_data_as_table$homeworld[is.na(starwars_data_as_table$homeworld)] <- 'unknown'
    starwars_data_as_table$species[is.na(starwars_data_as_table$species)] <- 'unknown'
    starwars_data_as_table$hair_color[is.na(starwars_data_as_table$hair_color)] <- 'not applicable'

    # a) add missing info

    starwars_data = starwars_data_as_table %>%
      mutate(
        height = case_when(
          name == 'Finn' ~ as.integer(178),
          name == 'Rey' ~ as.integer(170),
          name == 'Poe Dameron' ~ as.integer(172),
          name == 'BB8' ~ as.integer(67),
          name == 'Captain Phasma' ~ as.integer(200),
          TRUE ~ height
        ),
        mass = case_when(
          name == 'Finn' ~ 73,
          name == 'Rey' ~ 54,
          name == 'Poe Dameron' ~ 80,
          name == 'BB8' ~ 18,
          name == 'Captain Phasma' ~ 76,
          TRUE ~ mass
        ),
        film_counter = lengths(films),
        vehicle_counter = lengths(vehicles),
        starship_counter = lengths(starships)
      )

    colnames(starwars_data) <- c("ID", "Name","Height", "Weight",
                                 "Hair","Skin","Eyes",
                                 "Birth", "Gender",
                                 "Homeworld","Species", "Movies",
                                 "Vehicles", "Starship", "Number of movies",
                                 "Number of vehicles", "Number of starships")
    starwars_data

  })

  # filter data using input box
  starwars_data_filtered <-  reactive({

    dta <- starwars_data()
    if(length(input$hair) > 0){
      dta <- dta %>%
        filter(Hair %in% input$hair)
    }
    if (length(input$spec) > 0) {
      dta <-  dta %>%
        filter(Species %in% input$spec)
    }
    if (length(input$spec) > 0 & length(input$hair) > 0) {
      dta <-  dta %>%
        filter(Hair %in% input$hair) %>%
        filter(Species %in% input$spec)
    }
    dta
  })

  output$plot <- renderPlotly({
    plot_ly(starwars_data_filtered(),
            source = 'scatter') %>%
      add_markers(
        x = ~Height,
        y = ~Homeworld,
        color = ~factor(Gender),
        key = ~ID
      ) %>%
      layout(
        xaxis = list(title = 'Height', rangemode = "tozero"),
        yaxis = list(title = 'Homeland', rangemode = "tozero"),
        dragmode = "select"
      )
  })

  selected_data = reactive({
    # need to keep all columns from the original dataframe
    # to have necessary info for output$txt
    sel_data = starwars_data_filtered()
    ed = event_data("plotly_selected", source = "scatter")
    if(!is.null(ed)){
      sel_data = sel_data %>%
        filter(ID %in% ed$key)
    }
    sel_data
  })

  output$table = renderDataTable({
    d = selected_data()

    # column names to show in datatable
    columns2show <- c("ID", "Name", "Height", "Weight", "Hair", "Birth",
                      "Number of movies", "Number of vehicles", "Number of starships")
    # column indexes to hide in datatable
    columns2hide <- which(!(colnames(selected_data()) %in% columns2show))

    if(!is.null(d)){
      datatable(d, selection = 'single', rownames = FALSE,
                ## columns to hide ##
                options = list(columnDefs = list(list(visible = FALSE, targets = columns2hide))))
    }
  })

  output$txt = renderText({
    row_count <-  input$table_rows_selected
    if(!is.null(row_count)){

      # a function to create a list from the vector
      vectorBulletList <- function(vector) {
        if(length(vector > 1)) {
          paste0("<ul><li>",
                 paste0(
                   paste0(vector, collpase = ""), collapse = "</li><li>"),
                 "</li></ul>")
        }
      }

      # need to subset dataframe that reacts to selecting points on plot
      # change starwars_data() to selected_data()

      # in starwars dataframe, vehicles and starships are lists
      # need to select the first element of the list (the character vector)
      vehicles <- selected_data()[row_count, "Vehicles"][[1]]
      starships <- selected_data()[row_count, "Starship"][[1]]
      movies <- selected_data()[row_count, "Movies"][[1]]

      paste("Name: ", "<b>",selected_data()[row_count,"Name"],"<br>","</b>",
            "Gender: ", "<b>",selected_data()[row_count,"Gender"],"<br>","</b>",
            "Birth: ", "<b>",selected_data()[row_count,"Birth"],"<br>","</b>",
            "Homeworld: ", "<b>",selected_data()[row_count,"Homeworld"],"<br>","</b>",
            "Species: ", "<b>",selected_data()[row_count,"Species"],"<br>","</b>",
            "Height: ", "<b>",selected_data()[row_count,"Height"],"<br>","</b>",
            "Weight: ", "<b>",selected_data()[row_count,"Weight"],"<br>","</b>",
            "Hair: ", "<b>",selected_data()[row_count,"Hair"],"<br>","</b>",
            "Skin: ", "<b>",selected_data()[row_count,"Skin"],"<br>","</b>",
            "Eyes: ", "<b>",selected_data()[row_count,"Eyes"],"<br>","</b>",
            "<br>",
            "Vehicles: ", "<b>", vectorBulletList(vehicles),"<br>","</b>",
            "<br>",
            "Starship: ", "<b>", vectorBulletList(starships),"<br>","</b>",
            "<br>",
            "Movies: ", "<b>", vectorBulletList(movies),"<br>","</b>")
    }
  })

}
shinyApp(ui, srv)
</code>```

I would like to display only defined columns ("ID", "Name", "Height", "Weight", "Hair", "Birth","Number of movies", "Number of vehicles", "Number of starships") when I am substracting data on the plot. However, there is 'Gender' instead of 'Birth', 'Skin' which I do not want to show and 'Number of Movies' is missing completely. Any ideas why this happens?

答:
this is quite a simple problem but javascript starts indexing on 0 whereas R starts on 1 just subtract on from columns2hide and you will be fine

```<code>srv <- function(input, output) {
  starwars_data <- reactive({
    starwars_data_as_table <- as.data.frame(starwars)
    starwars_data_as_table = starwars_data_as_table %>%
      tibble::rownames_to_column(var = 'ID')

    starwars_data_as_table$gender[is.na(starwars_data_as_table$gender)] <- 'not applicable'
    starwars_data_as_table$homeworld[is.na(starwars_data_as_table$homeworld)] <- 'unknown'
    starwars_data_as_table$species[is.na(starwars_data_as_table$species)] <- 'unknown'
    starwars_data_as_table$hair_color[is.na(starwars_data_as_table$hair_color)] <- 'not applicable'

    # a) add missing info

    starwars_data = starwars_data_as_table %>%
      mutate(
        height = case_when(
          name == 'Finn' ~ as.integer(178),
          name == 'Rey' ~ as.integer(170),
          name == 'Poe Dameron' ~ as.integer(172),
          name == 'BB8' ~ as.integer(67),
          name == 'Captain Phasma' ~ as.integer(200),
          TRUE ~ height
        ),
        mass = case_when(
          name == 'Finn' ~ 73,
          name == 'Rey' ~ 54,
          name == 'Poe Dameron' ~ 80,
          name == 'BB8' ~ 18,
          name == 'Captain Phasma' ~ 76,
          TRUE ~ mass
        ),
        film_counter = lengths(films),
        vehicle_counter = lengths(vehicles),
        starship_counter = lengths(starships)
      )

    colnames(starwars_data) <- c("ID", "Name","Height", "Weight",
                                 "Hair","Skin","Eyes",
                                 "Birth", "Gender",
                                 "Homeworld","Species", "Movies",
                                 "Vehicles", "Starship", "Number of movies",
                                 "Number of vehicles", "Number of starships")
    starwars_data

  })

  # filter data using input box
  starwars_data_filtered <-  reactive({

    dta <- starwars_data()
    if(length(input$hair) > 0){
      dta <- dta %>%
        filter(Hair %in% input$hair)
    }
    if (length(input$spec) > 0) {
      dta <-  dta %>%
        filter(Species %in% input$spec)
    }
    if (length(input$spec) > 0 & length(input$hair) > 0) {
      dta <-  dta %>%
        filter(Hair %in% input$hair) %>%
        filter(Species %in% input$spec)
    }
    dta
  })

  output$plot <- renderPlotly({
    plot_ly(starwars_data_filtered(),
            source = 'scatter') %>%
      add_markers(
        x = ~Height,
        y = ~Homeworld,
        color = ~factor(Gender),
        key = ~ID
      ) %>%
      layout(
        xaxis = list(title = 'Height', rangemode = "tozero"),
        yaxis = list(title = 'Homeland', rangemode = "tozero"),
        dragmode = "select"
      )
  })

  selected_data = reactive({
    # need to keep all columns from the original dataframe
    # to have necessary info for output$txt
    sel_data = starwars_data_filtered()
    ed = event_data("plotly_selected", source = "scatter")
    if(!is.null(ed)){
      sel_data = sel_data %>%
        filter(ID %in% ed$key)
    }
    sel_data
  })

  output$table = renderDataTable({
    d = selected_data()

    # column names to show in datatable
    columns2show <- c("ID", "Name", "Height", "Weight", "Hair", "Birth",
                      "Number of movies", "Number of vehicles", "Number of starships")
    # column indexes to hide in datatable
    columns2hide <- which(!(colnames(selected_data()) %in% columns2show))

    if(!is.null(d)){
      datatable(d, selection = 'single', rownames = FALSE,
                ## columns to hide ##
                options = list(columnDefs = list(list(visible = FALSE, targets = columns2hide - 1))))
    }
  })

  output$txt = renderText({
    row_count <-  input$table_rows_selected
    if(!is.null(row_count)){

      # a function to create a list from the vector
      vectorBulletList <- function(vector) {
        if(length(vector > 1)) {
          paste0("<ul><li>",
                 paste0(
                   paste0(vector, collpase = ""), collapse = "</li><li>"),
                 "</li></ul>")
        }
      }

      # need to subset dataframe that reacts to selecting points on plot
      # change starwars_data() to selected_data()

      # in starwars dataframe, vehicles and starships are lists
      # need to select the first element of the list (the character vector)
      vehicles <- selected_data()[row_count, "Vehicles"][[1]]
      starships <- selected_data()[row_count, "Starship"][[1]]
      movies <- selected_data()[row_count, "Movies"][[1]]

      paste("Name: ", "<b>",selected_data()[row_count,"Name"],"<br>","</b>",
            "Gender: ", "<b>",selected_data()[row_count,"Gender"],"<br>","</b>",
            "Birth: ", "<b>",selected_data()[row_count,"Birth"],"<br>","</b>",
            "Homeworld: ", "<b>",selected_data()[row_count,"Homeworld"],"<br>","</b>",
            "Species: ", "<b>",selected_data()[row_count,"Species"],"<br>","</b>",
            "Height: ", "<b>",selected_data()[row_count,"Height"],"<br>","</b>",
            "Weight: ", "<b>",selected_data()[row_count,"Weight"],"<br>","</b>",
            "Hair: ", "<b>",selected_data()[row_count,"Hair"],"<br>","</b>",
            "Skin: ", "<b>",selected_data()[row_count,"Skin"],"<br>","</b>",
            "Eyes: ", "<b>",selected_data()[row_count,"Eyes"],"<br>","</b>",
            "<br>",
            "Vehicles: ", "<b>", vectorBulletList(vehicles),"<br>","</b>",
            "<br>",
            "Starship: ", "<b>", vectorBulletList(starships),"<br>","</b>",
            "<br>",
            "Movies: ", "<b>", vectorBulletList(movies),"<br>","</b>")
    }
  })

}
</code>```

Body:
I am trying to figure out how to display only desired columns for my data table when I am substracting observation on the plot, here is my code:

library(shiny)
library(dplyr)
library(DT)
library(plotly)

# 1) Prepare layout

hair = starwars %>%
  select(hair_color) %>%
  arrange(hair_color) %>%
  distinct()

spec = starwars %>%
  select(species) %>%
  arrange(species) %>%
  distinct()

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput('hair', 'Hair', hair, multiple = TRUE),
      selectInput('spec', 'Species', spec, multiple = TRUE),
      htmlOutput('txt')
    ),
    mainPanel(
      plotlyOutput('plot'),
      dataTableOutput('table')
    )
  )
)

# 2) Prepare data

srv <- function(input, output){

  starwars_data <- reactive({
    starwars_data_as_table <- as.data.frame(starwars)
    starwars_data_as_table = starwars_data_as_table %>%
      tibble::rownames_to_column(var = 'ID')

    starwars_data_as_table$gender[is.na(starwars_data_as_table$gender)] <- 'not applicable'
    starwars_data_as_table$homeworld[is.na(starwars_data_as_table$homeworld)] <- 'unknown'
    starwars_data_as_table$species[is.na(starwars_data_as_table$species)] <- 'unknown'
    starwars_data_as_table$hair_color[is.na(starwars_data_as_table$hair_color)] <- 'not applicable'

    # a) add missing info

    starwars_data = starwars_data_as_table %>%
      mutate(
        height = case_when(
          name == 'Finn' ~ as.integer(178),
          name == 'Rey' ~ as.integer(170),
          name == 'Poe Dameron' ~ as.integer(172),
          name == 'BB8' ~ as.integer(67),
          name == 'Captain Phasma' ~ as.integer(200),
          TRUE ~ height
        ),
        mass = case_when(
          name == 'Finn' ~ 73,
          name == 'Rey' ~ 54,
          name == 'Poe Dameron' ~ 80,
          name == 'BB8' ~ 18,
          name == 'Captain Phasma' ~ 76,
          TRUE ~ mass
        ),
        film_counter = lengths(films),
        vehicle_counter = lengths(vehicles),
        starship_counter = lengths(starships)
      )

    colnames(starwars_data) <- c("ID", "Name","Height", "Weight",
                                 "Hair","Skin","Eyes",
                                 "Birth", "Gender",
                                 "Homeworld","Species", "Movies",
                                 "Vehicles", "Starship", "Number of movies",
                                 "Number of vehicles", "Number of starships")
    starwars_data

  })

  # filter data using input box
  starwars_data_filtered <-  reactive({

    dta <- starwars_data()
    if(length(input$hair) > 0){
      dta <- dta %>%
        filter(Hair %in% input$hair)
    }
    if (length(input$spec) > 0) {
      dta <-  dta %>%
        filter(Species %in% input$spec)
    }
    if (length(input$spec) > 0 & length(input$hair) > 0) {
      dta <-  dta %>%
        filter(Hair %in% input$hair) %>%
        filter(Species %in% input$spec)
    }
    dta
  })

  output$plot <- renderPlotly({
    plot_ly(starwars_data_filtered(),
            source = 'scatter') %>%
      add_markers(
        x = ~Height,
        y = ~Homeworld,
        color = ~factor(Gender),
        key = ~ID
      ) %>%
      layout(
        xaxis = list(title = 'Height', rangemode = "tozero"),
        yaxis = list(title = 'Homeland', rangemode = "tozero"),
        dragmode = "select"
      )
  })

  selected_data = reactive({
    # need to keep all columns from the original dataframe
    # to have necessary info for output$txt
    sel_data = starwars_data_filtered()
    ed = event_data("plotly_selected", source = "scatter")
    if(!is.null(ed)){
      sel_data = sel_data %>%
        filter(ID %in% ed$key)
    }
    sel_data
  })

  output$table = renderDataTable({
    d = selected_data()

    # column names to show in datatable
    columns2show <- c("ID", "Name", "Height", "Weight", "Hair", "Birth",
                      "Number of movies", "Number of vehicles", "Number of starships")
    # column indexes to hide in datatable
    columns2hide <- which(!(colnames(selected_data()) %in% columns2show))

    if(!is.null(d)){
      datatable(d, selection = 'single', rownames = FALSE,
                ## columns to hide ##
                options = list(columnDefs = list(list(visible = FALSE, targets = columns2hide))))
    }
  })

  output$txt = renderText({
    row_count <-  input$table_rows_selected
    if(!is.null(row_count)){

      # a function to create a list from the vector
      vectorBulletList <- function(vector) {
        if(length(vector > 1)) {
          paste0("

",
                 paste0(
                   paste0(vector, collpase = ""), collapse = "

"),
                 "

")
        }
      }

      # need to subset dataframe that reacts to selecting points on plot
      # change starwars_data() to selected_data()

      # in starwars dataframe, vehicles and starships are lists
      # need to select the first element of the list (the character vector)
      vehicles <- selected_data()[row_count, "Vehicles"][[1]]
      starships <- selected_data()[row_count, "Starship"][[1]]
      movies <- selected_data()[row_count, "Movies"][[1]]

      paste("Name: ", "",selected_data()[row_count,"Name"],"
","",
            "Gender: ", "",selected_data()[row_count,"Gender"],"
","",
            "Birth: ", "",selected_data()[row_count,"Birth"],"
","",
            "Homeworld: ", "",selected_data()[row_count,"Homeworld"],"
","",
            "Species: ", "",selected_data()[row_count,"Species"],"
","",
            "Height: ", "",selected_data()[row_count,"Height"],"
","",
            "Weight: ", "",selected_data()[row_count,"Weight"],"
","",
            "Hair: ", "",selected_data()[row_count,"Hair"],"
","",
            "Skin: ", "",selected_data()[row_count,"Skin"],"
","",
            "Eyes: ", "",selected_data()[row_count,"Eyes"],"
","",
            "
",
            "Vehicles: ", "", vectorBulletList(vehicles),"
","",
            "
",
            "Starship: ", "", vectorBulletList(starships),"
","",
            "
",
            "Movies: ", "", vectorBulletList(movies),"
","")
    }
  })

}
shinyApp(ui, srv)

I would like to display only defined columns ("ID", "Name", "Height", "Weight", "Hair", "Birth","Number of movies", "Number of vehicles", "Number of starships") when I am substracting data on the plot. However, there is 'Gender' instead of 'Birth', 'Skin' which I do not want to show and 'Number of Movies' is missing completely. Any ideas why this happens?

Body:
this is quite a simple problem but javascript starts indexing on 0 whereas R starts on 1 just subtract on from columns2hide and you will be fine

srv <- function(input, output) {
  starwars_data <- reactive({
    starwars_data_as_table <- as.data.frame(starwars)
    starwars_data_as_table = starwars_data_as_table %>%
      tibble::rownames_to_column(var = 'ID')

    starwars_data_as_table$gender[is.na(starwars_data_as_table$gender)] <- 'not applicable'
    starwars_data_as_table$homeworld[is.na(starwars_data_as_table$homeworld)] <- 'unknown'
    starwars_data_as_table$species[is.na(starwars_data_as_table$species)] <- 'unknown'
    starwars_data_as_table$hair_color[is.na(starwars_data_as_table$hair_color)] <- 'not applicable'

    # a) add missing info

    starwars_data = starwars_data_as_table %>%
      mutate(
        height = case_when(
          name == 'Finn' ~ as.integer(178),
          name == 'Rey' ~ as.integer(170),
          name == 'Poe Dameron' ~ as.integer(172),
          name == 'BB8' ~ as.integer(67),
          name == 'Captain Phasma' ~ as.integer(200),
          TRUE ~ height
        ),
        mass = case_when(
          name == 'Finn' ~ 73,
          name == 'Rey' ~ 54,
          name == 'Poe Dameron' ~ 80,
          name == 'BB8' ~ 18,
          name == 'Captain Phasma' ~ 76,
          TRUE ~ mass
        ),
        film_counter = lengths(films),
        vehicle_counter = lengths(vehicles),
        starship_counter = lengths(starships)
      )

    colnames(starwars_data) <- c("ID", "Name","Height", "Weight",
                                 "Hair","Skin","Eyes",
                                 "Birth", "Gender",
                                 "Homeworld","Species", "Movies",
                                 "Vehicles", "Starship", "Number of movies",
                                 "Number of vehicles", "Number of starships")
    starwars_data

  })

  # filter data using input box
  starwars_data_filtered <-  reactive({

    dta <- starwars_data()
    if(length(input$hair) > 0){
      dta <- dta %>%
        filter(Hair %in% input$hair)
    }
    if (length(input$spec) > 0) {
      dta <-  dta %>%
        filter(Species %in% input$spec)
    }
    if (length(input$spec) > 0 & length(input$hair) > 0) {
      dta <-  dta %>%
        filter(Hair %in% input$hair) %>%
        filter(Species %in% input$spec)
    }
    dta
  })

  output$plot <- renderPlotly({
    plot_ly(starwars_data_filtered(),
            source = 'scatter') %>%
      add_markers(
        x = ~Height,
        y = ~Homeworld,
        color = ~factor(Gender),
        key = ~ID
      ) %>%
      layout(
        xaxis = list(title = 'Height', rangemode = "tozero"),
        yaxis = list(title = 'Homeland', rangemode = "tozero"),
        dragmode = "select"
      )
  })

  selected_data = reactive({
    # need to keep all columns from the original dataframe
    # to have necessary info for output$txt
    sel_data = starwars_data_filtered()
    ed = event_data("plotly_selected", source = "scatter")
    if(!is.null(ed)){
      sel_data = sel_data %>%
        filter(ID %in% ed$key)
    }
    sel_data
  })

  output$table = renderDataTable({
    d = selected_data()

    # column names to show in datatable
    columns2show <- c("ID", "Name", "Height", "Weight", "Hair", "Birth",
                      "Number of movies", "Number of vehicles", "Number of starships")
    # column indexes to hide in datatable
    columns2hide <- which(!(colnames(selected_data()) %in% columns2show))

    if(!is.null(d)){
      datatable(d, selection = 'single', rownames = FALSE,
                ## columns to hide ##
                options = list(columnDefs = list(list(visible = FALSE, targets = columns2hide - 1))))
    }
  })

  output$txt = renderText({
    row_count <-  input$table_rows_selected
    if(!is.null(row_count)){

      # a function to create a list from the vector
      vectorBulletList <- function(vector) {
        if(length(vector > 1)) {
          paste0("<ul><li>",
                 paste0(
                   paste0(vector, collpase = ""), collapse = "</li><li>"),
                 "</li></ul>")
        }
      }

      # need to subset dataframe that reacts to selecting points on plot
      # change starwars_data() to selected_data()

      # in starwars dataframe, vehicles and starships are lists
      # need to select the first element of the list (the character vector)
      vehicles <- selected_data()[row_count, "Vehicles"][[1]]
      starships <- selected_data()[row_count, "Starship"][[1]]
      movies <- selected_data()[row_count, "Movies"][[1]]

      paste("Name: ", "<b>",selected_data()[row_count,"Name"],"<br>","</b>",
            "Gender: ", "<b>",selected_data()[row_count,"Gender"],"<br>","</b>",
            "Birth: ", "<b>",selected_data()[row_count,"Birth"],"<br>","</b>",
            "Homeworld: ", "<b>",selected_data()[row_count,"Homeworld"],"<br>","</b>",
            "Species: ", "<b>",selected_data()[row_count,"Species"],"<br>","</b>",
            "Height: ", "<b>",selected_data()[row_count,"Height"],"<br>","</b>",
            "Weight: ", "<b>",selected_data()[row_count,"Weight"],"<br>","</b>",
            "Hair: ", "<b>",selected_data()[row_count,"Hair"],"<br>","</b>",
            "Skin: ", "<b>",selected_data()[row_count,"Skin"],"<br>","</b>",
            "Eyes: ", "<b>",selected_data()[row_count,"Eyes"],"<br>","</b>",
            "<br>",
            "Vehicles: ", "<b>", vectorBulletList(vehicles),"<br>","</b>",
            "<br>",
            "Starship: ", "<b>", vectorBulletList(starships),"<br>","</b>",
            "<br>",
            "Movies: ", "<b>", vectorBulletList(movies),"<br>","</b>")
    }
  })

}


问:
Android RTL password fields?
It appears that if you have an EditText on android with the

android:inputType="textPassword" or android:password="true

fields on them, right-to-left text does NOT appear right-to-left (stays left-to-right).

However without the password denotations the text does appear RTL.

Is this a known issue or is there a workaround?

答:
If you put inputType = textPassword or set a passwordTransformation method on EditText, text direction is taken as LTR. It means RTL for password is discouraged. You need to write custom TextView to override this behaviour.

Code snippet from android source for TextView.

```<code>// PasswordTransformationMethod always have LTR text direction heuristics returned by
        // getTextDirectionHeuristic, needs reset
        mTextDir = getTextDirectionHeuristic();

protected TextDirectionHeuristic getTextDirectionHeuristic() {
        if (hasPasswordTransformationMethod()) {
            // passwords fields should be LTR
            return TextDirectionHeuristics.LTR;
        }
</code>```

Title: Android RTL password fields?

Body:
If you put inputType = textPassword or set a passwordTransformation method on EditText, text direction is taken as LTR. It means RTL for password is discouraged. You need to write custom TextView to override this behaviour.

Code snippet from android source for TextView.

// PasswordTransformationMethod always have LTR text direction heuristics returned by
        // getTextDirectionHeuristic, needs reset
        mTextDir = getTextDirectionHeuristic();

protected TextDirectionHeuristic getTextDirectionHeuristic() {
        if (hasPasswordTransformationMethod()) {
            // passwords fields should be LTR
            return TextDirectionHeuristics.LTR;
        }


问:
Is there a way to implement some gui (message box that asks for multiple inputs ie. registration document) into a code ive written
I just want a simple popup message box that asks for multiple inputs and such.

```<code>System.out.println("Please enter  Name");
Name = name.nextLine();
System.out.println("Please enter  Age");
age=ages.nextInt();
System.out.println("Please enter  Gender");
Gender =gender.nextLine();
System.out.println("Please enter  Contact Number");
ConNum =number.nextLine();-->
</code>```

Is there a way to make a gui for this? (its a foundation level project)

答:
Use JOptionPane to take your input:

```<code>String name = JOptionPane.showInputDialog(null, "Please enter  Name");
</code>```

Edit:

You could ask the user all the questions on the one box (for this example, ensure they separate the answers by a space).

```<code>String input = JOptionPane.showInputDialog(null, "Please enter name.\nPlease enter age.\nPlease enter gender.");
String[] allInput = input.split("\\s+");
System.out.println("Name: " + allInput[0] + " Age: " + allInput[1] + " Gender: " + allInput[2]);
</code>```

Note: obviously there will be issues, such as not using a space, or using a full name (Jack Sparrow) etc; but it gives you a general idea.

Body:
I just want a simple popup message box that asks for multiple inputs and such.

System.out.println("Please enter  Name");
Name = name.nextLine();
System.out.println("Please enter  Age");
age=ages.nextInt();
System.out.println("Please enter  Gender");
Gender =gender.nextLine();
System.out.println("Please enter  Contact Number");
ConNum =number.nextLine();-->

Is there a way to make a gui for this? (its a foundation level project)

Body:
Use JOptionPane to take your input:

String name = JOptionPane.showInputDialog(null, "Please enter  Name");

Edit:

You could ask the user all the questions on the one box (for this example, ensure they separate the answers by a space).

String input = JOptionPane.showInputDialog(null, "Please enter name.\nPlease enter age.\nPlease enter gender.");
String[] allInput = input.split("\\s+");
System.out.println("Name: " + allInput[0] + " Age: " + allInput[1] + " Gender: " + allInput[2]);

Note: obviously there will be issues, such as not using a space, or using a full name (Jack Sparrow) etc; but it gives you a general idea.


问:
Emulator: Process finished with exit code -1073741819 (0xC0000005)
I'm using android studio 3.0.1, when I start my emulator I get many error messages, I've tried to solve each problem separately, I also searched a lot but nothing works for me.

```<code>12:24 م Emulator: init: Could not find wglGetExtensionsStringARB!

12:24 م Emulator: OpenGL backend 'angle' without OpenGL ES 1.x library
detected. Using GLESv2 only.

12:24 م Emulator: Failed to eglInitialize

12:24 م Emulator: Could not initialize emulated framebuffer

12:24 م Emulator: Warning: requested RAM 1024M too high for your system.
Reducing to maximum supported size 512M

12:25 م Emulator: emulator: ERROR: Could not initialize OpenglES emulation,
use '-gpu off' to disable it.

12:25 م Emulator: Process finished with exit code -1073741819 (0xC0000005)
</code>```

I also tried this

答:
check in your emulator setting Use Host GPU enabled shown in below image

this will you get Android Studio -> Tools -> Android -> AVD Manager here

Body:
I'm using android studio 3.0.1, when I start my emulator I get many error messages, I've tried to solve each problem separately, I also searched a lot but nothing works for me.

12:24 م Emulator: init: Could not find wglGetExtensionsStringARB!

12:24 م Emulator: OpenGL backend 'angle' without OpenGL ES 1.x library
detected. Using GLESv2 only.

12:24 م Emulator: Failed to eglInitialize

12:24 م Emulator: Could not initialize emulated framebuffer

12:24 م Emulator: Warning: requested RAM 1024M too high for your system.
Reducing to maximum supported size 512M

12:25 م Emulator: emulator: ERROR: Could not initialize OpenglES emulation,
use '-gpu off' to disable it.

12:25 م Emulator: Process finished with exit code -1073741819 (0xC0000005)

I also tried this


问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
You'll want to join the tags table again.</p>

```<code>SELECT * FROM users
INNER JOIN tags as t1 on t1.user_id = users.id and t1.name='tag1'
INNER JOIN tags as t2 on t2.user_id = users.id and t2.name='tag2'
</code>```

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

Body:
You'll want to join the tags table again.

SELECT * FROM users
INNER JOIN tags as t1 on t1.user_id = users.id and t1.name='tag1'
INNER JOIN tags as t2 on t2.user_id = users.id and t2.name='tag2'


问:
Why _ (underscore) of type Unit and () treated differently?
I have a method which returns Future[Unit], so when I call whenReady

These two options work: whenReady(doItAsync())(_ => {}) and whenReady(doItAsync()) { _ => }

but this doesn't: whenReady(doItAsync())(() => {})

Are not _ of type Unit and empty params list equivalent in this case?

答:
Although type Unit is similar to void from other languages it is not exactly the same.
This particular trouble comes from a limitation in Java (and thus Scala) generics implementation: they are implemented using type erasure. Particularly it means that generic method can't change the number of arguments. Now what happens when type parameter is Unit? We still must have the same number of arguments and also can't magically change return type to return nothing (void) because this will be a different signature. So the answer is to use some fake type with only fakes values: scala.runtime.BoxedUnit. And thus Unit might represent actual parameter that you don't need but has to be there. And so type signature () => {} doesn't match that because it takes no parameters.

Note also that in Java itself there is the same issue and thus there is a similar thing called java.lang.Void

Update:

To make the point more clear consider following generic vs. non-generic code:

```<code>def foo(f: () => String) = println(f())

def fooGeneric[T](arg: T, f: (T) => String) = println(f(arg))

foo(() => "Non-generic")
fooGeneric[Unit]((), (_) => "generic")
</code>```

Note that also logically fooGeneric[Unit] is the same as foo, you still have to pass first argument and pass function that accept an (useless) argument as the second parameter.

Body:
Although type Unit is similar to void from other languages it is not exactly the same.
This particular trouble comes from a limitation in Java (and thus Scala) generics implementation: they are implemented using type erasure. Particularly it means that generic method can't change the number of arguments. Now what happens when type parameter is Unit? We still must have the same number of arguments and also can't magically change return type to return nothing (void) because this will be a different signature. So the answer is to use some fake type with only fakes values: scala.runtime.BoxedUnit. And thus Unit might represent actual parameter that you don't need but has to be there. And so type signature () => {} doesn't match that because it takes no parameters.

Note also that in Java itself there is the same issue and thus there is a similar thing called java.lang.Void

Update:

To make the point more clear consider following generic vs. non-generic code:

def foo(f: () => String) = println(f())

def fooGeneric[T](arg: T, f: (T) => String) = println(f(arg))

foo(() => "Non-generic")
fooGeneric[Unit]((), (_) => "generic")

Note that also logically fooGeneric[Unit] is the same as foo, you still have to pass first argument and pass function that accept an (useless) argument as the second parameter.