问:
Sort an array of names except for one item
Considering that I have an object like the following where it's possible to have many names and that 'The others' can appear at any index, how can I sort the array having 'The others' always as the first element and the rest of the names sorted in alphabetical order?

```<code>var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];
</code>```

For the sample array above, the desired result would be:

```<code>[
   { id: 3, name: 'The others' },
   { id: 4, name: 'John' },
   { id: 2, name: 'Mary' },
   { id: 1, name: 'Paul' }
]
</code>```

答:
You want to hard code your compare function so that 'The others' always has the lowest/greatest value.

var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];

function compare(a, b){
  if(a.name === "The others") {
   return -1;
  } else if (b.name === "The others") {
   return 1;
  } else if (a.name > b.name){
   return -1;
  } else if (a.name < b.name){
   return 1;
  } else {
   return 0;
  }
}

console.log(friends.sort(compare))```

Body:
Considering that I have an object like the following where it's possible to have many names and that 'The others' can appear at any index, how can I sort the array having 'The others' always as the first element and the rest of the names sorted in alphabetical order?

var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];

For the sample array above, the desired result would be:

[
   { id: 3, name: 'The others' },
   { id: 4, name: 'John' },
   { id: 2, name: 'Mary' },
   { id: 1, name: 'Paul' }
]


来源: stackexchange

问:
Email error -The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP;
I am trying to send email through my asp.net Application and it is throwing the error  "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [SG2PR0601CA0003.apcprd06.prod.outlook.com]"</p>

```<code>       MailMessage message = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
        message.From = new MailAddress("xxx@outlook.com");
        message.To.Add("xxx@gmail.com");
        message.Subject = "Test Email";
        message.Body = "Email Body";
        SmtpServer.Port = 587;
        SmtpServer.Credentials = new
         System.Net.NetworkCredential("xxx@outlook.com", "xxxxxxxx");
        //SmtpServer.EnableSsl = true;
        SmtpServer.Timeout = 60000; // 60 seconds
        SmtpServer.Send(message);
</code>```

答:
below code worked for me</p>

```<code>    System.Net.Mail.AlternateView htmlView = null;
        string from = "xxx@outlook.com";
        using (MailMessage mail = new MailMessage(from, txtEmail.Text.Trim()))
        {
            mail.Subject = "Json File";
            htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body><div style='border-style:solid;border-width:5px;border-radius: 10px; padding-left: 10px;margin: 20px; font-size: 18px;'> <p style='font-family: Vladimir Script;font-weight: bold; color: #f7d722;font-size: 48px;'>Kindly find the Attachment.</p><hr><div width=40%;> <p  style='font-size: 20px;'>Thanks</div></body></html>", null, "text/html");
            mail.AlternateViews.Add(htmlView);
            mail.IsBodyHtml = true;
            System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
            contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
            contentType.Name = "New-Assign04.json";
            mail.Attachments.Add(new Attachment(Server.MapPath("~/App_Data/New-Assign04.json"), contentType));
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp-mail.outlook.com";
            smtp.EnableSsl = true;
            NetworkCredential networkCredential = new NetworkCredential("xxx@outlook.com", "xxxxxxxx");   // username and password
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = networkCredential;
            smtp.Port = 587;
            smtp.Send(mail);
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to send email through my asp.net Application and it is throwing the error  "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [SG2PR0601CA0003.apcprd06.prod.outlook.com]"

       MailMessage message = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
        message.From = new MailAddress("xxx@outlook.com");
        message.To.Add("xxx@gmail.com");
        message.Subject = "Test Email";
        message.Body = "Email Body";
        SmtpServer.Port = 587;
        SmtpServer.Credentials = new
         System.Net.NetworkCredential("xxx@outlook.com", "xxxxxxxx");
        //SmtpServer.EnableSsl = true;
        SmtpServer.Timeout = 60000; // 60 seconds
        SmtpServer.Send(message);

Body:
below code worked for me

    System.Net.Mail.AlternateView htmlView = null;
        string from = "xxx@outlook.com";
        using (MailMessage mail = new MailMessage(from, txtEmail.Text.Trim()))
        {
            mail.Subject = "Json File";
            htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body><div style='border-style:solid;border-width:5px;border-radius: 10px; padding-left: 10px;margin: 20px; font-size: 18px;'> <p style='font-family: Vladimir Script;font-weight: bold; color: #f7d722;font-size: 48px;'>Kindly find the Attachment.</p><hr><div width=40%;> <p  style='font-size: 20px;'>Thanks</div></body></html>", null, "text/html");
            mail.AlternateViews.Add(htmlView);
            mail.IsBodyHtml = true;
            System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
            contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
            contentType.Name = "New-Assign04.json";
            mail.Attachments.Add(new Attachment(Server.MapPath("~/App_Data/New-Assign04.json"), contentType));
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp-mail.outlook.com";
            smtp.EnableSsl = true;
            NetworkCredential networkCredential = new NetworkCredential("xxx@outlook.com", "xxxxxxxx");   // username and password
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = networkCredential;
            smtp.Port = 587;
            smtp.Send(mail);
        }


问:
How do you create custom notifications in Swift 3?
In Objective-C, a custom notification is just a plain NSString, but it's not obvious in the WWDC version of Swift 3 just what it should be.</p>

答:
if you use string-only custom notifications, there's no reason to extend any classes but String

```<code>    extension String {
        var notificationName : Notification.Name{
            return Notification.Name.init(self)
        }
    }
</code>```

Body:
if you use string-only custom notifications, there's no reason to extend any classes but String

    extension String {
        var notificationName : Notification.Name{
            return Notification.Name.init(self)
        }
    }


问:
view doesn't change when login, but change after registering
I'm currently having problem with my login in the main page(I got template from w3layout to practice).

I'm using authentication with default middle ware(guest, user).

After I registered, the auth:check() worked and only show log out link in the main page.

But when I try to login the login pop up modal still there in the main view.

I'm currently new to laravel.

I hope you can help me :D

my route

```<code>Route::get('/', function () {
    return view('mainpage');
});
Route::get('/mail',function(){
    return view('mail');
});
Route::group(['prefix'=>'user'],function(){
    Route::group(['middleware' => 'guest'], function() {
        Route::post('/register',[
            'uses'=>'UserController@postSignup',
            'as'=>'signup',
        ]);
        Route::post('/login',[
            'uses'=>'UserController@postSignin',
            'as'=>'signin',
        ]);
    });
    Route::group(['middleware' => 'auth'], function() {
        Route::get('/logout',[
            'uses'=>'UserController@getLogout',
            'as'=>'logout',
        ]);
    });
});
</code>```

My UserController

```<code>public function postSignup(Request $request){
    $this->validate($request,[
        'name'=>'required',
        'email'=>'email|required|unique:users',
        'password'=>'required|min:4',
        'birthday'=>'required',
        'address'=>'required',
    ]);

    $user = new User([
        'name'=>$request->input('name'),
        'email'=>$request->input('email'),
        'password'=>bcrypt($request->input('password')),
        'birthday'=>$request->input('birthday'),
        'address'=>$request->input('address'),
    ]);
    $user->save();
    Auth::login($user);
    return redirect()->back();
}
public function postSignin(Request $request){
    $this->validate($request,[
        'email'=>'email|required|unique:users',
        'password'=>'required|min:4',
    ]);
    if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
        return redirect()->back();
    }
    return redirect()->back();
}
public function getLogout(){
    Auth::logout();
    return redirect()->back();
}
</code>```

AND IN THE MAIN PAGE

```<code>@if(\Illuminate\Support\Facades\Auth::check())
    <div><a href="{{route('logout')}}">LOG OUT</a></div>
@else
    <div class="w3l_login">
        <a href="#" data-toggle="modal" data-target="#myModal88"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></a>
    </div>
    <div class="modal fade" id="myModal88" tabindex="-1" role="dialog" aria-labelledby="myModal88" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalLabel">Don't Wait, Login now!</h4>
                </div>
                <div class="modal-body modal-body-sub">
                    <div class="row">
                        <div class="col-md-8 modal_body_left modal_body_left1" style="border-right: 1px dotted #C2C2C2;padding-right:3em;">
                            <div class="sap_tabs">
                                <div id="horizontalTab" style="display: block; width: 100%; margin: 0px;">
                                    <ul>
                                        <li class="resp-tab-item" aria-controls="tab_item-0"><span>Sign in</span></li>
                                        <li class="resp-tab-item" aria-controls="tab_item-1"><span>Sign up</span></li>
                                    </ul>
                                    <div class="tab-1 resp-tab-content" aria-labelledby="tab_item-0">
                                        <div class="facts">
                                            <div class="register">
                                                <form action="{{route('signin')}}" method="post">
                                                    <input name="email" placeholder="Email Address" type="text" required="">
                                                    <input name="password" placeholder="Password" type="password" required="">
                                                    <div class="sign-up"><input type="submit"/>{{csrf_field()}}</div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="tab-2 resp-tab-content" aria-labelledby="tab_item-1">
                                        <div class="facts">
                                            <div class="register">
                                                <form action="{{route('signup')}}" method="post">
                                                    <input placeholder="Name" name="name" type="text" required="">
                                                    <input placeholder="Email Address" name="email" type="email" required="">
                                                    <input placeholder="Password" name="password" type="password" required="">
                                                    <input placeholder="Confirm Password" name="password" type="password" required="">
                                                    <input placeholder="Birthday" name="birthday" type="text" required="">
                                                    <input placeholder="Address" name="address" type="text" required="">
                                                    @if(count($errors)>0)
                                                           <div class="alert alert-danger">
                                                           @foreach($errors->all() as $error))
                                                            <p>{{$error}}</p>
                                                           @endforeach
                                                          </div>
                                                    @endif
                                                    <div class="sign-up">
                                                        <input type="submit"/>
                                                        {{csrf_field()}}
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="OR" class="hidden-xs">OR</div>
                        </div>
                        <div class="col-md-4 modal_body_right modal_body_right1">
                            <div class="row text-center sign-with">
                                <div class="col-md-12">
                                    <h3 class="other-nw">Sign in with</h3>
                                </div>
                                <div class="col-md-12">
                                    <ul class="social">
                                        <li class="social_facebook"><a href="#" class="entypo-facebook"></a></li>
                                        <li class="social_dribbble"><a href="#" class="entypo-dribbble"></a></li>
                                        <li class="social_twitter"><a href="#" class="entypo-twitter"></a></li>
                                        <li class="social_behance"><a href="#" class="entypo-behance"></a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endif
</code>```

答:
you should specify your redirect route after login.
If you use redirect()->back(), it will definitely show up that modal.

You can try:

```<code>return redirect('your_route_name');
or return redirect()->route('route_name');
or return redirect()->action('Controller@Action');
</code>```

https://laravel.com/docs/5.5/redirects

Body:
I'm currently having problem with my login in the main page(I got template from w3layout to practice).

I'm using authentication with default middle ware(guest, user).

After I registered, the auth:check() worked and only show log out link in the main page.

But when I try to login the login pop up modal still there in the main view.

I'm currently new to laravel.

I hope you can help me :D

my route

Route::get('/', function () {
    return view('mainpage');
});
Route::get('/mail',function(){
    return view('mail');
});
Route::group(['prefix'=>'user'],function(){
    Route::group(['middleware' => 'guest'], function() {
        Route::post('/register',[
            'uses'=>'UserController@postSignup',
            'as'=>'signup',
        ]);
        Route::post('/login',[
            'uses'=>'UserController@postSignin',
            'as'=>'signin',
        ]);
    });
    Route::group(['middleware' => 'auth'], function() {
        Route::get('/logout',[
            'uses'=>'UserController@getLogout',
            'as'=>'logout',
        ]);
    });
});

My UserController

public function postSignup(Request $request){
    $this->validate($request,[
        'name'=>'required',
        'email'=>'email|required|unique:users',
        'password'=>'required|min:4',
        'birthday'=>'required',
        'address'=>'required',
    ]);

    $user = new User([
        'name'=>$request->input('name'),
        'email'=>$request->input('email'),
        'password'=>bcrypt($request->input('password')),
        'birthday'=>$request->input('birthday'),
        'address'=>$request->input('address'),
    ]);
    $user->save();
    Auth::login($user);
    return redirect()->back();
}
public function postSignin(Request $request){
    $this->validate($request,[
        'email'=>'email|required|unique:users',
        'password'=>'required|min:4',
    ]);
    if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
        return redirect()->back();
    }
    return redirect()->back();
}
public function getLogout(){
    Auth::logout();
    return redirect()->back();
}

AND IN THE MAIN PAGE

@if(\Illuminate\Support\Facades\Auth::check())

LOG OUT

@else

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Don't Wait, Login now!

Sign in

Sign up

                                                <form action="{{route('signin')}}" method="post">
                                                    <input name="email" placeholder="Email Address" type="text" required="">
                                                    <input name="password" placeholder="Password" type="password" required="">

<input type="submit"/>{{csrf_field()}}

                                                </form>

                                                <form action="{{route('signup')}}" method="post">
                                                    <input placeholder="Name" name="name" type="text" required="">
                                                    <input placeholder="Email Address" name="email" type="email" required="">
                                                    <input placeholder="Password" name="password" type="password" required="">
                                                    <input placeholder="Confirm Password" name="password" type="password" required="">
                                                    <input placeholder="Birthday" name="birthday" type="text" required="">
                                                    <input placeholder="Address" name="address" type="text" required="">
                                                    @if(count($errors)>0)

                                                           @foreach($errors->all() as $error))

{{$error}}

                                                           @endforeach

                                                    @endif

                                                        <input type="submit"/>
                                                        {{csrf_field()}}

                                                </form>

OR

Sign in with

@endif

Body:
you should specify your redirect route after login.
If you use redirect()->back(), it will definitely show up that modal.

You can try:

return redirect('your_route_name');
or return redirect()->route('route_name');
or return redirect()->action('Controller@Action');

https://laravel.com/docs/5.5/redirects


问:
How to tell which version of Google App Engine is running
In the Google App Engine app.yaml file, you specify a version property  (though the current preference instead of app.yaml: "...instead, use a command-line flag (--version) to specify your version ID").

In my case, I use this for different environments. (See note at bottom) As documented in app.yaml, unique version values produce unique URLs:

Note: Version names should begin with a letter, to distinguish them from numeric instances which are always specified by a number. This avoids the ambiguity with URLs like 123.my-service.appspot.com...

I use two versions, the first as my "QA environment" , the second as my "Production environment":

dev

1

I want my code to set a variable is_prod, and I want the value to be a boolean True if the version value is equal to 'dev'. How can I do that?

*Note, as @Dan Cornilescu says in the comments, using-versions-for-environments may be a bad idea, per posts like this and this

答:
The google.appengine.api.modules.modules module appears to have the method I want. It produces a string, even though the value is an integer my app.yaml (Google calls this a "numeric instance"):

```<code>from google.appengine.api.modules  import modules

# Adjust for your different versions, these string values are based on my setup in the OP
is_prod = modules.get_current_version_name()=='1'
is_dev= modules.get_current_version_name()=='dev'
</code>```

Body:
The google.appengine.api.modules.modules module appears to have the method I want. It produces a string, even though the value is an integer my app.yaml (Google calls this a "numeric instance"):

from google.appengine.api.modules  import modules

# Adjust for your different versions, these string values are based on my setup in the OP
is_prod = modules.get_current_version_name()=='1'
is_dev= modules.get_current_version_name()=='dev'


问:
Convert Rails API to project back to regular?
I've created a rails API project (Rails 5) to be the back end for my mobile application, but i would now like to create some administrative functions that I can access directly from a browser.

I'm not exactly sure what I need to do to restore all the web features of my rails project so that some of my controllers will service requests for web pages, and things like scaffolding will generate web pages instead of json responses.

Any suggestions appreciated.

答: Just run rails new {your app name} on top of your application and press Y to overwrite the existing files. You can then use Git to look at the changes made and keep the changes that exist for a fresh Rails installation and also the changes you had made on your Rails API project. Run the tests to ensure everything still works and then you're good to go.


问:
Cannot horizontally center fixed width div in IE
I am creating a template for a website.

The example is at Framework Login Page

The main CSS sheet is at: master.css

I am trying to center the main parent div.

I am using

```<code>#body {
  width: 100%;
  background: url('pathtoimage.png');
}

#inner_body{
  width: 800px;
  margin: auto;
}

<body>
  <div id="body">
    <div id="inner_body"></div>
  </div>
</body>
</code>```

What could the issue be?

答:
This is a (very) old IE bug.

Fortunately, it's been fixed since IE 6, but you do need to have a proper doctype on your page to cause IE to use "standards" rendering mode and respect your margin: auto style.  On a page without a doctype, IE instead uses "quirks" mode, which falls back to old, non-standard behavior.

Quirksmode has a good page on doctypes and standards mode that explains why you want to make sure your pages have a correct doctype, including some nice tables spelling out what each browser will do differently in quirks and standards mode.

ContentLicense: CC BY-SA 2.5

Body:
I am creating a template for a website.

The example is at Framework Login Page

The main CSS sheet is at: master.css

I am trying to center the main parent div.

I am using

#body {
  width: 100%;
  background: url('pathtoimage.png');
}

#inner_body{
  width: 800px;
  margin: auto;
}

What could the issue be?


问:
php evaluating multidimensional array from inner array to outer araray
How do I solve the following problem using PHP RecursiveIteratorIterator?

```<code>$arr = array(
    "sum"=>array(2,4,6, "multiply" => array(1,3,5) ),
    "multiply"=>array(3,3,3, "sum" => array(2,4,6) ),
);
</code>```

I am expecting the following answers

```<code>(2 + 4 + 6 + ( 1 * 3 * 5) ) = 27;
(3 * 3 * 3 * (2 + 4 + 6)) = 324;
</code>```

Partial code so far..

```<code>   $calc = new ArrayObject($arr);
   $MRI = new RecursiveIteratorIterator(new      MyRecursiveIterator($calc), 1);
   foreach ($MRI as $key=>$value) {
   echo " Current Depth: ". $MRI->getDepth() . "\n";
   echo $key . " : " . $value . "\n";
   $currentDepth = $MRI->getDepth();
   for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--)
   { echo "sub Depth: ". $subDepth . "\n";
   $subIterator = $MRI->getSubIterator($subDepth);
   // var_dump($subIterator); } }
</code>```

答:
You can do it like this, do the calculation from the innermost of the array. Check the demo.

```<code><?php
function f(&$array)
{
    foreach($array as $k => &$v)
    {
        if(is_array($v))
        {
            if(count($v) == count($v, 1))
            {
                unset($array[$k]);
                if($k == 'sum')
                {
                    $v =  array_sum($v);
                    $array[] = $v;

                }elseif($k == 'multiply'){
                    $v = array_product($v);
                    $array[] = $v;
                }else{

                    foreach($v as $vv)
                        $array[] = $vv;
                }
            }else
                f($v);
        }
    }
}

while(count($array) != count($array, 1))
{
    f($array);
}

print_r($array);
</code>```

Note：

traverse array from outer to inner

traverse array from inner to outer

Body:
How do I solve the following problem using PHP RecursiveIteratorIterator?

$arr = array(
    "sum"=>array(2,4,6, "multiply" => array(1,3,5) ),
    "multiply"=>array(3,3,3, "sum" => array(2,4,6) ),
);

I am expecting the following answers

(2 + 4 + 6 + ( 1 * 3 * 5) ) = 27;
(3 * 3 * 3 * (2 + 4 + 6)) = 324;

Partial code so far..

   $calc = new ArrayObject($arr);
   $MRI = new RecursiveIteratorIterator(new      MyRecursiveIterator($calc), 1);
   foreach ($MRI as $key=>$value) {
   echo " Current Depth: ". $MRI->getDepth() . "\n";
   echo $key . " : " . $value . "\n";
   $currentDepth = $MRI->getDepth();
   for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--)
   { echo "sub Depth: ". $subDepth . "\n";
   $subIterator = $MRI->getSubIterator($subDepth);
   // var_dump($subIterator); } }

Body:
You can do it like this, do the calculation from the innermost of the array. Check the demo.

<?php
function f(&$array)
{
    foreach($array as $k => &$v)
    {
        if(is_array($v))
        {
            if(count($v) == count($v, 1))
            {
                unset($array[$k]);
                if($k == 'sum')
                {
                    $v =  array_sum($v);
                    $array[] = $v;

                }elseif($k == 'multiply'){
                    $v = array_product($v);
                    $array[] = $v;
                }else{

                    foreach($v as $vv)
                        $array[] = $vv;
                }
            }else
                f($v);
        }
    }
}

while(count($array) != count($array, 1))
{
    f($array);
}

print_r($array);

Note：

traverse array from outer to inner

traverse array from inner to outer


问:
Style node of Dabeng's OrgChart library
I am using the Dabeng Orgchart library, but I would like to customize the nodes, specifically creating a diamond instead of the squares they have in most examples. I have seen the createNode method, and I have found various CSS for creating a diamond but I can't figure out how to integrate it in dabeng org chart.  What I want to do is display a diamond if some conditions are met, and the default square shapes if others are met. I have searched the web, but no example for changing the shape.</p>

答:
I would suggest you to use getorgchart instead it is highly customizable

http://www.getorgchart.com/Demos/Create-Your-Own-Theme-4

ContentLicense: CC BY-SA 4.0

Title: Style node of Dabeng's OrgChart library


问:
producing related 'detail' for a summary query
Data:

```<code>ID          CITY         SEX            AGE
1           NYC          M              23
2           NYC          M              28
3           NYC          F              22
4           NYC          F              19
5           LA           M              29
6           LA           M              25
7           LA           F              18
8           LA           F              21
</code>```

Query: I want to produce the ID of the youngest person for each gender from each city. There are 2 genders, and 2 cities in the data above (although there may be more cities in the actual data).

I want to solve this using both Microsoft Access as well as plain SQL

Below is my solution using Microsoft Access. Do you know a better
solution?

I don't know how to do this with plain SQL. What is your solution?

Data (in Access)

Query 1 (used by Query 2)

Query 2 (uses Query 1, and produces the IDs that I was looking for)

答:
You need to do the join on all three characteristics:

```<code>SELECT table.*
FROM table INNER JOIN (SELECT city, sex, MIN(age) AS min_age
                       FROM Table
                       GROUP BY city, sex) tA ON table.city = tA.city
                                                 AND table.sex = tA.sex
                                                 AND table.age = tA.min_age
</code>```

The advantage here is that the subquery is not correlated, so it gets evaluated just once. A correlated subquery gets evaluated for each record in the parent query and can be performance-intensive for large tables and/or complex join criteria.

Body:
Data:

ID          CITY         SEX            AGE
1           NYC          M              23
2           NYC          M              28
3           NYC          F              22
4           NYC          F              19
5           LA           M              29
6           LA           M              25
7           LA           F              18
8           LA           F              21

Query: I want to produce the ID of the youngest person for each gender from each city. There are 2 genders, and 2 cities in the data above (although there may be more cities in the actual data).

I want to solve this using both Microsoft Access as well as plain SQL

Below is my solution using Microsoft Access. Do you know a better
solution?

I don't know how to do this with plain SQL. What is your solution?

Data (in Access)

Query 1 (used by Query 2)

Query 2 (uses Query 1, and produces the IDs that I was looking for)

Body:
You need to do the join on all three characteristics:

SELECT table.*
FROM table INNER JOIN (SELECT city, sex, MIN(age) AS min_age
                       FROM Table
                       GROUP BY city, sex) tA ON table.city = tA.city
                                                 AND table.sex = tA.sex
                                                 AND table.age = tA.min_age

The advantage here is that the subquery is not correlated, so it gets evaluated just once. A correlated subquery gets evaluated for each record in the parent query and can be performance-intensive for large tables and/or complex join criteria.


问:
java script whack a mole, dynamically removing mole
I am not sure how to remove a mole at a random timed interval, any thoughts? the instructions are..One of the few tasks which remains is to make the randomly appearing moles, disappear at random! Each randomly added mole should also disappear after a separately random time.</p>

```<code>   function timeDecrease(){
   $("#timer").show();
   $("#timer").html(time + " seconds left")
   time -= 1;
   if (time >0)
     {
      t = setTimeout("timeDecrease()",1000);
     }
     else time = 0;
     };

function randomMole(min,max){
  return Math.floor(Math.random() * (max - min + 1)) + min;
};
 function addMole(){

   yPos = getY();
   xPos = getX();

   $("#gamespace").append('<img class= "Image" img src="img/mole.png"
   style ="top:'+yPos+'px; bottom:
  '+xPos+'px;left:'+xPos+'px;right:'+yPos+'px;"/>');
   moreMoles = setTimeout(addMole,randomMole(0,2000));
</code>```

答:
In your addMole function, store a reference to the new mole and set a timer to remove it.

```<code>let newMole = $(`<img
                   class="Image"
                   src="img/mole.png"
                   style="top: ${yPos}px; left: ${xPos}px;"
                 >`);
$("#gamespace").append(newMole);
setTimeout(newMole.remove.bind(newMole), randomMole(1000, 2000));
moreMoles = setTimeout(addMole,randomMole(0,2000));
</code>```

We use template literals because they hurt less than concatenating strings. newMole.remove() would remove the new mole from the DOM, but calling it as a setTimeout callback won't work. It would be called by window, so the this keyword would be set to window, but jQuery expects this to be set to the element you're removing. newMole.remove.bind(newMole) gives us a version of newMole.remove with this explicitly set to newMole.

Body:
I am not sure how to remove a mole at a random timed interval, any thoughts? the instructions are..One of the few tasks which remains is to make the randomly appearing moles, disappear at random! Each randomly added mole should also disappear after a separately random time.

   function timeDecrease(){
   $("#timer").show();
   $("#timer").html(time + " seconds left")
   time -= 1;
   if (time >0)
     {
      t = setTimeout("timeDecrease()",1000);
     }
     else time = 0;
     };

function randomMole(min,max){
  return Math.floor(Math.random() * (max - min + 1)) + min;
};
 function addMole(){

   yPos = getY();
   xPos = getX();

   $("#gamespace").append('');
   moreMoles = setTimeout(addMole,randomMole(0,2000));

Body:
In your addMole function, store a reference to the new mole and set a timer to remove it.

let newMole = $(`<img
                   class="Image"
                   src="img/mole.png"
                   style="top: ${yPos}px; left: ${xPos}px;"
                 >`);
$("#gamespace").append(newMole);
setTimeout(newMole.remove.bind(newMole), randomMole(1000, 2000));
moreMoles = setTimeout(addMole,randomMole(0,2000));

We use template literals because they hurt less than concatenating strings. newMole.remove() would remove the new mole from the DOM, but calling it as a setTimeout callback won't work. It would be called by window, so the this keyword would be set to window, but jQuery expects this to be set to the element you're removing. newMole.remove.bind(newMole) gives us a version of newMole.remove with this explicitly set to newMole.


问:
how to add Closable admob banner to android app
I added Admon to my android app.
what I want to do, add a Closable banner that has "X" that allows the user to close the banner
i've seen many apps do that.</p>

答:
Adjust button on Banner and set visibility on button click</p>

```<code>btnCloseAd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adView.destroy();
            adView.setVisibility(View.GONE);
        }
    });
</code>```

Body:
Adjust button on Banner and set visibility on button click

btnCloseAd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adView.destroy();
            adView.setVisibility(View.GONE);
        }
    });


问:
How to keep a div on the right side of the page in CSS
I'm building a website, and I'm trying to get a div element to stick to the right side of the page.

However, when my other divs, that contain blog post data/images scroll over to the next page, the div gets entered down.

How do I prevent the right side column from being entered down, while still allowing my blog post entries to scroll over?

Here is my code, what's relevant anyways. I'm sorry if this is a beginner question (it really is). I appreciate all the help I can get.
Thanks.

```<code>.column {
    float:left;
}

.column.main {
    width:70%;
    min-height:1px;
}

.column.side {
    width:20%;
    min-height:1px;

}

.column.left {
    width:10%;
    background-color:012C40;
    height:85%;
    min-width:1px;
}

.column.right {
    width:10%;
    background-color:012C40;
    height:85%;
    float:right;
    min-height:1px;
}

.postAd {
    width:19%;
    height:32%;
    float:left;
    background-color:DAEBF2;
    text-align:center;
    display:inline-block;
    margin:.5%;
    overflow: auto;
}

.postAd img {
    width:80%;
    height:80%;*/
}

<div class="column left">
</div>
<!--middle content-->

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">
</div>

<!--right side content-->

<div class="column right">
</div>
</code>```

First of all, thanks for all of the proposed solutions! However, I've tried each one, and I'm running into problems. I have a navigation bar on top of my website, and each one overwrites that bar. When I try to make adaptations, I get the same problem as before. How do I implement these without completely destroying the layout of my website?

Again, huge thanks to everyone that responded.

答:
I think this what you are looking to do

The right-left columns should be position:fixed then I just put width:150px then for the right column width:150px and I set up for the middle content margin-left: 150px and margin-right: 150px; that's all
and I used for items in the middle content to show flex-warp

this code:

```<code>flex-wrap: wrap;
padding: 0;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
align-items: left;
justify-content: left;
</code>```

Here's the code:

```<code><!DOCTYPE html>
<html>
<head>
<style>

* {
    box-sizing: border-box;
}

body {
    margin: 0;
}
html {
  height: 100%;
}

.column-left {
    height: 100%;
    width: 15%;
    position: fixed;
    z-index: 999;
    top: 0;
    left: 0;
    background-color: #d6c4ff;
    overflow-x: hidden;
    padding-top: 60px;
}

.column-right {
    height: 100%;
    width: 15%;
    position: fixed;
    z-index: 999;
    top: 0;
    right: 0;
    background-color: #d6c4ff;
    overflow-x: hidden;
    padding-top: 60px;
}
.middle-content{
    margin-left: 17%;
        margin-right: 17%;
        height: 100%;
    padding: 0;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    flex-wrap: wrap;
    align-items: left;
    justify-content: left;
    }
.postAd {
    width:19%;
    height:32%;
    float:left;
    background-color:#DAEBF2;
    text-align:center;
    display:inline-block;
    margin:.5%;
    overflow: auto;
}

.postAd img {
    width:80%;
    height:80%;*/
}

</style>
</head>
<body>

<!--left side content-->
<div class="column-left">
</div>

<!--middle content-->
<div class="middle-content">
<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">
    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">
    <img src="images/Sunset.JPG" alt="sunset">
    <p>New here!</p>
</div>
<div class="postAd">
    <img src="images/Sunset.JPG" alt="sunset">
    <p>New here!</p>
</div>

</div>

<!--right side content-->

<div class="column-right">
</div>
</body>
</html>
</code>```

Body:
I'm building a website, and I'm trying to get a div element to stick to the right side of the page.

However, when my other divs, that contain blog post data/images scroll over to the next page, the div gets entered down.

How do I prevent the right side column from being entered down, while still allowing my blog post entries to scroll over?

Here is my code, what's relevant anyways. I'm sorry if this is a beginner question (it really is). I appreciate all the help I can get.
Thanks.

.column {
    float:left;
}

.column.main {
    width:70%;
    min-height:1px;
}

.column.side {
    width:20%;
    min-height:1px;

}

.column.left {
    width:10%;
    background-color:012C40;
    height:85%;
    min-width:1px;
}

.column.right {
    width:10%;
    background-color:012C40;
    height:85%;
    float:right;
    min-height:1px;
}

.postAd {
    width:19%;
    height:32%;
    float:left;
    background-color:DAEBF2;
    text-align:center;
    display:inline-block;
    margin:.5%;
    overflow: auto;
}

.postAd img {
    width:80%;
    height:80%;*/
}

Text here!

Text here!

Text here!

Text here!

First of all, thanks for all of the proposed solutions! However, I've tried each one, and I'm running into problems. I have a navigation bar on top of my website, and each one overwrites that bar. When I try to make adaptations, I get the same problem as before. How do I implement these without completely destroying the layout of my website?

Again, huge thanks to everyone that responded.

Body:
I think this what you are looking to do

The right-left columns should be position:fixed then I just put width:150px then for the right column width:150px and I set up for the middle content margin-left: 150px and margin-right: 150px; that's all
and I used for items in the middle content to show flex-warp

this code:

flex-wrap: wrap;
padding: 0;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
align-items: left;
justify-content: left;

Here's the code:

<!DOCTYPE html>
<html>
<head>
<style>

* {
    box-sizing: border-box;
}

body {
    margin: 0;
}
html {
  height: 100%;
}

.column-left {
    height: 100%;
    width: 15%;
    position: fixed;
    z-index: 999;
    top: 0;
    left: 0;
    background-color: #d6c4ff;
    overflow-x: hidden;
    padding-top: 60px;
}

.column-right {
    height: 100%;
    width: 15%;
    position: fixed;
    z-index: 999;
    top: 0;
    right: 0;
    background-color: #d6c4ff;
    overflow-x: hidden;
    padding-top: 60px;
}
.middle-content{
    margin-left: 17%;
        margin-right: 17%;
        height: 100%;
    padding: 0;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    flex-wrap: wrap;
    align-items: left;
    justify-content: left;
    }
.postAd {
    width:19%;
    height:32%;
    float:left;
    background-color:#DAEBF2;
    text-align:center;
    display:inline-block;
    margin:.5%;
    overflow: auto;
}

.postAd img {
    width:80%;
    height:80%;*/
}

</style>
</head>
<body>

<!--left side content-->
<div class="column-left">
</div>

<!--middle content-->
<div class="middle-content">
<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">
    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">
    <img src="images/Sunset.JPG" alt="sunset">
    <p>New here!</p>
</div>
<div class="postAd">
    <img src="images/Sunset.JPG" alt="sunset">
    <p>New here!</p>
</div>

</div>

<!--right side content-->

<div class="column-right">
</div>
</body>
</html>


问:
DatePicker and TimePicker dialogs incorrect padding
I'm trying to show DatePickerDialog and TimePickerDialog in my Activity using the following code:

```<code>    private void showDatePickerDialog(DatePickerDialog.OnDateSetListener listener) {

        Calendar c = Calendar.getInstance();

        DatePickerDialog dialog = new DatePickerDialog(
                this,
                listener,
                c.get(Calendar.YEAR),
                c.get(Calendar.MONTH),
                c.get(Calendar.DAY_OF_MONTH)
        );

        dialog.show();

    }
</code>```

My activity extends from AppCompatActivity and I have the following dependencies in my gradle file:

```<code>compile 'com.android.support:support-v4:25.4.0'
compile 'com.android.support:appcompat-v7:25.4.0'
compile 'com.android.support:design:25.4.0'
</code>```

The problem is that the dialogs do not have proper padding:

I'm using a Samsung Galaxy J1 with API 22 for testing, my project's minSdkVersion is 16 and targetSdkVersion 25. Any help would be appreciated.

P.S. The same thing happens with Toast messages:

Edit: I'm using the following Theme:

```<code>    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>
        <item name="android:fitsSystemWindows">true</item>
        <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>
    </style>
</code>```

答:
Change your style as for above Api 21 in v21\styles.xml.</p>

```<code> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>
</style>
</code>```

Body:
I'm trying to show DatePickerDialog and TimePickerDialog in my Activity using the following code:

    private void showDatePickerDialog(DatePickerDialog.OnDateSetListener listener) {

        Calendar c = Calendar.getInstance();

        DatePickerDialog dialog = new DatePickerDialog(
                this,
                listener,
                c.get(Calendar.YEAR),
                c.get(Calendar.MONTH),
                c.get(Calendar.DAY_OF_MONTH)
        );

        dialog.show();

    }

My activity extends from AppCompatActivity and I have the following dependencies in my gradle file:

compile 'com.android.support:support-v4:25.4.0'
compile 'com.android.support:appcompat-v7:25.4.0'
compile 'com.android.support:design:25.4.0'

The problem is that the dialogs do not have proper padding:

I'm using a Samsung Galaxy J1 with API 22 for testing, my project's minSdkVersion is 16 and targetSdkVersion 25. Any help would be appreciated.

P.S. The same thing happens with Toast messages:

Edit: I'm using the following Theme:

Body:
Change your style as for above Api 21 in v21\styles.xml.

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>
</style>


问:
go test regex type or syntax
What type or syntax of regex is used when running go test -r <regex> commands? I'm using -list to find the tests I want to run before using -r, like this:

```<code>go test -list 'Foo' *.go
</code>```

I'm having specific difficulty with the following two test names:

```<code>func TestSendTrap(...
func TestSendTrapFull(...
</code>```

This works:

```<code>go test -list 'TestSendTrap\b' *.go
</code>```

So I'm presuming PCRE syntax is being used, but command go doesn't detail.

答: It's Go regex, documented in regexp/syntax.</p>

Title: go test regex type or syntax

Body:
What type or syntax of regex is used when running go test -r <regex> commands? I'm using -list to find the tests I want to run before using -r, like this:

go test -list 'Foo' *.go

I'm having specific difficulty with the following two test names:

func TestSendTrap(...
func TestSendTrapFull(...

This works:

go test -list 'TestSendTrap\b' *.go

So I'm presuming PCRE syntax is being used, but command go doesn't detail.


问:
R: Fast hashing of strings to integer modulo n?
I have a vector of strings and I would like to hash each element individually to integers modulo n.

In this SO post it suggests an approach using digest and strotoi. But when I try it I get NA as the returned value

```<code>library(digest)
strtoi(digest("cc", algo = "xxhash32"), 16L)
</code>```

So the above approach will not work as it can not even produce an integer let alone modulo of one.

What's the best way to hash a large vector of strings to integers modulo n for some n? Efficient solutions are more than welcome as the vector is large.

答:
I made a Rcpp implementation using code from this SO post and the resultant code is quite fast even for large-ish string vectors.

To use it

```<code>if(!require(disk.frame)) devtools::install_github("xiaodaigh/disk.frame")
modn = 17
disk.frame::hashstr2i(c("string1","string2"), modn)
</code>```

Body:
I have a vector of strings and I would like to hash each element individually to integers modulo n.

In this SO post it suggests an approach using digest and strotoi. But when I try it I get NA as the returned value

library(digest)
strtoi(digest("cc", algo = "xxhash32"), 16L)

So the above approach will not work as it can not even produce an integer let alone modulo of one.

What's the best way to hash a large vector of strings to integers modulo n for some n? Efficient solutions are more than welcome as the vector is large.

Body:
I made a Rcpp implementation using code from this SO post and the resultant code is quite fast even for large-ish string vectors.

To use it

if(!require(disk.frame)) devtools::install_github("xiaodaigh/disk.frame")
modn = 17
disk.frame::hashstr2i(c("string1","string2"), modn)


问:
Unable to sort the data from whole table
If I set the pagination to 5 than I'm unbale to sort the data from all pages of the table in ascending or descending order from all pages, it will sort the data only from current page. I want to fix this whatever the pagination is, the data will sorted from all pages of table not only from current page. The Jsfiddle of this is that.

Secondly, how to preset size of pagination to 5 or 10.  Kindly help me out please.

HTML FILE

```<code><div  style="margin-top:35px;">
        <h4>Per Page:</h4>
        <div class="form-group">
            <select name="state" id="maxRows" class="form-control" style="width: 150px;">
            <option value="500">Pagination</option>
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="15">15</option>
            <option value="20">20</option>
            <option value="50">50</option>
            <option value="100">100</option>
            <option value="100">500</option>
            <option value="100">1000</option>
            </select>
          </div>

<table id="mytable" class="table table-hover table-bordered results">
  <thead>
    <tr>
      <th>#</th>
      <th class="col-md-5 col-xs-5">Name</th>
      <th class="col-md-4 col-xs-4">Qty</th>

    </tr>
  </thead>
  <tbody id="my" data-link="row" class="rowlink">
  <tr><td>1</td><td>A</td><td>10</td></tr>
  <tr><td>2</td><td>B</td><td>10</td></tr>
  <tr><td>3</td><td>C</td><td>12</td></tr>
  <tr><td>4</td><td>D</td><td>10</td></tr>
  <tr><td>5</td><td>E</td><td>15</td></tr>
  <tr><td>6</td><td>F</td><td>10</td></tr>
  <tr><td>7</td><td>G</td><td>30</td></tr>
  <tr><td>8</td><td>H</td><td>50</td></tr>
  <tr><td>9</td><td>I</td><td>10</td></tr>
  <tr><td>10</td><td>J</td><td>90</td></tr>
  <tr><td>11</td><td>K</td><td>20</td></tr>
  <tr><td>12</td><td>L</td><td>10</td></tr>

        <tbody>

        </tbody>
</table>
    <div class="pagination-container col-md-6">
        <nav>
            <ul class="pagination"></ul>
        </nav>
    </div>
</code>```

SCRIPT

```<code>    //for pagination

    var table = '#mytable'
    $('#maxRows').on('change', function(){
        $('.pagination').html('')
        var trnum = 0
        var maxRows = parseInt($(this).val())
        var totalRows = $(table+' tbody tr').length
        $(table+' tr:gt(0)').each(function(){
            trnum++
            if(trnum > maxRows){
                $(this).hide()
            }
            if(trnum <= maxRows){
                $(this).show()
            }
        })
        if(totalRows > maxRows){
            var pagenum = Math.ceil(totalRows/maxRows)
            for(var i=1;i<=pagenum;){
                $('.pagination').append('<li data-page="'+i+'">\<span>'+ i++ +'<span class="sr-only">(current)</span></span>\</li>').show()
            }
        }
        $('.pagination li:first-child').addClass('active')
                $('.pagination li').on('click',function(){
                var pagenum = $(this).attr('data-page')
                var trIndex = 0;
                    $('.pagination li').removeClass('active')
                    $(this).addClass('active')
                    $(table+' tr:gt(0)').each(function(){
                    trIndex++
                    if(trIndex > (maxRows*pagenum) || trIndex <= ((maxRows*pagenum)-maxRows)){
                        $(this).hide()
                    }else{
                        $(this).show()
                    }
                    })
                })
    });

    //for sorting per page

$(document).ready(function() {

  $("th").click(function() {
    sortTable($("#mytable"), $(this));
  });

});

function sortTable(table, th) {
    var rows = $(table).find("tr:gt(0)").toArray().sort(compare($(th).index()));

    if ($(th).hasClass("ascending")) {
      $(th).removeClass("ascending").addClass("descending");
      rows = rows.reverse();
    }
    else {
      $(th).removeClass("descending").addClass("ascending");
    }

    for (var i = 0; i < rows.length; i++) {
        $(table).append(rows[i]);
    }

    evenify($(table).attr("id"));
}

function compare(index) {
    return function(a, b) {
        var valA = $(a).children("td").eq(index).html();
        var valB = $(b).children("td").eq(index).html();
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
    }
}
</code>```

My required result on clicking Qty image is attached below

My current result on clicking Qty image is attached below

答: Use https://datatables.net/, do not invent a wheel this time.</p>

Body:
If I set the pagination to 5 than I'm unbale to sort the data from all pages of the table in ascending or descending order from all pages, it will sort the data only from current page. I want to fix this whatever the pagination is, the data will sorted from all pages of table not only from current page. The Jsfiddle of this is that.

Secondly, how to preset size of pagination to 5 or 10.  Kindly help me out please.

HTML FILE

Per Page:

            <select name="state" id="maxRows" class="form-control" style="width: 150px;">
            <option value="500">Pagination</option>
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="15">15</option>
            <option value="20">20</option>
            <option value="50">50</option>
            <option value="100">100</option>
            <option value="100">500</option>
            <option value="100">1000</option>
            </select>

      #
      Name
      Qty

1	A	10

2	B	10

3	C	12

4	D	10

5	E	15

6	F	10

7	G	30

8	H	50

9	I	10

10	J	90

11	K	20

12	L	10

SCRIPT

    //for pagination

    var table = '#mytable'
    $('#maxRows').on('change', function(){
        $('.pagination').html('')
        var trnum = 0
        var maxRows = parseInt($(this).val())
        var totalRows = $(table+' tbody tr').length
        $(table+' tr:gt(0)').each(function(){
            trnum++
            if(trnum > maxRows){
                $(this).hide()
            }
            if(trnum <= maxRows){
                $(this).show()
            }
        })
        if(totalRows > maxRows){
            var pagenum = Math.ceil(totalRows/maxRows)
            for(var i=1;i<=pagenum;){
                $('.pagination').append('
\'+ i++ +'(current)\
').show()
            }
        }
        $('.pagination li:first-child').addClass('active')
                $('.pagination li').on('click',function(){
                var pagenum = $(this).attr('data-page')
                var trIndex = 0;
                    $('.pagination li').removeClass('active')
                    $(this).addClass('active')
                    $(table+' tr:gt(0)').each(function(){
                    trIndex++
                    if(trIndex > (maxRows*pagenum) || trIndex <= ((maxRows*pagenum)-maxRows)){
                        $(this).hide()
                    }else{
                        $(this).show()
                    }
                    })
                })
    });

    //for sorting per page

$(document).ready(function() {

  $("th").click(function() {
    sortTable($("#mytable"), $(this));
  });

});

function sortTable(table, th) {
    var rows = $(table).find("tr:gt(0)").toArray().sort(compare($(th).index()));

    if ($(th).hasClass("ascending")) {
      $(th).removeClass("ascending").addClass("descending");
      rows = rows.reverse();
    }
    else {
      $(th).removeClass("descending").addClass("ascending");
    }

    for (var i = 0; i < rows.length; i++) {
        $(table).append(rows[i]);
    }

    evenify($(table).attr("id"));
}

function compare(index) {
    return function(a, b) {
        var valA = $(a).children("td").eq(index).html();
        var valB = $(b).children("td").eq(index).html();
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
    }
}

My required result on clicking Qty image is attached below

My current result on clicking Qty image is attached below


问:
Not able to create chart using MPAndroidChart in xamarin android
I tried below code to create a pie chart using MPAndroidChart in xamarin.android project..it is not giving any error but chart is not drawn.

Not able to find any example using xamarin.adroid. Please guide me.

PACKAGE USED:

```<code><package id="MPAndroidChart" version="3.0.2" targetFramework="monoandroid60" />
</code>```

LAYOUT:

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

  <LinearLayout
    android:id="@+id/chartlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  </LinearLayout>
</LinearLayout>
</code>```

FRAGMENT:

```<code>public class ChartMainFragment : Android.Support.V4.App.Fragment
{

    private PieChart _chart;
    private float[] yData = { 5, 10, 15, 30, 40 };
    private String[] xData = { "Sony", "Huawei", "LG", "Apple", "Samsung" };
    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your fragment here
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Use this to return your custom view for this Fragment
        View view = inflater.Inflate(Resource.Layout.chart_main_layout, container, false);

        _chart = new PieChart(this.Activity);
        var chartlayout = view.FindViewById<LinearLayout>(Resource.Id.chartlayout);
        chartlayout.AddView(_chart);

        List<PieEntry> entries = new List<PieEntry>();

        entries.Add(new PieEntry(18.5f, "Green"));
        entries.Add(new PieEntry(26.7f, "Yellow"));
        entries.Add(new PieEntry(24.0f, "Red"));
        entries.Add(new PieEntry(30.8f, "Blue"));

        PieDataSet set = new PieDataSet(entries, "");
        PieData data = new PieData(set);
        _chart.Data=data;
        _chart.Invalidate(); // refresh
        return view;
    }
</code>```

OUTPUT:

Please help me to find out reason why chart is not showing properly.

Thanks,

@Paul

答:
Add the PieChart in your layout like this :

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

  <LinearLayout
      android:id="@+id/chartlayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent">

   <com.github.mikephil.charting.charts.PieChart
      android:id="@+id/chart1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
       />
  </LinearLayout>
</LinearLayout>
</code>```

Then in your Fragment  OnCreateView method add color :

```<code>var mChart = view.FindViewById<PieChart>(Resource.Id.chart1);

List<PieEntry> entries = new List<PieEntry>();

entries.Add(new PieEntry(18.5f, "Sony"));
entries.Add(new PieEntry(26.7f, "Huawei"));
entries.Add(new PieEntry(24.0f, "Apple"));
entries.Add(new PieEntry(30.8f, "Samsung"));

PieDataSet set = new PieDataSet(entries, "");

List<Integer> colors = new List<Integer>();

foreach (Integer c in ColorTemplate.VordiplomColors)
    colors.Add(c);

foreach (Integer c in ColorTemplate.JoyfulColors)
    colors.Add(c);

foreach (Integer c in ColorTemplate.ColorfulColors)
    colors.Add(c);

foreach (Integer c in ColorTemplate.LibertyColors)
    colors.Add(c);

foreach (Integer c in ColorTemplate.PastelColors)
    colors.Add(c);

colors.Add((Integer)ColorTemplate.HoloBlue);

set.Colors = colors;

PieData data = new PieData(set);
mChart.Data = data;
mChart.Invalidate(); // refresh
return view;
</code>```

Effect.

For more detail information, you could read this native android example, its usage is almost the same in C#. If there is any problem, please feel free to ask.

Body:
I tried below code to create a pie chart using MPAndroidChart in xamarin.android project..it is not giving any error but chart is not drawn.

Not able to find any example using xamarin.adroid. Please guide me.

PACKAGE USED:

<package id="MPAndroidChart" version="3.0.2" targetFramework="monoandroid60" />

LAYOUT:

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

  <LinearLayout
    android:id="@+id/chartlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  </LinearLayout>
</LinearLayout>

FRAGMENT:

public class ChartMainFragment : Android.Support.V4.App.Fragment
{

    private PieChart _chart;
    private float[] yData = { 5, 10, 15, 30, 40 };
    private String[] xData = { "Sony", "Huawei", "LG", "Apple", "Samsung" };
    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your fragment here
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Use this to return your custom view for this Fragment
        View view = inflater.Inflate(Resource.Layout.chart_main_layout, container, false);

        _chart = new PieChart(this.Activity);
        var chartlayout = view.FindViewById<LinearLayout>(Resource.Id.chartlayout);
        chartlayout.AddView(_chart);

        List<PieEntry> entries = new List<PieEntry>();

        entries.Add(new PieEntry(18.5f, "Green"));
        entries.Add(new PieEntry(26.7f, "Yellow"));
        entries.Add(new PieEntry(24.0f, "Red"));
        entries.Add(new PieEntry(30.8f, "Blue"));

        PieDataSet set = new PieDataSet(entries, "");
        PieData data = new PieData(set);
        _chart.Data=data;
        _chart.Invalidate(); // refresh
        return view;
    }

OUTPUT:

Please help me to find out reason why chart is not showing properly.

Thanks,

@Paul

Body:
Add the PieChart in your layout like this :

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

  <LinearLayout
      android:id="@+id/chartlayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent">

   <com.github.mikephil.charting.charts.PieChart
      android:id="@+id/chart1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
       />
  </LinearLayout>
</LinearLayout>

Then in your Fragment  OnCreateView method add color :

var mChart = view.FindViewById<PieChart>(Resource.Id.chart1);

List<PieEntry> entries = new List<PieEntry>();

entries.Add(new PieEntry(18.5f, "Sony"));
entries.Add(new PieEntry(26.7f, "Huawei"));
entries.Add(new PieEntry(24.0f, "Apple"));
entries.Add(new PieEntry(30.8f, "Samsung"));

PieDataSet set = new PieDataSet(entries, "");

List<Integer> colors = new List<Integer>();

foreach (Integer c in ColorTemplate.VordiplomColors)
    colors.Add(c);

foreach (Integer c in ColorTemplate.JoyfulColors)
    colors.Add(c);

foreach (Integer c in ColorTemplate.ColorfulColors)
    colors.Add(c);

foreach (Integer c in ColorTemplate.LibertyColors)
    colors.Add(c);

foreach (Integer c in ColorTemplate.PastelColors)
    colors.Add(c);

colors.Add((Integer)ColorTemplate.HoloBlue);

set.Colors = colors;

PieData data = new PieData(set);
mChart.Data = data;
mChart.Invalidate(); // refresh
return view;

Effect.

For more detail information, you could read this native android example, its usage is almost the same in C#. If there is any problem, please feel free to ask.


问:
Transforming a list of Long into a Map with long item as the key and list of String as the value
I have a person

```<code>class Person{
  private Long id;
  private String firstName;
  private String lastName;
  //with getters and setters
}
</code>```

I have a following method that receives a person's id and returns a list of tags that are associated with the person

```<code>public List<String> getTags(Long personId){
 /*ExampleImplementation*/
   someCollection.stream()
     .filter(Objects::nonNull)
     .map(SomeType::someMethod)
     .filter(Objects:nonNull)
     .collect(Collectors.toList());
}
</code>```

I am building a method in order to get a map of all the personIds and the list of tags associated with the personId.

```<code>public Map<Long, List<String>>getPersonTags(List<Long> personIds){
  return personIds.stream()
            .collect(Collectors.groupingBy(
            (personId) -> personId,
            Collectors.mapping(this::getTags, Collectors.toList())));
}
</code>```

But getPersonTags() is returning a Map<Long, List<List<String>>> but I expect a Map<Long, List<String>> What should I change to get my expected return type.

答:
If personIds contains distinct values, you don't need to use groupingBy(). Use toMap() instead:

```<code>return personIds.stream()
        .collect(Collectors.toMap(Function.identity(), this::getTags));
</code>```

Body:
I have a person

class Person{
  private Long id;
  private String firstName;
  private String lastName;
  //with getters and setters
}

I have a following method that receives a person's id and returns a list of tags that are associated with the person

public List<String> getTags(Long personId){
 /*ExampleImplementation*/
   someCollection.stream()
     .filter(Objects::nonNull)
     .map(SomeType::someMethod)
     .filter(Objects:nonNull)
     .collect(Collectors.toList());
}

I am building a method in order to get a map of all the personIds and the list of tags associated with the personId.

public Map<Long, List<String>>getPersonTags(List<Long> personIds){
  return personIds.stream()
            .collect(Collectors.groupingBy(
            (personId) -> personId,
            Collectors.mapping(this::getTags, Collectors.toList())));
}

But getPersonTags() is returning a Map<Long, List<List<String>>> but I expect a Map<Long, List<String>> What should I change to get my expected return type.

Body:
If personIds contains distinct values, you don't need to use groupingBy(). Use toMap() instead:

return personIds.stream()
        .collect(Collectors.toMap(Function.identity(), this::getTags));


问:
Comparing arrays in javascript where order doesn't matter
I am learning Javascript, and I saw a function on SO for comparing arrays to check if they are same. However, my current function returns false if the two arrays are [string1,string2] & [string2,string1]. Basically, the two positions are interchanged. The code is as follows:

```<code>function _compareArrays(arr1,arr2){
    var result = arr1 != null && arr2 != null && arr1.length == arr2.length && arr1.every(function(element) {
            return arr2.indexOf(element);
        });
    return result ;
}
</code>```

However, I want these two arrays to be returned as same. So, I changed .every to .indexOf() and it seemed to work. But, I have a doubt, how exactly is the counter getting incremented here to make sure the comparison is being done for every element?
I mean, like, in C++, we do,

```<code>for (int i = 0; i < 10; i++)
    if (arr1[i] == arr2[i]
      cout<<"Elements are same\n";
</code>```

Here, I have an explicit i++ which increments the counter. How does it happen in the above function?

Thanks!

答:
Convert the array into an object instead. Convert array values into keys and their respective count as their value. This is more performant as you iterate over the arrays only once.

```<code>function compare(a, b) {
  if (a.length !== b.length) {
    return false;
  }
  let set = {};
  a.forEach((i) => {
    if (set[i] !== undefined) {
      set[i]++;
    } else {
      set[i] = 1;
    }
  });
  let difference = b.every((i) => {
    if (set[i] === undefined) {
      return false;
    } else {
      set[i]--;
      if (set[i] === 0) {
        delete set[i];
      }
      return true;
    }
  });
  return Object.keys(set) == 0 && difference;
}
</code>```

The first loop on the first array initialises the the set (object), the second loop on the second array subtracts the count and removes the keys when the count hits 0. If a key is not found or if the set is not empty at the end of the procedure, then the arrays are not similar.

Body:
I am learning Javascript, and I saw a function on SO for comparing arrays to check if they are same. However, my current function returns false if the two arrays are [string1,string2] & [string2,string1]. Basically, the two positions are interchanged. The code is as follows:

function _compareArrays(arr1,arr2){
    var result = arr1 != null && arr2 != null && arr1.length == arr2.length && arr1.every(function(element) {
            return arr2.indexOf(element);
        });
    return result ;
}

However, I want these two arrays to be returned as same. So, I changed .every to .indexOf() and it seemed to work. But, I have a doubt, how exactly is the counter getting incremented here to make sure the comparison is being done for every element?
I mean, like, in C++, we do,

for (int i = 0; i < 10; i++)
    if (arr1[i] == arr2[i]
      cout<<"Elements are same\n";

Here, I have an explicit i++ which increments the counter. How does it happen in the above function?

Thanks!

Body:
Convert the array into an object instead. Convert array values into keys and their respective count as their value. This is more performant as you iterate over the arrays only once.

function compare(a, b) {
  if (a.length !== b.length) {
    return false;
  }
  let set = {};
  a.forEach((i) => {
    if (set[i] !== undefined) {
      set[i]++;
    } else {
      set[i] = 1;
    }
  });
  let difference = b.every((i) => {
    if (set[i] === undefined) {
      return false;
    } else {
      set[i]--;
      if (set[i] === 0) {
        delete set[i];
      }
      return true;
    }
  });
  return Object.keys(set) == 0 && difference;
}

The first loop on the first array initialises the the set (object), the second loop on the second array subtracts the count and removes the keys when the count hits 0. If a key is not found or if the set is not empty at the end of the procedure, then the arrays are not similar.


问:
Android Instant App: showInstallPrompt's postInstallIntent does nothing?
The app in the play store currently is configured to handle https://www.example.com/hello/in an intent filter to launch an activity and showInstallPrompt(...) is supposed to launch the activity once installation of the app is finished.

https://developer.android.com/topic/instant-apps/reference.html#public_methods

showInstallPrompt(...) Docs:

Shows a dialog that allows the user to install the current instant app. This method is a no-op if the current running process is an installed app. You must provide a post-install intent, which the system uses to start the application after install is complete.

postInstallIntent Docs:

The intent to launch after the instant app has been installed. This intent must resolve to an activity in the installed app package, or it will not be used.

I've tried doing this:

```<code>Uri uri = Uri.parse("https://www.example.com/hello/");
Intent postInstallIntent = new Intent("action", uri);
InstantApps.showInstallPrompt(MainActivity.this, postInstallIntent, 0, "InstantApp");
</code>```

and this

```<code>Intent postInstallIntent = new Intent("https://www.example.com/hello/");
InstantApps.showInstallPrompt(MainActivity.this, postInstallIntent, 0, "InstantApp");
</code>```

and this

```<code>Intent postInstallIntent = new Intent(Intent.ACTION_VIEW,
        Uri.parse("https://www.example.com/hello/"))
        .addCategory(Intent.CATEGORY_DEFAULT)
        .addCategory(Intent.CATEGORY_BROWSABLE);
</code>```

It brings me the the play store, but neither launches the app automatically once the install is completed.

答:
Please have a look at:

https://github.com/googlesamples/android-instant-apps/tree/master/install-api

and

https://github.com/googlesamples/android-instant-apps/blob/master/install-api/features/install/src/main/java/com/instantappsamples/feature/install/InstallApiActivity.kt

This sample app demonstrates how to use the Install API. The API triggers the Intent to install the app on device.

The call also accepts the Intent, which is triggered after the installation is complete.

The sample also shows the correct structure to implement showInstallPrompt method along with postInstallIntent.

Refer the sample code snippet:

```<code>private val postInstallIntent = Intent(Intent.ACTION_VIEW,
        Uri.parse("https://install-api.instantappsample.com/")).
        addCategory(Intent.CATEGORY_BROWSABLE).
        putExtras(Bundle().apply {
            putString("The key to", "sending data via intent")
        })

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_install)

    val isInstantApp = InstantApps.isInstantApp(this)

    findViewById<Button>(R.id.start_installation).apply {
        isEnabled = isInstantApp
        // Show the installation prompt only for an instant app.
        if (isInstantApp) {
            setOnClickListener {
                InstantApps.showInstallPrompt(this@InstallApiActivity,
                        postInstallIntent,
                        REQUEST_CODE,
                        REFERRER)
            } }
    } }
</code>```

Body:
The app in the play store currently is configured to handle https://www.example.com/hello/in an intent filter to launch an activity and showInstallPrompt(...) is supposed to launch the activity once installation of the app is finished.

https://developer.android.com/topic/instant-apps/reference.html#public_methods

showInstallPrompt(...) Docs:

Shows a dialog that allows the user to install the current instant app. This method is a no-op if the current running process is an installed app. You must provide a post-install intent, which the system uses to start the application after install is complete.

postInstallIntent Docs:

The intent to launch after the instant app has been installed. This intent must resolve to an activity in the installed app package, or it will not be used.

I've tried doing this:

Uri uri = Uri.parse("https://www.example.com/hello/");
Intent postInstallIntent = new Intent("action", uri);
InstantApps.showInstallPrompt(MainActivity.this, postInstallIntent, 0, "InstantApp");

and this

Intent postInstallIntent = new Intent("https://www.example.com/hello/");
InstantApps.showInstallPrompt(MainActivity.this, postInstallIntent, 0, "InstantApp");

and this

Intent postInstallIntent = new Intent(Intent.ACTION_VIEW,
        Uri.parse("https://www.example.com/hello/"))
        .addCategory(Intent.CATEGORY_DEFAULT)
        .addCategory(Intent.CATEGORY_BROWSABLE);

It brings me the the play store, but neither launches the app automatically once the install is completed.

Body:
Please have a look at:

https://github.com/googlesamples/android-instant-apps/tree/master/install-api

and

https://github.com/googlesamples/android-instant-apps/blob/master/install-api/features/install/src/main/java/com/instantappsamples/feature/install/InstallApiActivity.kt

This sample app demonstrates how to use the Install API. The API triggers the Intent to install the app on device.

The call also accepts the Intent, which is triggered after the installation is complete.

The sample also shows the correct structure to implement showInstallPrompt method along with postInstallIntent.

Refer the sample code snippet:

private val postInstallIntent = Intent(Intent.ACTION_VIEW,
        Uri.parse("https://install-api.instantappsample.com/")).
        addCategory(Intent.CATEGORY_BROWSABLE).
        putExtras(Bundle().apply {
            putString("The key to", "sending data via intent")
        })

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_install)

    val isInstantApp = InstantApps.isInstantApp(this)

    findViewById<Button>(R.id.start_installation).apply {
        isEnabled = isInstantApp
        // Show the installation prompt only for an instant app.
        if (isInstantApp) {
            setOnClickListener {
                InstantApps.showInstallPrompt(this@InstallApiActivity,
                        postInstallIntent,
                        REQUEST_CODE,
                        REFERRER)
            } }
    } }


问:
Docker-swarm error: read-only file system
I have been trying to set up swarm using docker-machine. I created a swarm of three VMs using virtualbox driver (swarm-master, swarm-node-00, swarm-node-01) using docker-hub token.
Here is the info:

```<code> [peeyush@localhost ~]$ $(docker-machine_linux-amd64 env --swarm swarm-master)
[peeyush@localhost ~]$ docker info
Containers: 6
Nodes: 3
 swarm-master: 192.168.99.103:2376
  └ Containers: 2
  └ Reserved CPUs: 0 / 4
  └ Reserved Memory: 0 B / 999.9 MiB
 swarm-node-00: 192.168.99.104:2376
  └ Containers: 1
  └ Reserved CPUs: 0 / 4
  └ Reserved Memory: 0 B / 999.9 MiB
 swarm-node-01: 192.168.99.105:2376
  └ Containers: 3
  └ Reserved CPUs: 0 / 4
  └ Reserved Memory: 0 B / 999.9 MiB
</code>```

Now, the when I try to run a container using this swarm, I get this error:

```<code>[peeyush@localhost ~]$ docker run busybox echo "Hello World"
FATA[0029] Error response from daemon: Error pulling image (latest) from busybox, Mktemp failed: mkdir /mnt/sda1/var/lib/docker/graph/_tmp/2385573d8527cb02322beb23238c3d4bb1e35d4d6eec42ad0daa43b51a825eef: read-only file system
</code>```

Could you please help me figure out, what exactly is wrong here?

答:
The error message tells that /mnt/sda1/var/lib/docker/graph/ is mounted as read-only. You can check how it was mounted.

Another thing I can think off top of my head is that you might want to re- configure (change) docker/graph/ where stores docker configuration file, docker images, etc, to another place other than /var/lib/

Body:
I have been trying to set up swarm using docker-machine. I created a swarm of three VMs using virtualbox driver (swarm-master, swarm-node-00, swarm-node-01) using docker-hub token.
Here is the info:

 [peeyush@localhost ~]$ $(docker-machine_linux-amd64 env --swarm swarm-master)
[peeyush@localhost ~]$ docker info
Containers: 6
Nodes: 3
 swarm-master: 192.168.99.103:2376
  └ Containers: 2
  └ Reserved CPUs: 0 / 4
  └ Reserved Memory: 0 B / 999.9 MiB
 swarm-node-00: 192.168.99.104:2376
  └ Containers: 1
  └ Reserved CPUs: 0 / 4
  └ Reserved Memory: 0 B / 999.9 MiB
 swarm-node-01: 192.168.99.105:2376
  └ Containers: 3
  └ Reserved CPUs: 0 / 4
  └ Reserved Memory: 0 B / 999.9 MiB

Now, the when I try to run a container using this swarm, I get this error:

[peeyush@localhost ~]$ docker run busybox echo "Hello World"
FATA[0029] Error response from daemon: Error pulling image (latest) from busybox, Mktemp failed: mkdir /mnt/sda1/var/lib/docker/graph/_tmp/2385573d8527cb02322beb23238c3d4bb1e35d4d6eec42ad0daa43b51a825eef: read-only file system

Could you please help me figure out, what exactly is wrong here?


问:
Why the player is never going forward even if the forward direction is selected?
I'm using ThirdPersonController as player i also tried with a cube.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.IO;

public class DirsFinder : MonoBehaviour
{
    enum Directions
    {
        Forward,Backward,Left,Right
    }

    public Transform player;

    private Transform start;
    private Transform end;
    private GridGenerator gridgenerator;
    public List<Vector3> possibleDirections = new List<Vector3>();
    private Vector3 direction;
    private float m_distanceTraveled = 0f;

    public void Find()
    {
        gridgenerator = GetComponent<GridGenerator>();
        GenerateStartEnd();
        FindDirections();
        m_distanceTraveled = 0;
    }

    private void FindDirections()
    {
        possibleDirections = new List<Vector3>();
        Vector3 playerPosition;
        playerPosition = player.localPosition;

        if (playerPosition.x > 0)
        {
            // can go left
            possibleDirections.Add(Vector3.left);
        }

        if (playerPosition.x + 1.5f < gridgenerator.gridWidth * 1.5f)
        {
            // can go right
            possibleDirections.Add(Vector3.right);
        }

        if (playerPosition.z > 0)
        {
            // can go backward
            possibleDirections.Add(Vector3.back);
        }

        if (playerPosition.z + 1.5f < gridgenerator.gridHeight * 1.5f)
        {
            // can go forward
            possibleDirections.Add(Vector3.forward);
            print("I'm moving forward !!!!!");
        }

        direction = possibleDirections[Random.Range(0, possibleDirections.Count - 1)];

        if (player.position == start.position)
            player.forward = direction;
    }

    private void Update()
    {
        if (m_distanceTraveled < 1.5f)
        {
            Vector3 oldPosition = player.position;
            player.position += direction * Time.deltaTime * 1f;
            m_distanceTraveled += Vector3.Distance(oldPosition, player.position);
        }
    }

    private List<Vector3> GenerateStartEnd()
    {
        GameObject walls = GameObject.Find("Walls");
        List<Transform> wallsParents = new List<Transform>();
        List<Vector3> startEndPos = new List<Vector3>();

        foreach (Transform child in walls.transform)
        {
            wallsParents.Add(child);
        }

        for (int i = 0; i < 2; i++)
        {
            wallsParents.Remove(wallsParents[Random.Range(0, wallsParents.Count)]);
        }

        var childsWall0 = wallsParents[0].GetComponentsInChildren<Transform>().ToList();
        var childsWall1 = wallsParents[1].GetComponentsInChildren<Transform>().ToList();
        childsWall0.RemoveAt(0);
        childsWall1.RemoveAt(0);

        start = childsWall0[Random.Range(0, childsWall0.Count)];
        player.position = start.position;
        end = childsWall1[Random.Range(0, childsWall1.Count)];
        end.tag = "End";
        startEndPos.Add(start.position);
        startEndPos.Add(end.position);

        start.GetComponent<Renderer>().material.color = Color.red;
        end.GetComponent<Renderer>().material.color = Color.blue;

        return startEndPos;
    }
}
</code>```

Inside the FindDirections bottom i'm making the player to be facing to the selected direction:

```<code>if (player.position == start.position)
    player.forward = direction;
</code>```

Then in the Update i'm moving the player by 1.5 fistance on the selected direction.

It's working fine on the 3 directions: Left , Right , Backward

But when it's selecting the forward direction i see the player is moving right.
I tried many times and it's never moving forward on the grid.

I can't figure out why it's not moving forward it does selecting the forward direction sometimes but it's not making the player moving forward on the grid.

In the screenshot it's example of a grid the blue circle is the player the red arrows are what the player is moving and the black arrow should be forward but it's never moving that direction. When it's forward it's moving to the right but never to the black arrow direction as forward should be:

答:
Problem: The Random.Range line:

```<code>direction = possibleDirections[Random.Range(0, possibleDirections.Count - 1)];
</code>```

Solution: To remove the - 1

```<code>direction = possibleDirections[Random.Range(0, possibleDirections.Count];
</code>```

Body:
I'm using ThirdPersonController as player i also tried with a cube.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.IO;

public class DirsFinder : MonoBehaviour
{
    enum Directions
    {
        Forward,Backward,Left,Right
    }

    public Transform player;

    private Transform start;
    private Transform end;
    private GridGenerator gridgenerator;
    public List<Vector3> possibleDirections = new List<Vector3>();
    private Vector3 direction;
    private float m_distanceTraveled = 0f;

    public void Find()
    {
        gridgenerator = GetComponent<GridGenerator>();
        GenerateStartEnd();
        FindDirections();
        m_distanceTraveled = 0;
    }

    private void FindDirections()
    {
        possibleDirections = new List<Vector3>();
        Vector3 playerPosition;
        playerPosition = player.localPosition;

        if (playerPosition.x > 0)
        {
            // can go left
            possibleDirections.Add(Vector3.left);
        }

        if (playerPosition.x + 1.5f < gridgenerator.gridWidth * 1.5f)
        {
            // can go right
            possibleDirections.Add(Vector3.right);
        }

        if (playerPosition.z > 0)
        {
            // can go backward
            possibleDirections.Add(Vector3.back);
        }

        if (playerPosition.z + 1.5f < gridgenerator.gridHeight * 1.5f)
        {
            // can go forward
            possibleDirections.Add(Vector3.forward);
            print("I'm moving forward !!!!!");
        }

        direction = possibleDirections[Random.Range(0, possibleDirections.Count - 1)];

        if (player.position == start.position)
            player.forward = direction;
    }

    private void Update()
    {
        if (m_distanceTraveled < 1.5f)
        {
            Vector3 oldPosition = player.position;
            player.position += direction * Time.deltaTime * 1f;
            m_distanceTraveled += Vector3.Distance(oldPosition, player.position);
        }
    }

    private List<Vector3> GenerateStartEnd()
    {
        GameObject walls = GameObject.Find("Walls");
        List<Transform> wallsParents = new List<Transform>();
        List<Vector3> startEndPos = new List<Vector3>();

        foreach (Transform child in walls.transform)
        {
            wallsParents.Add(child);
        }

        for (int i = 0; i < 2; i++)
        {
            wallsParents.Remove(wallsParents[Random.Range(0, wallsParents.Count)]);
        }

        var childsWall0 = wallsParents[0].GetComponentsInChildren<Transform>().ToList();
        var childsWall1 = wallsParents[1].GetComponentsInChildren<Transform>().ToList();
        childsWall0.RemoveAt(0);
        childsWall1.RemoveAt(0);

        start = childsWall0[Random.Range(0, childsWall0.Count)];
        player.position = start.position;
        end = childsWall1[Random.Range(0, childsWall1.Count)];
        end.tag = "End";
        startEndPos.Add(start.position);
        startEndPos.Add(end.position);

        start.GetComponent<Renderer>().material.color = Color.red;
        end.GetComponent<Renderer>().material.color = Color.blue;

        return startEndPos;
    }
}

Inside the FindDirections bottom i'm making the player to be facing to the selected direction:

if (player.position == start.position)
    player.forward = direction;

Then in the Update i'm moving the player by 1.5 fistance on the selected direction.

It's working fine on the 3 directions: Left , Right , Backward

But when it's selecting the forward direction i see the player is moving right.
I tried many times and it's never moving forward on the grid.

I can't figure out why it's not moving forward it does selecting the forward direction sometimes but it's not making the player moving forward on the grid.

In the screenshot it's example of a grid the blue circle is the player the red arrows are what the player is moving and the black arrow should be forward but it's never moving that direction. When it's forward it's moving to the right but never to the black arrow direction as forward should be:

Body:
Problem: The Random.Range line:

direction = possibleDirections[Random.Range(0, possibleDirections.Count - 1)];

Solution: To remove the - 1

direction = possibleDirections[Random.Range(0, possibleDirections.Count];


问:
Multiple conditions in ngClass - Angular 4
How to use multiple conditions for ngClass? Example:

```<code><section [ngClass]="[menu1 ? 'class1' : '' || menu2 ? 'class1' : '' || (something && (menu1 || menu2)) ? 'class2' : '']">
</code>```

something like this. I got same class for 2 menus,  and I need class when one of those menus is true and 'something' is true. Hope I explained well enough

答:
There are multiple ways to write same logic. As it mentioned earlier, you can use object notation or simply expression. However, I think you should not that much logic in HTML. Hard to test and find issue. You can use a getter function to assign the class.

For Instance;

```<code>public getCustomCss() {
    //Logic here;
    if(this.x == this.y){
        return 'class1'
    }
    if(this.x == this.z){
        return 'class2'
    }
}
<!-- HTML -->
<div [ngClass]="getCustomCss()"> Some prop</div>

//OR

get customCss() {
    //Logic here;
    if(this.x == this.y){
        return 'class1'
    }
    if(this.x == this.z){
        return 'class2'
    }
}
<!-- HTML -->
<div [ngClass]="customCss"> Some prop</div>
</code>```

Body:
How to use multiple conditions for ngClass? Example:

something like this. I got same class for 2 menus,  and I need class when one of those menus is true and 'something' is true. Hope I explained well enough

Body:
There are multiple ways to write same logic. As it mentioned earlier, you can use object notation or simply expression. However, I think you should not that much logic in HTML. Hard to test and find issue. You can use a getter function to assign the class.

For Instance;

public getCustomCss() {
    //Logic here;
    if(this.x == this.y){
        return 'class1'
    }
    if(this.x == this.z){
        return 'class2'
    }
}
<!-- HTML -->
<div [ngClass]="getCustomCss()"> Some prop</div>

//OR

get customCss() {
    //Logic here;
    if(this.x == this.y){
        return 'class1'
    }
    if(this.x == this.z){
        return 'class2'
    }
}
<!-- HTML -->
<div [ngClass]="customCss"> Some prop</div>


问:
List object has AttributeError for a method in a self-defined class
I'm trying to calculate weighted averages. We just started OOP and I'm not sure if my problem is with that or lists.

Here is my code:

```<code>class WeightedAverage:
    """ Class to compute weighted averages. """

    def __init__(self):
        """ Creates empty lists. """
        scoresList = []
        weightsList = []

    def addScore(self,score,weight):
        scoreBool = checkScore(score)
        weightBool = checkWeight(weight)

        if scoreBool == True and weightBool == True:
            scoresList.append(score)
            weightsList.append(weight)

    def checkScore(scr):
        if scr in range(1,10):
            scrBl = True
        else:
            scrBl = False
        return scrBl

    def checkWeight(wgt):
        if wgt in [0.5,1,1.5,2]:
            wgtBl = True
        else:
            wgtBl = False
        return wgtBl

    def getScores(self,scoresList):
        return scoresList

    def getWeights(self,weightsList):
        return weightsList

    def getWAvg(self,scoresList,weightsList):
        wAvg = [scoresList*weightsList for scoresList,weightsList in zip(scoresList,weightsList)]
        return wAvg

# For testing
def main():
    scoresData = [1.5,3,9.2]
    weightsData = [0.5,2,1]

    wAvg = scoresData.getWAvg(scoresData,weightsData)
    print(wAvg)    # should display 15.95/3
</code>```

Where main() is defined as a means of testing the code in my class.

When I run main(), I get the following TraceBack:

```<code>Traceback (most recent call last):
  File "H:\WeightAverages.py", line 58, in <module>
    main()
  File "H:\WeightAverages.py", line 54, in main
    wAvg = scoresData.getWAvg(scoresData,weightsData)
AttributeError: 'list' object has no attribute 'getWAvg'
</code>```

Is this a problem with my class or is it just a list issue? This is my first time writing OO code so I'm not entirely sure this is even right!

答:
you should do this </p>

```<code>class WeightedAverage(object):
""" Class to compute weighted averages. """

    def __init__(self):
        """ Creates empty lists. """
        scoresList = []
        weightsList = []

    def addScore(self,score,weight):
        scoreBool = checkScore(score)
        weightBool = checkWeight(weight)

        if scoreBool == True and weightBool == True:
            scoresList.append(score)
            weightsList.append(weight)

    def checkScore(scr):
        if scr in range(1,10):
            scrBl = True
        else:
            scrBl = False
        return scrBl

    def checkWeight(wgt):
        if wgt in [0.5,1,1.5,2]:
            wgtBl = True
        else:
            wgtBl = False
        return wgtBl

    def getScores(self,scoresList):
        return scoresList

    def getWeights(self,weightsList):
        return weightsList

   def getWAvg(self,scoresList,weightsList):
        wAvg = [scoresList*weightsList for scoresList,weightsList in zip(scoresList,weightsList)]
        return wAvg

# For testing
def main():
    scoresData = [1.5,3,9.2]
    weightsData = [0.5,2,1]
    obj = WeightedAverage()
    wAvg = obj.getWAvg(scoresData,weightsData)
    print(wAvg)
</code>```

Body:
I'm trying to calculate weighted averages. We just started OOP and I'm not sure if my problem is with that or lists.

Here is my code:

class WeightedAverage:
    """ Class to compute weighted averages. """

    def __init__(self):
        """ Creates empty lists. """
        scoresList = []
        weightsList = []

    def addScore(self,score,weight):
        scoreBool = checkScore(score)
        weightBool = checkWeight(weight)

        if scoreBool == True and weightBool == True:
            scoresList.append(score)
            weightsList.append(weight)

    def checkScore(scr):
        if scr in range(1,10):
            scrBl = True
        else:
            scrBl = False
        return scrBl

    def checkWeight(wgt):
        if wgt in [0.5,1,1.5,2]:
            wgtBl = True
        else:
            wgtBl = False
        return wgtBl

    def getScores(self,scoresList):
        return scoresList

    def getWeights(self,weightsList):
        return weightsList

    def getWAvg(self,scoresList,weightsList):
        wAvg = [scoresList*weightsList for scoresList,weightsList in zip(scoresList,weightsList)]
        return wAvg

# For testing
def main():
    scoresData = [1.5,3,9.2]
    weightsData = [0.5,2,1]

    wAvg = scoresData.getWAvg(scoresData,weightsData)
    print(wAvg)    # should display 15.95/3

Where main() is defined as a means of testing the code in my class.

When I run main(), I get the following TraceBack:

Traceback (most recent call last):
  File "H:\WeightAverages.py", line 58, in <module>
    main()
  File "H:\WeightAverages.py", line 54, in main
    wAvg = scoresData.getWAvg(scoresData,weightsData)
AttributeError: 'list' object has no attribute 'getWAvg'

Is this a problem with my class or is it just a list issue? This is my first time writing OO code so I'm not entirely sure this is even right!

Body:
you should do this

class WeightedAverage(object):
""" Class to compute weighted averages. """

    def __init__(self):
        """ Creates empty lists. """
        scoresList = []
        weightsList = []

    def addScore(self,score,weight):
        scoreBool = checkScore(score)
        weightBool = checkWeight(weight)

        if scoreBool == True and weightBool == True:
            scoresList.append(score)
            weightsList.append(weight)

    def checkScore(scr):
        if scr in range(1,10):
            scrBl = True
        else:
            scrBl = False
        return scrBl

    def checkWeight(wgt):
        if wgt in [0.5,1,1.5,2]:
            wgtBl = True
        else:
            wgtBl = False
        return wgtBl

    def getScores(self,scoresList):
        return scoresList

    def getWeights(self,weightsList):
        return weightsList

   def getWAvg(self,scoresList,weightsList):
        wAvg = [scoresList*weightsList for scoresList,weightsList in zip(scoresList,weightsList)]
        return wAvg

# For testing
def main():
    scoresData = [1.5,3,9.2]
    weightsData = [0.5,2,1]
    obj = WeightedAverage()
    wAvg = obj.getWAvg(scoresData,weightsData)
    print(wAvg)