问:
Django Admin conditional display inlines based on models property
I've got marketplace models with fields:

```<code>class VacationEvent(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    process_fba = models.BooleanField(default=True)

    @property
    def has_amazon_fba_vacation(self):
        return hasattr(self, 'amazon_fba_vacation')
</code>```

And in admin.py:

```<code>class FBAInline(admin.StackedInline):
    model = AmazonFBAVacation
    can_delete = False
    verbose_name_plural = 'amazon fba vacation'
    fk_name = 'event'
</code>```

I need to display conditionally FBAInline class when creating\updating VacationEventAdmin. list_filter shows true\false values of "process_fba" field, so if it is true - FBAInline should be displayed:

```<code>@admin.register(VacationEvent)
class VacationEventAdmin(admin.ModelAdmin):
    inlines = []
    list_display = ('id', 'user', 'holiday_name', 'start_date', 'end_date', 'process_fba', 'process_fbm', 'process_walmart', 'process_ebay')
    list_filter = ['process_fba', 'process_fbm', 'process_walmart', 'process_ebay', 'status',]
    search_fields = ['holiday_name', 'user__username']

# if VacationEvent.process_fba and VacationEvent.has_amazon_fba_vacation:
#     inlines.append(FBAInline)

# try:
#     getattr(VacationEvent, 'process_fba')
# except AttributeError:
#     print "doesn't"
# else:
#     inlines.append(FBAInline)
</code>```

I tried getting attr but don't understant how to compare field values for admin. Thanks for any help.

答:
Override get_formsets_with_inlines method

```<code>get_formsets_with_inlines(self, request, obj=None):
    for inline in self.get_inline_instances(request, obj):
        if obj and obj.has_amazon_fba_vacation:
            yield inline.get_formset(request, obj), inline
</code>```

Body:
I've got marketplace models with fields:

class VacationEvent(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    process_fba = models.BooleanField(default=True)

    @property
    def has_amazon_fba_vacation(self):
        return hasattr(self, 'amazon_fba_vacation')

And in admin.py:

class FBAInline(admin.StackedInline):
    model = AmazonFBAVacation
    can_delete = False
    verbose_name_plural = 'amazon fba vacation'
    fk_name = 'event'

I need to display conditionally FBAInline class when creating\updating VacationEventAdmin. list_filter shows true\false values of "process_fba" field, so if it is true - FBAInline should be displayed:

@admin.register(VacationEvent)
class VacationEventAdmin(admin.ModelAdmin):
    inlines = []
    list_display = ('id', 'user', 'holiday_name', 'start_date', 'end_date', 'process_fba', 'process_fbm', 'process_walmart', 'process_ebay')
    list_filter = ['process_fba', 'process_fbm', 'process_walmart', 'process_ebay', 'status',]
    search_fields = ['holiday_name', 'user__username']

# if VacationEvent.process_fba and VacationEvent.has_amazon_fba_vacation:
#     inlines.append(FBAInline)

# try:
#     getattr(VacationEvent, 'process_fba')
# except AttributeError:
#     print "doesn't"
# else:
#     inlines.append(FBAInline)

I tried getting attr but don't understant how to compare field values for admin. Thanks for any help.

Body:
Override get_formsets_with_inlines method

get_formsets_with_inlines(self, request, obj=None):
    for inline in self.get_inline_instances(request, obj):
        if obj and obj.has_amazon_fba_vacation:
            yield inline.get_formset(request, obj), inline


来源: stackexchange

问:
Upgrading Visual Studio 2010 Professional to Premium, just install over?
I just discovered that our MSDN licensing covers Premium, and I installed Professional.

Can I just install Premium over Professional, or do I have to uninstall and reinstall everything? I'd rather not if installing on top of Professional is safe since I have addins and configuration already set up.

答:
I came across the some issue and needed to upgrade from Visual Studio 2010 Professional to Visual Studio 2010 Premium.

I simply installed Visual Studio 2010 Premium over the Visual Studio 2010 Professional version. All worked without issue ;0)

I did need to reinstall my VS add-ins and service packs (such as Silverlight 4 Tools) and point to my original settings file but that was all. Looks like most or all of my extensions remained in place.

ContentLicense: CC BY-SA 2.5


问:
How to convert AES encrypt output bytes to string and vise versa
I want to encrypt texts using PyCrypto AES and write the output ciphertext to a text file. As you know the encrypt() output returns bytes and so I have to decode it to unicode first for it to be accepted by write() method. My problem is both str() and decode() methods throw the same error:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 0: invalid continuation byte
</code>```

Here's part of the encrypted text I'm trying to decode to utf-8:

...\xa5- \xd9\x14_\x02\x18\x96\xde\xbb\xad\xb57>\xe5i\x82H\x9b\xcc\x19y\x0f\x89\x0c~\x81\xb5(\xcc|6\x0b\x1c\xa3\x93E\x91d\xa4\x01\xb3\x98C\xb4,\x94@,\xb0\xb0\xd7\xe2\xf7\xf6U\x129B\xd6#u\x02\xc3\xe4l\xa3\x05V\x143\xe6\x85-\x88\x7f\x14\xc0\x1e\x1d\x19vQ\xbe\xc3\xda8\x06\xaf\xb9\xb7F\x91\xa6\xba&\xcb\xd7\xd0\x12\xed\xfd\xd3n\x06\xb6\x8fZ\xccpO\x05f\x...

答:
AES encryption can output all 1-byte hex numbers (0x00 to 0xFF), however UTF8 requires the last byte in each character  be  in the range 0x00 to 0x7F. This means there will be numerous AES characters that have no corresponding UTF-8 translation, which seems to be the error you're getting.

In fact, if you look closely at your sample text given, it is already in unicode-8. Look at the beginning of your example:

\xa5- \xd9\x14_

This expression contains a unicode-8 hyphen, space, and underscore. The other raw bytes shown are those for which Python couldn't find a corresponding unicode-8 translation.
There is a hyphen, a

ContentLicense: CC BY-SA 3.0

Body:
I want to encrypt texts using PyCrypto AES and write the output ciphertext to a text file. As you know the encrypt() output returns bytes and so I have to decode it to unicode first for it to be accepted by write() method. My problem is both str() and decode() methods throw the same error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 0: invalid continuation byte

Here's part of the encrypted text I'm trying to decode to utf-8:

...\xa5- \xd9\x14_\x02\x18\x96\xde\xbb\xad\xb57>\xe5i\x82H\x9b\xcc\x19y\x0f\x89\x0c~\x81\xb5(\xcc|6\x0b\x1c\xa3\x93E\x91d\xa4\x01\xb3\x98C\xb4,\x94@,\xb0\xb0\xd7\xe2\xf7\xf6U\x129B\xd6#u\x02\xc3\xe4l\xa3\x05V\x143\xe6\x85-\x88\x7f\x14\xc0\x1e\x1d\x19vQ\xbe\xc3\xda8\x06\xaf\xb9\xb7F\x91\xa6\xba&\xcb\xd7\xd0\x12\xed\xfd\xd3n\x06\xb6\x8fZ\xccpO\x05f\x...


问:
my telegram bot keeps sending messages endlessly
I Started programming a telegram bot and I've got a problem. when I send /start command it sends me a welcome message (as i programmed it) but it doesn't sends it once! it keeps sending it endlessly like loop!
this is the source:</p>
```<code><?php
    define('API_KEY','<token>');

    function makereq($method,$datas=[])
    {
        $url = "https://api.telegram.org/bot".API_KEY."/".$method;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($datas));
        $res = curl_exec($ch);
        if(curl_error($ch)){
            var_dump(curl_error($ch));
        }else{
            return json_decode($res);
        }
    }

    $website = "https://api.telegram.org/bot".API_KEY;

    $update = json_decode(file_get_contents('php://input'));

    $chat_id = $update->message->chat->id;
    $message_id = $update->message->message_id;
    $from_id = $update->message->from->id;
    $name = $update->message->from->first_name;
    $username = $update->message->from->username;
    $textmessage = isset($update->message->text)?$update->message->text:'';
    $reply = $update->message->reply_to_message->forward_from->id;
    $stickerid = $update->message->reply_to_message->sticker->file_id;
    $messageEntity = $update->messageentity->type;

    function SendMessage($ChatId, $TextMsg)
    {
     makereq('sendMessage',[
    'chat_id'=>$ChatId,
    'text'=>$TextMsg,
    'parse_mode'=>"MarkDown"]
     );
    }
    if($textmessage == '/start')
    {
      SendMessage($chat_id,'<welcome message>');
    }

?>
</code>```

答:
As Yoily L said, you gotta return 200 before telegram thinks the request has failed.

You may use fastcgi_finish_request() to flush response data to the client.
http://php.net/manual/en/function.fastcgi-finish-request.php

```<code>http_response_code(200);
fastcgi_finish_request();

// continue execution, send messages and whatever
</code>```

Also, notice what tuxrampage commented in the docs:

The script will still occupy a FPM process after
  fastcgi_finish_request(). So using it excessively for long running
  tasks may occupy all your FPM threads up to pm.max_children. This will
  lead to gateway errors on the webserver.

Another important thing is session handling. Sessions are locked as
  long as they're active (see the documentation for
  session_write_close()). This means subsequent requests will block
  until the session is closed.

You should therefore call session_write_close() as soon as possible
  (even before fastcgi_finish_request()) to allow subsequent requests
  and a good user experience.

This also applies for all other locking techniques as flock or
  database locks for example. As long as a lock is active subsequent
  requests might bock.

You'll probably want to check

```<code>if (is_callable('fastcgi_finish_request')) {
    ...
}
</code>```

More info in related question: continue processing php after sending http response

ContentLicense: CC BY-SA 4.0

Body:
I Started programming a telegram bot and I've got a problem. when I send /start command it sends me a welcome message (as i programmed it) but it doesn't sends it once! it keeps sending it endlessly like loop!
this is the source:

<?php
    define('API_KEY','<token>');

    function makereq($method,$datas=[])
    {
        $url = "https://api.telegram.org/bot".API_KEY."/".$method;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($datas));
        $res = curl_exec($ch);
        if(curl_error($ch)){
            var_dump(curl_error($ch));
        }else{
            return json_decode($res);
        }
    }

    $website = "https://api.telegram.org/bot".API_KEY;

    $update = json_decode(file_get_contents('php://input'));

    $chat_id = $update->message->chat->id;
    $message_id = $update->message->message_id;
    $from_id = $update->message->from->id;
    $name = $update->message->from->first_name;
    $username = $update->message->from->username;
    $textmessage = isset($update->message->text)?$update->message->text:'';
    $reply = $update->message->reply_to_message->forward_from->id;
    $stickerid = $update->message->reply_to_message->sticker->file_id;
    $messageEntity = $update->messageentity->type;

    function SendMessage($ChatId, $TextMsg)
    {
     makereq('sendMessage',[
    'chat_id'=>$ChatId,
    'text'=>$TextMsg,
    'parse_mode'=>"MarkDown"]
     );
    }
    if($textmessage == '/start')
    {
      SendMessage($chat_id,'<welcome message>');
    }

?>

Body:
As Yoily L said, you gotta return 200 before telegram thinks the request has failed.

You may use fastcgi_finish_request() to flush response data to the client.
http://php.net/manual/en/function.fastcgi-finish-request.php

http_response_code(200);
fastcgi_finish_request();

// continue execution, send messages and whatever

Also, notice what tuxrampage commented in the docs:

The script will still occupy a FPM process after
  fastcgi_finish_request(). So using it excessively for long running
  tasks may occupy all your FPM threads up to pm.max_children. This will
  lead to gateway errors on the webserver.

Another important thing is session handling. Sessions are locked as
  long as they're active (see the documentation for
  session_write_close()). This means subsequent requests will block
  until the session is closed.

You should therefore call session_write_close() as soon as possible
  (even before fastcgi_finish_request()) to allow subsequent requests
  and a good user experience.

This also applies for all other locking techniques as flock or
  database locks for example. As long as a lock is active subsequent
  requests might bock.

You'll probably want to check

if (is_callable('fastcgi_finish_request')) {
    ...
}

More info in related question: continue processing php after sending http response


问:
iOS 11 and up crashing with -[UIView setDrawsWithVibrantLightMode:]: unrecognized selector sent to instance
I've noticed a significant spike in app crashes on iOS 11 and up with this message. This appears to be an internal API that UIKit is calling, the stack trace reveals that it's something inside UITableViewCell:

```<code>    Application Specific Information:
    *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setDrawsWithVibrantLightMode:]: unrecognized selector sent to instance 0x15defa6d0'

    Last Exception Backtrace:
    0   CoreFoundation                       0x0000000181691d04 __exceptionPreprocess + 124
    1   libobjc.A.dylib                      0x00000001808e0528 objc_exception_throw + 52
    2   CoreFoundation                       0x000000018169f1c8 -[NSObject(NSObject) doesNotRecognizeSelector:] + 136
    3   UIKit                                0x000000018ae8711c -[UIResponder doesNotRecognizeSelector:] + 292
    4   CoreFoundation                       0x00000001816976b0 ___forwarding___ + 1376
    5   CoreFoundation                       0x000000018157d01c _CF_forwarding_prep_0 + 88
    6   UIKit                                0x000000018b022d58 -[UITableViewCell _setSeparatorDrawsInVibrantLightMode:] + 216
    7   UIKit                                0x000000018abf5ef0 -[UITableViewCell setSeparatorColor:] + 340
    8   UIKit                                0x000000018abf451c __53-[UITableView _configureCellForDisplay:forIndexPath:]_block_invoke + 1228
    9   UIKit                                0x000000018aad6e34 +[UIView(Animation) performWithoutAnimation:] + 100
    10  UIKit                                0x000000018abf3f64 -[UITableView _configureCellForDisplay:forIndexPath:] + 268
    11  UIKit                                0x000000018ae03a00 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 844
    12  UIKit                                0x000000018ae03eac -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 76
    13  UIKit                                0x000000018ade39f0 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2136
    14  UIKit                                0x000000018ab99508 -[UITableView layoutSubviews] + 136
</code>```

I've been unable to reproduce this but it's crashing consistently on a number of user devices and there's no common thread between device or OS version except that it's only occurring on iOS 11 and up.

答:
Eventually figured out that this is a bug in UIKit when the Darken Colors setting is enabled under Accessibility settings:

Settings -> General -> Accessibility -> Increase Contrast -> Darken Colors

If you're experiencing this crash try toggling that setting on/off to reproduce it.

For now we've suppressed this by simply implementing this method as a Void function in an extension:

```<code>@available(iOS 11.0, *)
extension UITableViewCell {
  func _setSeparatorDrawsInVibrantLightMode(_ value: Bool) {

  }
}
</code>```

So UIKit can call it but it just doesn't do anything (and doesn't crash the app).

Body:
I've noticed a significant spike in app crashes on iOS 11 and up with this message. This appears to be an internal API that UIKit is calling, the stack trace reveals that it's something inside UITableViewCell:

    Application Specific Information:
    *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setDrawsWithVibrantLightMode:]: unrecognized selector sent to instance 0x15defa6d0'

    Last Exception Backtrace:
    0   CoreFoundation                       0x0000000181691d04 __exceptionPreprocess + 124
    1   libobjc.A.dylib                      0x00000001808e0528 objc_exception_throw + 52
    2   CoreFoundation                       0x000000018169f1c8 -[NSObject(NSObject) doesNotRecognizeSelector:] + 136
    3   UIKit                                0x000000018ae8711c -[UIResponder doesNotRecognizeSelector:] + 292
    4   CoreFoundation                       0x00000001816976b0 ___forwarding___ + 1376
    5   CoreFoundation                       0x000000018157d01c _CF_forwarding_prep_0 + 88
    6   UIKit                                0x000000018b022d58 -[UITableViewCell _setSeparatorDrawsInVibrantLightMode:] + 216
    7   UIKit                                0x000000018abf5ef0 -[UITableViewCell setSeparatorColor:] + 340
    8   UIKit                                0x000000018abf451c __53-[UITableView _configureCellForDisplay:forIndexPath:]_block_invoke + 1228
    9   UIKit                                0x000000018aad6e34 +[UIView(Animation) performWithoutAnimation:] + 100
    10  UIKit                                0x000000018abf3f64 -[UITableView _configureCellForDisplay:forIndexPath:] + 268
    11  UIKit                                0x000000018ae03a00 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 844
    12  UIKit                                0x000000018ae03eac -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 76
    13  UIKit                                0x000000018ade39f0 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2136
    14  UIKit                                0x000000018ab99508 -[UITableView layoutSubviews] + 136

I've been unable to reproduce this but it's crashing consistently on a number of user devices and there's no common thread between device or OS version except that it's only occurring on iOS 11 and up.

Body:
Eventually figured out that this is a bug in UIKit when the Darken Colors setting is enabled under Accessibility settings:

Settings -> General -> Accessibility -> Increase Contrast -> Darken Colors

If you're experiencing this crash try toggling that setting on/off to reproduce it.

For now we've suppressed this by simply implementing this method as a Void function in an extension:

@available(iOS 11.0, *)
extension UITableViewCell {
  func _setSeparatorDrawsInVibrantLightMode(_ value: Bool) {

  }
}

So UIKit can call it but it just doesn't do anything (and doesn't crash the app).


问:
How do you convert a relational dataset with 3 columns to a 2d sparse matrix?
I'm using spark 2.0.0 with scala 2.11.

I have a dataframe that has 3 columns:

```<code>object_id  category_id   count
1          653           5
1          78            1
1          28            6
2          63            2
3          59            7
</code>```

How do I convert it to this format?

```<code>1 653:5 78:1 28:6
2 63:2
3 59:7
</code>```

Cheers

答:
Don't want to leave this guy unanswered - turns out the pivot function after a groupBy does exactly what I want.

dataset
  .groupBy("object_id")
  .pivot("category_id", listOfAllCategoryIds)

Body:
I'm using spark 2.0.0 with scala 2.11.

I have a dataframe that has 3 columns:

object_id  category_id   count
1          653           5
1          78            1
1          28            6
2          63            2
3          59            7

How do I convert it to this format?

1 653:5 78:1 28:6
2 63:2
3 59:7

Cheers


问:
Cannot pass URL from JavaScript to PHP in Laravel
I'm trying to get three values from a front-end form in JavaScript and then passing those values to the Laravel controller.

I can get two values (Key and Id) but I cannot get the third value because it is a URL. If I comment the URL variable then I'm getting the rest of the two values (Key and Id) but if I'm passing the URL along other two values then I'm not getting anything in my controller.

I have tried these two JavaScript methods encodeURIComponent() and encodeURI() to encode the https URL given but still no luck.

This is my code in JavaScript:

```<code>let get_url = $("#get-url").val();
let get_key = $("#get-key").val();
let get_id = $("#get-area").data('getId');
toastr.remove();
if (get_key) {
    var req = new Image();
    req.src = api_url + 'senddata/' + get_id + '/' + get_key + '/' + get_url;
    console.log(req.src);
       toastr.success(MEASURE.UTILITIES.translate("success_request_successfully_sent"));
        $("#btn-send-data-request").hide();
        $("#block_get_url").hide();
        $("#block_get_key").hide();
        $("#csv_get_request_message").show();
    } else {
        toastr.error(MEASURE.UTILITIES.translate("error_enter_valid_data"));
    }
</code>```

答:
Your get_url contains a url, which i believe has https:// or http://

This is a problem when you are adding to the API URL you are constructing as adding more / changes the ROUTE.

For example your API URL expects req.src = api_url + 'senddata/' + get_id + '/' + get_key + '/' + get_url;
 which is something like http://www.laravel.com/api/senddata/123/123/urlhere  but you are making is something like http://www.laravel.com/api/senddata/123/123/http://urlhere which means you are altering the ROUTE.

To solve that you can URL Encode the URL before passing it.

Change your code to this should work : let get_url = encodeURIComponent($("#get-url").val());

Reference: https://www.w3schools.com/jsref/jsref_encodeuricomponent.asp

Body:
I'm trying to get three values from a front-end form in JavaScript and then passing those values to the Laravel controller.

I can get two values (Key and Id) but I cannot get the third value because it is a URL. If I comment the URL variable then I'm getting the rest of the two values (Key and Id) but if I'm passing the URL along other two values then I'm not getting anything in my controller.

I have tried these two JavaScript methods encodeURIComponent() and encodeURI() to encode the https URL given but still no luck.

This is my code in JavaScript:

let get_url = $("#get-url").val();
let get_key = $("#get-key").val();
let get_id = $("#get-area").data('getId');
toastr.remove();
if (get_key) {
    var req = new Image();
    req.src = api_url + 'senddata/' + get_id + '/' + get_key + '/' + get_url;
    console.log(req.src);
       toastr.success(MEASURE.UTILITIES.translate("success_request_successfully_sent"));
        $("#btn-send-data-request").hide();
        $("#block_get_url").hide();
        $("#block_get_key").hide();
        $("#csv_get_request_message").show();
    } else {
        toastr.error(MEASURE.UTILITIES.translate("error_enter_valid_data"));
    }


问:
Scope associated element with join table
I'm trying to scope the main group of my user. This group is noted with a cat: which is 2.

So I thought of doing this with a scope like

```<code>class User < ApplicationRecord
  has_many :users_group, dependent: :destroy
  has_many :groups, through: :users_group

  scope :my_group, -> { self.joins(:groups).where('groups.cat = 2').limit(1) }
end
</code>```

But the command below is not working :

current_user.my_group

Can you lead me on the good way to achieve it ?

答:
current_user doesn't return an ActiveRecord relation, it just returns the user so you can't chain it together with a scope (I'm assuming the error message you're getting is undefined method 'my_group' for #<User>?). Add the scope to your Group class and use it through your groups has_many relationship e.g.
current_user.groups.my_group

Body:
I'm trying to scope the main group of my user. This group is noted with a cat: which is 2.

So I thought of doing this with a scope like

class User < ApplicationRecord
  has_many :users_group, dependent: :destroy
  has_many :groups, through: :users_group

  scope :my_group, -> { self.joins(:groups).where('groups.cat = 2').limit(1) }
end

But the command below is not working :

current_user.my_group

Can you lead me on the good way to achieve it ?


问:
Angular Modal issue
I am trying to implement a modal from
https://plnkr.co/edit/VSOzZ8AJz61az9TANGsp?p=preview

However, I am trying to put the modal into a component instead of  directive as shown in the plunker above. I rant into one error ($.confirm)

```<code>import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    closeResult: string;

    name: string;
    constructor(public modal: Modal) {
        this.name = 'Angular version'
    }

    @Output('confirm-click') click: any = new EventEmitter();

    @HostListener('click', ['$event']) clicked(e) {
        $.confirm({
            buttons: {
                confirm: () => this.click.emit(),
                cancel: () => { }
            }
        });
    }

}
</code>```

error:  Cannot find name '$'.

************************************UPDATE**************************************

I just ended up using bootstrap Modal , which works and easy to implement
modal.html

```<code><div>

    <span class="fa fa-trash-o"  data-toggle="modal" data-target="#myModal">

    </span>
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">Confirm</h4>
                </div>
                <div class="modal-body">
                    <p>Delete this record?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" (click)="onOk()">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                </div>
            </div>
            <div>

            </div>
        </div>
    </div>
</div>
</code>```

Modal.ts

```<code>     import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

declare const jQuery: {
    confirm: Function
};

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    @Output() open: EventEmitter<any> = new EventEmitter();

    onOk() {
        console.log("OK");
        this.open.emit('yes');
    }
    onDelete() {

        console.log("Cancel");
    }

}
</code>```

答:
try to add this

```<code>import * as $ from 'jquery';
</code>```

or

```<code>declare const jQuery: {
  confirm: Function
};
</code>```

and in your code

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

Title: Angular Modal issue

Body:
I am trying to implement a modal from
https://plnkr.co/edit/VSOzZ8AJz61az9TANGsp?p=preview

However, I am trying to put the modal into a component instead of  directive as shown in the plunker above. I rant into one error ($.confirm)

import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    closeResult: string;

    name: string;
    constructor(public modal: Modal) {
        this.name = 'Angular version'
    }

    @Output('confirm-click') click: any = new EventEmitter();

    @HostListener('click', ['$event']) clicked(e) {
        $.confirm({
            buttons: {
                confirm: () => this.click.emit(),
                cancel: () => { }
            }
        });
    }

}

error:  Cannot find name '$'.

************************************UPDATE**************************************

I just ended up using bootstrap Modal , which works and easy to implement
modal.html

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

Confirm

Delete this record?

                    <button type="button" class="btn btn-primary" data-dismiss="modal" (click)="onOk()">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

Modal.ts

     import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

declare const jQuery: {
    confirm: Function
};

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    @Output() open: EventEmitter<any> = new EventEmitter();

    onOk() {
        console.log("OK");
        this.open.emit('yes');
    }
    onDelete() {

        console.log("Cancel");
    }

}

Body:
try to add this

import * as $ from 'jquery';

or

declare const jQuery: {
  confirm: Function
};

and in your code

jQuery.confirm();


问:
Google Cloud Firestore Sync Devices Data in Local Network (no internet temporally)
Google has launched Google Cloud Firestore. Just as they says...
"Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. Like Firebase Realtime Database, it keeps your data in sync across client apps through realtime listeners and offers offline support for mobile and web".

The question is...

In the application I am thinking about, needs that everyone to have data perfectly sync between devices (web and mobile). Ok, Firestore looks perfect for that.
* But what if my application also needs to sync between devices in a local network. Let's suppose if the internet connection is gone (whatever reasons...)*.
Does anyone could give me a direction how could it be made using Google Cloud Firestore (I don't mean the code). I use node for web application and Android for mobile.

答:
Cloud Firestore as well as Firebase Reatime Database supports offline data persistence. This feature caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline. So, if you are using:

```<code>FirebaseDatabase.getInstance().setPersistenceEnabled(true);
</code>```

It means that Firestore will create a local copy of your database on your device, which in turn means that you'll be able to query your the database even if you are offline. So every change that is made while you are offline, will be updated on Firebase servers once you are back online. Unfortunately this local copy of your database cannot exist elsewhere than on your device. It cannot be hosted in a local network. Also all CRUD operation can be done only on the database which are hosted on users device.

Another thing to note, is that once the Internet connectivity is reestablished, you'll receive the appropriate current server state. The Firebase client synchronizes that data with the Firebase servers and with other clients that are using the same database. So, as a conclusion, in order to keep all your devices from a local network synced, you need to have internet access.

Body:
Cloud Firestore as well as Firebase Reatime Database supports offline data persistence. This feature caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline. So, if you are using:

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

It means that Firestore will create a local copy of your database on your device, which in turn means that you'll be able to query your the database even if you are offline. So every change that is made while you are offline, will be updated on Firebase servers once you are back online. Unfortunately this local copy of your database cannot exist elsewhere than on your device. It cannot be hosted in a local network. Also all CRUD operation can be done only on the database which are hosted on users device.

Another thing to note, is that once the Internet connectivity is reestablished, you'll receive the appropriate current server state. The Firebase client synchronizes that data with the Firebase servers and with other clients that are using the same database. So, as a conclusion, in order to keep all your devices from a local network synced, you need to have internet access.


问:
How to implement this foldl0 function without helper method?
I have following code:

```<code>function foldr0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return func(list[0], foldr0(list.slice(1), func));
  }
}

function foldl0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return ?
  }
}
</code>```

I know it is easy to implement a recursive foldl0 with an iterative logic by defining a helper method iter(list, func, part_result) and store the result as an argument. But how to implement foldl0 without helper method just like foldr0's implementation?

NOTICE: I wrote this problem with Javascript for convenience. Please solve it with car and cdr, thanks.

答:
Just use exactly the same approach as in foldr0 but split the array to the other side:

```<code>function foldl0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return func(list[list.length-1], foldr0(list.slice(0, -1), func));
//                   ^^^^^^^^^^^^^                     ^^^^^
//                       last                       without last
  }
}
</code>```

Of course this would be much easier if you had foldl/foldr functions with a parameter for the initial accumulator value.

Body:
I have following code:

function foldr0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return func(list[0], foldr0(list.slice(1), func));
  }
}

function foldl0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return ?
  }
}

I know it is easy to implement a recursive foldl0 with an iterative logic by defining a helper method iter(list, func, part_result) and store the result as an argument. But how to implement foldl0 without helper method just like foldr0's implementation?

NOTICE: I wrote this problem with Javascript for convenience. Please solve it with car and cdr, thanks.

Body:
Just use exactly the same approach as in foldr0 but split the array to the other side:

function foldl0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return func(list[list.length-1], foldr0(list.slice(0, -1), func));
//                   ^^^^^^^^^^^^^                     ^^^^^
//                       last                       without last
  }
}

Of course this would be much easier if you had foldl/foldr functions with a parameter for the initial accumulator value.


问:
One Hot Encoding using numpy
If the input is zero I want to make an array which looks like this:

```<code>[1,0,0,0,0,0,0,0,0,0]
</code>```

and if the input is 5:

```<code>[0,0,0,0,0,1,0,0,0,0]
</code>```

For the above I wrote:

```<code>np.put(np.zeros(10),5,1)
</code>```

but it did not work.

Is there any way in which, this can be implemented in one line?

答:
You could use List comprehension:

```<code>[0 if i !=5 else 1 for i in range(10)]
</code>```

turns to

```<code>[0,0,0,0,0,1,0,0,0,0]
</code>```

Title: One Hot Encoding using numpy

Body:
If the input is zero I want to make an array which looks like this:

[1,0,0,0,0,0,0,0,0,0]

and if the input is 5:

[0,0,0,0,0,1,0,0,0,0]

For the above I wrote:

np.put(np.zeros(10),5,1)

but it did not work.

Is there any way in which, this can be implemented in one line?

Body:
You could use List comprehension:

[0 if i !=5 else 1 for i in range(10)]

turns to

[0,0,0,0,0,1,0,0,0,0]


问:
Hide folder from search in Sublime Text 3
I want to exclude a folder from search in Sublime Text 3 but not in sidebar.

folder_exclude_patterns: hides folder from Search and Goto Anything but also in sidebar

binary_file_patterns: hides from Goto Anything but not from Search.

Is there any trick to do this?

```<code>"folder_exclude_patterns":
[
    "node_modules"
],

"binary_file_patterns":
[
    "node_modules/"
],
</code>```

答:
This works for me if you don't want to remove them from the side bar, but remove it from the search index

```<code>{
  "folders":
  [
    {
      "path": "my/path",
      "folder_exclude_patterns":[],
      "binary_file_patterns":["node_modules/*"],
    }
  ]
}
</code>```

Notice I am using the /*

Body:
I want to exclude a folder from search in Sublime Text 3 but not in sidebar.

folder_exclude_patterns: hides folder from Search and Goto Anything but also in sidebar

binary_file_patterns: hides from Goto Anything but not from Search.

Is there any trick to do this?

"folder_exclude_patterns":
[
    "node_modules"
],

"binary_file_patterns":
[
    "node_modules/"
],

Body:
This works for me if you don't want to remove them from the side bar, but remove it from the search index

{
  "folders":
  [
    {
      "path": "my/path",
      "folder_exclude_patterns":[],
      "binary_file_patterns":["node_modules/*"],
    }
  ]
}

Notice I am using the /*


问:
Build Nested Object in Javascript
I trying to build a nested object, I'll try to make myself clear.

I have this json structure:

```<code> {
      "origin.geo.country": "USA",
      "origin.geo.state": "NY",
      "origin.geo.zip": 4444,
      "user.name": "Michael",
      "user.surname": "Jordan"
}
</code>```

And I need a function that outputs something like this:

```<code>{
     origin: {
         geo: {
             country: "USA",
             state: "NY",
             zip: 4444
         }
     },
     user: {
         name: "Michael",
         surname: "Jordan"
     }
 }
</code>```

I know i have to use recursion to achieve this, but I'm not able to code it.
Can you guys help me with this?

Thanks.

答:
You could reach the desired solution using e.g. Array#reduce.

const o = {
  "origin.geo.country": "USA",
  "origin.geo.state": "NY",
  "origin.geo.zip": 4444,
  "user.name": "Michael",
  "user.surname": "Jordan",
};

const r = Object.keys(o).reduce((s, a) => {
  const t = a.split('.');
  const k = t[0];
  const v = t[t.length - 1];
  k in s ? s[k][v] = o[a] : s[k] = Object.assign({}, { [v]: o[a] });
  return s;
}, {});

console.log(r);```

Title: Build Nested Object in Javascript

Body:
I trying to build a nested object, I'll try to make myself clear.

I have this json structure:

 {
      "origin.geo.country": "USA",
      "origin.geo.state": "NY",
      "origin.geo.zip": 4444,
      "user.name": "Michael",
      "user.surname": "Jordan"
}

And I need a function that outputs something like this:

{
     origin: {
         geo: {
             country: "USA",
             state: "NY",
             zip: 4444
         }
     },
     user: {
         name: "Michael",
         surname: "Jordan"
     }
 }

I know i have to use recursion to achieve this, but I'm not able to code it.
Can you guys help me with this?

Thanks.


问:
django REST swagger function based api does not have input PARAMETERS
I am trying to do Django REST function based API with swagger following these instructions.

https://github.com/m-haziq/django-rest-swagger-docs

However, I am unable to get any parameters shown in the function. This is the screenshot of swagger NOT displaying any parameters.
https://imgur.com/a/fDITT https://imgur.com/a/n5CDU

UPDATE:This is how I want to achieve with the parameters https://imgur.com/a/cLYNF

Here is my API code, I want to have "name" parameters shown in swagger
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

```<code>@api_view(['POST'])
def test_post(request):
    # ----- YAML below for Swagger -----
    """
    description: This API deletes/uninstalls a device.
    parameters:
      - name: name
        type: string
        required: true
        location: form
    """
    name = request.POST.get('name')

    return Response("Data Saved!", status=status.HTTP_201_CREATED)
</code>```

This is the difference on my pip freeze library with the working example of django-rest-swagger-docs https://gist.github.com/anonymous/c5c328b9e4a6ff3f86676fe930440dd2

What is the problem, you can view the whole source code in gitlab. Thanks.

答:
I found this in readme

```<code>*Input parameters for function based views do not appear:* You might be using
    incompatible versions, try using `djangorestframework==3.5.3` and `django-rest-swagger==2.1.1`.
</code>```

I updated to djangorestframework==3.5.3 and it works

Body:
I am trying to do Django REST function based API with swagger following these instructions.

https://github.com/m-haziq/django-rest-swagger-docs

However, I am unable to get any parameters shown in the function. This is the screenshot of swagger NOT displaying any parameters.
https://imgur.com/a/fDITT https://imgur.com/a/n5CDU

UPDATE:This is how I want to achieve with the parameters https://imgur.com/a/cLYNF

Here is my API code, I want to have "name" parameters shown in swagger
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

@api_view(['POST'])
def test_post(request):
    # ----- YAML below for Swagger -----
    """
    description: This API deletes/uninstalls a device.
    parameters:
      - name: name
        type: string
        required: true
        location: form
    """
    name = request.POST.get('name')

    return Response("Data Saved!", status=status.HTTP_201_CREATED)

This is the difference on my pip freeze library with the working example of django-rest-swagger-docs https://gist.github.com/anonymous/c5c328b9e4a6ff3f86676fe930440dd2

What is the problem, you can view the whole source code in gitlab. Thanks.

Body:
I found this in readme

*Input parameters for function based views do not appear:* You might be using
    incompatible versions, try using `djangorestframework==3.5.3` and `django-rest-swagger==2.1.1`.

I updated to djangorestframework==3.5.3 and it works


答:
Your description of the "desired plot" is a bit vague, but if you want to plot a point at every Y value associated with the X value at the beginning of the line, you can do this:

```<code>X = data[:, 0]
Ys = data[:, 1:]
plt.plot(X, Ys, '.', color='black')
</code>```

Title: Matplotlib data in X Y1 Y2 Y3 ... format

Body:
Given the file data.dat, where the first column is the X data, and the rest of the columns are Y1, Y2, data:

# Lines starting with #
# More lines starting with #
@ Lines starting with @
@ More lines starting with @

  0.00000E+00  0.81837E+02  0.81837E+02  0.14153E+03  0.14153E+03  0.17240E+03  0.17240E+03  0.19575E+03  0.19575E+03  0.21944E+03  0.21944E+03  0.25196E+03  0.25196E+03  0.35173E+03  0.35173E+03  0.35441E+03  0.35441E+03  0.37508E+03  0.37508E+03  0.71611E+03  0.71611E+03  0.72908E+03  0.72908E+03  0.87658E+03  0.87658E+03  0.11174E+04  0.11174E+04  0.15014E+04  0.15014E+04  0.15644E+04  0.15644E+04
  0.39856E+00  0.80923E+02  0.82842E+02  0.13984E+03  0.14327E+03  0.17059E+03  0.17417E+03  0.19258E+03  0.19907E+03  0.21823E+03  0.22072E+03  0.25141E+03  0.25250E+03  0.35083E+03  0.35230E+03  0.35441E+03  0.35467E+03  0.37481E+03  0.37543E+03  0.71596E+03  0.71626E+03  0.72906E+03  0.72913E+03  0.87640E+03  0.87676E+03  0.11173E+04  0.11176E+04  0.15011E+04  0.15016E+04  0.15631E+04  0.15657E+04

In the following code,

import os
import numpy as np
import matplotlib.pyplot as plt

path='./'
template = os.path.join(path, '*.dat')

fname = glob.glob(template)
fname = fname[0]

# This is just to skip lines that start with '@' and '#':
gen = (r for r in open(fname) if not r[0] in ('@', '#'))

data = np.genfromtxt(gen)
print 'data = ', data
print np.shape(data)

just as is stated in the last print, data is a 2 dimensional array of shape: (2, 31):

data = [[  0.00000000e+00   8.18370000e+01   8.18370000e+01   1.41530000e+02
    1.41530000e+02   1.72400000e+02   1.72400000e+02   1.95750000e+02
    1.95750000e+02   2.19440000e+02   2.19440000e+02   2.51960000e+02
    2.51960000e+02   3.51730000e+02   3.51730000e+02   3.54410000e+02
    3.54410000e+02   3.75080000e+02   3.75080000e+02   7.16110000e+02
    7.16110000e+02   7.29080000e+02   7.29080000e+02   8.76580000e+02
    8.76580000e+02   1.11740000e+03   1.11740000e+03   1.50140000e+03
    1.50140000e+03   1.56440000e+03   1.56440000e+03]
 [  3.98560000e-01   8.09230000e+01   8.28420000e+01   1.39840000e+02
    1.43270000e+02   1.70590000e+02   1.74170000e+02   1.92580000e+02
    1.99070000e+02   2.18230000e+02   2.20720000e+02   2.51410000e+02
    2.52500000e+02   3.50830000e+02   3.52300000e+02   3.54410000e+02
    3.54670000e+02   3.74810000e+02   3.75430000e+02   7.15960000e+02
    7.16260000e+02   7.29060000e+02   7.29130000e+02   8.76400000e+02
    8.76760000e+02   1.11730000e+03   1.11760000e+03   1.50110000e+03
    1.50160000e+03   1.56310000e+03   1.56570000e+03]]

For X1 = 0.00000000e+00, there are 30 values of Y. This corresponds to the first line of data.dat.

For X2 = 3.98560000e-01, there are other 30 values of Y. This corresponds to the second line of data.dat

I would like to matplotlib the data 2D array, i.e., all the 30 values of Y belonging to X1 = 0.00000000e+00 and all the 30 values of Y belonging to X2 = 3.98560000e-01

Update:

Thanks to @jakevdp answer, the following two statements:

print 'data[0][1:] = ', data[0][1:] # Extracts Ys(X1)
print 'data[0, 1:] = ', data[0, 1:] # "

print the same result:

data[0][1:] =  [   81.837    81.837   141.53    141.53    172.4     172.4     195.75
   195.75    219.44    219.44    251.96    251.96    351.73    351.73
   354.41    354.41    375.08    375.08    716.11    716.11    729.08
   729.08    876.58    876.58   1117.4    1117.4    1501.4    1501.4
  1564.4    1564.4  ]
data[0, 1:] =  [   81.837    81.837   141.53    141.53    172.4     172.4     195.75
   195.75    219.44    219.44    251.96    251.96    351.73    351.73
   354.41    354.41    375.08    375.08    716.11    716.11    729.08
   729.08    876.58    876.58   1117.4    1117.4    1501.4    1501.4
  1564.4    1564.4  ]

The following two statements also print the same result:

print 'data[1][1:] = ', data[1][1:] # Extracts Ys(X2)
print 'data[1, 1:] = ', data[1, 1:] # "

data[1][1:] =  [   80.923    82.842   139.84    143.27    170.59    174.17    192.58
   199.07    218.23    220.72    251.41    252.5     350.83    352.3
   354.41    354.67    374.81    375.43    715.96    716.26    729.06
   729.13    876.4     876.76   1117.3    1117.6    1501.1    1501.6
  1563.1    1565.7  ]
data[1, 1:] =  [   80.923    82.842   139.84    143.27    170.59    174.17    192.58
   199.07    218.23    220.72    251.41    252.5     350.83    352.3
   354.41    354.67    374.81    375.43    715.96    716.26    729.06
   729.13    876.4     876.76   1117.3    1117.6    1501.1    1501.6
  1563.1    1565.7  ]

Now, following the same logic, these two statements would also print the same result:

print 'data[:][0] = ' , data[:][0]
print 'data[:, 0] = ' , data[:, 0]

However, they do not:

data[:][0] =  [    0.       81.837    81.837   141.53    141.53    172.4     172.4
   195.75    195.75    219.44    219.44    251.96    251.96    351.73
   351.73    354.41    354.41    375.08    375.08    716.11    716.11
   729.08    729.08    876.58    876.58   1117.4    1117.4    1501.4
  1501.4    1564.4    1564.4  ]
data[:, 0] =  [ 0.       0.39856]

why this is happening?

Body:
Your description of the "desired plot" is a bit vague, but if you want to plot a point at every Y value associated with the X value at the beginning of the line, you can do this:

X = data[:, 0]
Ys = data[:, 1:]
plt.plot(X, Ys, '.', color='black')


问:
How do I run a modulo conditional using one list on another list in python
I've only been using python for about 2 weeks and need some help. I am trying to use the mod (%) function between two lists of varying sizes.

```<code>n = 23 #user input, starting point for the code
listp = [2, 3, 5, 7, 11, 13]
listr = list(range((n-1)**2, n**2+1, 2))
listb = list(listr)  #I need to remove items from listr but if i do, it
                     #crashes so I decided to copy it to listb in order to manipulate it

for k in listr:
    for i in listp[1:]:
        if k%i == 0:
            if k in listb:
                listb.remove(k)
</code>```

This works but it's slow, I'd like to manipulate listr directly and I can individually:

```<code>listr = [k for k in listr if i%listp[1] !=0]
listr = [k for k in listr if i%listp[2] !=0]
</code>```

Bottom line is that I'd like to use the % function on each k element in listr using every i element in listp and only keep those elements in listr that are !=0; I've tried using numpy and an array but that's not helping either

答:
You can stop from the moment you have found any such value. So replace:

```<code>for k in listr:
    <b>for i in listp[1:]:
        if k%i == 0:</b>
            if k in listb:
                listb.remove(k)</code>```

With:

```<code>for k in listr:
    <b>if any(k%i == 0 for i in listp[1:]):</b>
        listb.remove(k)</code>```

which will already yield some speedup. But list.remove is slow, it works in O(n). So now we can turn this into list comprehension:

```<code>listr = [k for k in listr <b>if not any(k%i == 0 for i in listp[1:])</b>]</code>```

So we add the number to the new listr list, if no such modulo condition holds. A not any(p(x) for x in X) can be rewritten to all(not p(x) for x in X), so we can apply this here:

```<code>listr = [k for k in listr if <b>all(k%i != 0</b> for i in listp[1:])]</code>```

Furthermore we can also save some cycles, by making a list listp1:

```<code><b>listp1 = listp[1:]</b>
listr = [k for k in listr if all(k%i != 0 for i in <b>listp1</b>)]</code>```

since now we only construct a new list once. Finally we can remove the != 0 since the truthiness of an integer is True if and only if the value is not equal to zero:

```<code>listp1 = listp[1:]
listr = [k for k in listr if all(k%i for i in listp1)]</code>```

Note that there are faster approaches than the Sieve of Eratosthenes.

Body:
I've only been using python for about 2 weeks and need some help. I am trying to use the mod (%) function between two lists of varying sizes.

n = 23 #user input, starting point for the code
listp = [2, 3, 5, 7, 11, 13]
listr = list(range((n-1)**2, n**2+1, 2))
listb = list(listr)  #I need to remove items from listr but if i do, it
                     #crashes so I decided to copy it to listb in order to manipulate it

for k in listr:
    for i in listp[1:]:
        if k%i == 0:
            if k in listb:
                listb.remove(k)

This works but it's slow, I'd like to manipulate listr directly and I can individually:

listr = [k for k in listr if i%listp[1] !=0]
listr = [k for k in listr if i%listp[2] !=0]

Bottom line is that I'd like to use the % function on each k element in listr using every i element in listp and only keep those elements in listr that are !=0; I've tried using numpy and an array but that's not helping either

Body:
You can stop from the moment you have found any such value. So replace:

for k in listr:
    for i in listp[1:]:
        if k%i == 0:
            if k in listb:
                listb.remove(k)

With:

for k in listr:
    if any(k%i == 0 for i in listp[1:]):
        listb.remove(k)

which will already yield some speedup. But list.remove is slow, it works in O(n). So now we can turn this into list comprehension:

listr = [k for k in listr if not any(k%i == 0 for i in listp[1:])]

So we add the number to the new listr list, if no such modulo condition holds. A not any(p(x) for x in X) can be rewritten to all(not p(x) for x in X), so we can apply this here:

listr = [k for k in listr if all(k%i != 0 for i in listp[1:])]

Furthermore we can also save some cycles, by making a list listp1:

listp1 = listp[1:]
listr = [k for k in listr if all(k%i != 0 for i in listp1)]

since now we only construct a new list once. Finally we can remove the != 0 since the truthiness of an integer is True if and only if the value is not equal to zero:

listp1 = listp[1:]
listr = [k for k in listr if all(k%i for i in listp1)]

Note that there are faster approaches than the Sieve of Eratosthenes.


问:
Is there a good tool for Eclipse to edit SWT interface graphically (WYSIWYG)?
I develop features for Eclipse, and I often have to make SWT GUIs, for ex. Wizards. Coding SWT in Java isn't difficult to me, but I would like sometimes to see in real time what I get. Actually, I found some extensions for Eclipse to edit SWT graphically, but I want to know some other users' experiences in that area, to decide if is it worth to deal with.</p>

答:
I recommend the WindowBuilder (https://www.eclipse.org/windowbuilder/).

It has a plugin for Eclipse and works with SWT and Swing.


问:
How to take property value from a datalist in angular2
my HTML:

```<code> <input list="tasks" id="selected-task" [(ngModel)]=query (keyup)=filter() name="tasks" class="select-project">
 <datalist id="tasks" #tasksDataList >
    <option *ngFor="let item of taskList"  (click)="select(item)" >{{item.title}}</option>

 </datalist>
</code>```

in my component:

```<code>select(item) {
this.query = item;
this.taskList = [];
}
</code>```

In the datalist I am showing all item.titles, when I choose one, I need to save item.id in a variable, but I can't access the id value from the selected item.
I have tried with:

```<code>select(item:myClass) {
this.query = item.title;
this.id = item.id;
this.taskList = [];
}
</code>```

but it's shows then id is undefined.

So any suggestions when the user selects an item from the datalist how to save the id of the selected item in a variable?

答: After many tries I just ended with the conclusion that angular and datalist (HTML5) are not working well together. If you want just string to be chosen, it is okay, but if u want to work with objects like in my case you can't achieve the desired result. Alternative way is to use select and after that using ul with list items, which are taking the data from the hidden select. So basically there is a little more work for the front-ender but it's the only way :)</p>

Body:
my HTML:

 <input list="tasks" id="selected-task" [(ngModel)]=query (keyup)=filter() name="tasks" class="select-project">
 <datalist id="tasks" #tasksDataList >
    <option *ngFor="let item of taskList"  (click)="select(item)" >{{item.title}}</option>

 </datalist>

in my component:

select(item) {
this.query = item;
this.taskList = [];
}

In the datalist I am showing all item.titles, when I choose one, I need to save item.id in a variable, but I can't access the id value from the selected item.
I have tried with:

select(item:myClass) {
this.query = item.title;
this.id = item.id;
this.taskList = [];
}

but it's shows then id is undefined.

So any suggestions when the user selects an item from the datalist how to save the id of the selected item in a variable?


问:
return selected properties with Joined complete entity
i need to return custom response, so i tried below query

```<code> @Query("SELECT g.name as name,g.id as id, city as city, g.listOfEquipment as listOfEquipment,g.listOfSlot as listOfSlot" +
            " FROM Gym g INNER JOIN g.city as city " +
            "WHERE city.id=:cityId")
    List<Map<String, Object>> listing(@Param("cityId") Integer cityId, Pageable pageable);
</code>```

as you can see my intention is to return city and listOfEquipment and listOfSlot also.

i was thinking this will works but unfortunately its not working
i am getting PSQLException: ERROR: syntax error at or near "."

please help me for the right approach

答:
Try this:

```<code>@Query("SELECT g.name as name,g.id as id, g.city as city, g.listOfEquipment as
listOfEquipment, g.listOfSlot as listOfSlot" +
        " FROM Gym g " +
        "WHERE g.city.id=:cityId")
</code>```

Your city property is inside Gym so, you can directly reach.

Body:
i need to return custom response, so i tried below query

 @Query("SELECT g.name as name,g.id as id, city as city, g.listOfEquipment as listOfEquipment,g.listOfSlot as listOfSlot" +
            " FROM Gym g INNER JOIN g.city as city " +
            "WHERE city.id=:cityId")
    List<Map<String, Object>> listing(@Param("cityId") Integer cityId, Pageable pageable);

as you can see my intention is to return city and listOfEquipment and listOfSlot also.

i was thinking this will works but unfortunately its not working
i am getting PSQLException: ERROR: syntax error at or near "."

please help me for the right approach

Body:
Try this:

@Query("SELECT g.name as name,g.id as id, g.city as city, g.listOfEquipment as
listOfEquipment, g.listOfSlot as listOfSlot" +
        " FROM Gym g " +
        "WHERE g.city.id=:cityId")

Your city property is inside Gym so, you can directly reach.


问:
disable ordering by default for django_tables2 Tables
I use django_tables2 to render my tables. For one table, I only want to see the most recent 5 entries. Therefore, I need to order my queryset before passing it to the table object:

```<code>qset = myObject.objects.order_by('-start_time').all()[:5]
table = MyTableClass(qset, template='path/to/template.html')
</code>```

This yields the following error message:

```<code>AssertionError: Cannot reorder a query once a slice has been taken.
</code>```

I could set orderable=False for every django_tables.Column, but since MyTableClass inherits from another table class, I would like to avoid this.

Thanks in advance

答:
Try changing to this.</p>

```<code>qset = myObject.objects.all().order_by('-start_time')[:5]
</code>```

Body:
I use django_tables2 to render my tables. For one table, I only want to see the most recent 5 entries. Therefore, I need to order my queryset before passing it to the table object:

qset = myObject.objects.order_by('-start_time').all()[:5]
table = MyTableClass(qset, template='path/to/template.html')

This yields the following error message:

AssertionError: Cannot reorder a query once a slice has been taken.

I could set orderable=False for every django_tables.Column, but since MyTableClass inherits from another table class, I would like to avoid this.

Thanks in advance

Body:
Try changing to this.

qset = myObject.objects.all().order_by('-start_time')[:5]


问:
Toggle div tag on button click
I have many buttons with id b1, b2 ... and each has a div tag after it with id q1, q2...
I want to toggle the div tag when the corresponding button is clicked. Example: When b1 is clicked q1 should toggle.
It is given here. http://upscfever.com/upsc-fever/en/topper/en-toppers.html

$(document).ready(function(){
  $(".info").hide();
  $("#b1").click(function(){
    $("#q1").toggle();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" class="btn btn-primary btn-block"></button>

<div id="q1" class="info"></div></code>```

But as i might have 100 of buttons, how can i do the same thing without adding click on each button?

答:
You could change your selector from $("#b1") to something like $(".btn"), and then use the id to determine which q you want to open, like this:

```<code>$(".button").click(function(){
  if(this.id){
    $("#q"+this.id.substring(1)).toggle();
  }
});
</code>```

This way, it doesn't matter how you arrange your HTML, as long as the ids match

$(document).ready(function(){
  $(".info").hide();
  $(".btn").click(function(){
    if(this.id){
      $("#q"+this.id.substring(1)).toggle();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" class="btn btn-primary btn-block">b1</button>
<button id="b2" type="button" class="btn btn-primary btn-block">b2</button>

<div id="q1" class="info">q1</div>
<div id="q2" class="info">q2</div></code>```

Here you have it on JSFiddle: https://jsfiddle.net/py8q340p/

Title: Toggle div tag on button click

Body:
I have many buttons with id b1, b2 ... and each has a div tag after it with id q1, q2...
I want to toggle the div tag when the corresponding button is clicked. Example: When b1 is clicked q1 should toggle.
It is given here. http://upscfever.com/upsc-fever/en/topper/en-toppers.html

$(document).ready(function(){
  $(".info").hide();
  $("#b1").click(function(){
    $("#q1").toggle();
  });
});

<button id="b1" type="button" class="btn btn-primary btn-block"></button>

But as i might have 100 of buttons, how can i do the same thing without adding click on each button?

Body:
You could change your selector from $("#b1") to something like $(".btn"), and then use the id to determine which q you want to open, like this:

$(".button").click(function(){
  if(this.id){
    $("#q"+this.id.substring(1)).toggle();
  }
});

This way, it doesn't matter how you arrange your HTML, as long as the ids match

$(document).ready(function(){
  $(".info").hide();
  $(".btn").click(function(){
    if(this.id){
      $("#q"+this.id.substring(1)).toggle();
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" class="btn btn-primary btn-block">b1</button>
<button id="b2" type="button" class="btn btn-primary btn-block">b2</button>

<div id="q1" class="info">q1</div>
<div id="q2" class="info">q2</div>

Here you have it on JSFiddle: https://jsfiddle.net/py8q340p/


问:
Changing x-axis labels to hours instead of the sample number
I currently have a dataset of 70,000 samples (sampled at 1Hz), and I am graphing it using MatPlotLib.

I am wondering how to change the x-axis labels to be in hours, instead of sample #.

The code that I am using today is as follows:

```<code>test = pd.read_csv("test.txt", sep='\t')
test.columns = ['TS', 'ppb', 'ppm']
test.head()

# The first couple minutes were with an empty container
# Then the apple was inserted into the container.
fig5 = plt.figure()
ax1 = fig5.add_subplot(111)
ax1.scatter(test.index, test['ppm'])
ax1.set_ylabel('(ppm)', color='b')
ax1.set_xlabel('Sampling Time', color='k')
ax2 = ax1.twinx()
ax2.scatter(test.index, test['ppb'], color = 'c')
ax2.set_ylabel('(ppb)', color='c')

plt.show
</code>```

My data looks as follows:

答:
If the data is sampled at 1Hz, that means that every 3600 samples is one hour. So create a new column like:</p>

```<code>test['hours'] = (test.index - test.index[0])/3600.0
</code>```

Body:
I currently have a dataset of 70,000 samples (sampled at 1Hz), and I am graphing it using MatPlotLib.

I am wondering how to change the x-axis labels to be in hours, instead of sample #.

The code that I am using today is as follows:

test = pd.read_csv("test.txt", sep='\t')
test.columns = ['TS', 'ppb', 'ppm']
test.head()

# The first couple minutes were with an empty container
# Then the apple was inserted into the container.
fig5 = plt.figure()
ax1 = fig5.add_subplot(111)
ax1.scatter(test.index, test['ppm'])
ax1.set_ylabel('(ppm)', color='b')
ax1.set_xlabel('Sampling Time', color='k')
ax2 = ax1.twinx()
ax2.scatter(test.index, test['ppb'], color = 'c')
ax2.set_ylabel('(ppb)', color='c')

plt.show

My data looks as follows:

Body:
If the data is sampled at 1Hz, that means that every 3600 samples is one hour. So create a new column like:

test['hours'] = (test.index - test.index[0])/3600.0


问:
C++ Using Method on Vector (If is word)
So I have a couple methods defined, one checks if the next is a word, one checks if there is a next word.

I take inputs for the text files, add the files content to a vector, then use the for loop

I can make it work by simply doing a for loop through the vector:

```<code> for (int x = 0; x != v2.size(); ++x) {
</code>```

But I want to use my two methods

```<code>bool ReadWords::isNextWord()
</code>```

and

```<code>string ReadWords::getNextWord()
{
 //take the input of the file until end of list is reached and return it

}
</code>```

So how would I do something like

```<code>vector<string> bigTextFile;
vector<string> vct;

while(vct.isNextWord) {
      vct.getNextWord

      if(vct.getNextWord == bigTextFile[i] {
         counter++
     }
}
</code>```

Let me know if you need any more of the code

答:
What about this:

```<code>vector<string> bigTextFile;
vector<string> vct;

while(ReadWords::isNextWord(vct))
{
      string nextWord = ReadWords::getNextWord(vct);

      if(nextWord  == bigTextFile[i])
      {
         counter++;
      }
}
</code>```

You could make your functions take in a vector as a parameter then do the work on the vector inside each function. I'm not 100% sure what your implementation is since its not the complete code.

Title: C++ Using Method on Vector (If is word)

Body:
So I have a couple methods defined, one checks if the next is a word, one checks if there is a next word.

I take inputs for the text files, add the files content to a vector, then use the for loop

I can make it work by simply doing a for loop through the vector:

 for (int x = 0; x != v2.size(); ++x) {

But I want to use my two methods

bool ReadWords::isNextWord()

and

string ReadWords::getNextWord()
{
 //take the input of the file until end of list is reached and return it

}

So how would I do something like

vector<string> bigTextFile;
vector<string> vct;

while(vct.isNextWord) {
      vct.getNextWord

      if(vct.getNextWord == bigTextFile[i] {
         counter++
     }
}

Let me know if you need any more of the code

Body:
What about this:

vector<string> bigTextFile;
vector<string> vct;

while(ReadWords::isNextWord(vct))
{
      string nextWord = ReadWords::getNextWord(vct);

      if(nextWord  == bigTextFile[i])
      {
         counter++;
      }
}

You could make your functions take in a vector as a parameter then do the work on the vector inside each function. I'm not 100% sure what your implementation is since its not the complete code.


问:
Create Autowireable @Beans from autoconfiguration
Related:

Spring Boot create a list of managed prototype beans from database configuration

How do I create beans programmatically in Spring Boot?

How to programatically add an @Bean definition to Spring context?

This question is pretty much the same as this, but the answer using BeanFactoryAware doesn't solve my problem as the created @Beans are not @Autowireable.

Requirements:

configure number of beans via spring configuration;

pick this configuration up via @ConfigurationProperties;

create & inject @Beans based on said config from an autoconfiguration module;

be able to @Autowire created beans in application.

Example:
Make it possible to declare number of caffeine-based Cache @Beans via spring config. Following is implementation based on the accepted answer from the similar question:

First, the boot autoconfiguration module:

```<code>@Component
@ConfigurationProperties
@Data
public class Props {

    private LocalCacheConf cache = new LocalCacheConf();

    @Data
    public static class LocalCacheConf {

        /**
        * List of caches to create, with accompanying configuration.
        */
        private List<CacheDef> caches = new ArrayList<>();

        @Data
        public static class CacheDef {

            private String name;
            private CaffeineCacheConf properties;
        }

        @Data
        public static class CaffeineCacheConf {

            private long maximumSize = -1;
        }
    }
}

@Configuration
@Slf4j
public class LocalCacheConfig implements BeanFactoryAware {

    @Autowired private Props props;
    @Setter private BeanFactory beanFactory;
    private CaffeineCacheManager localCacheManager;

    @PostConstruct
    public void configure() {
        setCacheManager();
        createCaches( props.getCache() );
    }

    private void createCaches( LocalCacheConf locCacheConf ) {
        ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;

        for ( CacheDef cacheProps : locCacheConf.getCaches() ) {
            Cache cache = createAndConfigureCache(
                    cacheProps.getName(),
                    cacheProps.getProperties()
            );
            configurableBeanFactory.registerSingleton( cacheProps.getName(), cache );
        }
    }

    private Cache createAndConfigureCache( String name, CaffeineCacheConf props ) {
        Caffeine<Object, Object> c = Caffeine.newBuilder().recordStats();

        if ( props.getMaximumSize() >= 0 ) {
            c.maximumSize( props.getMaximumSize() );
        }
        // can extend config to include additional properties

        localCacheManager.setCaffeine( c );
        log.info( "building [{}] cache with config: [{}]", name, c.toString() );

        return localCacheManager.getCache( name );
    }

    private void setCacheManager() {
        log.info( "creating {}...", "localCacheManager" );
        localCacheManager = new CaffeineCacheManager();
        ( (ConfigurableBeanFactory) beanFactory )
                .registerSingleton( "localCacheManager", localCacheManager );
    }
}
</code>```

And finally, the using application would define its caches via configuration (yaml here):

```<code>cache:
  caches:
    - name: c1
      properties:
        maximumSize: 50
    - name: c2
      properties:
        maximumSize: 5000
</code>```

This example is based on the answer from the similar question, but the cache @Beans created this way can't be autowired in the application.

Feels like registering bean definitions in ImportBeanDefinitionRegistrar could work, but don't think beanDefs can be used with Caffeine instances, as those are created via builder, not property setters.

How could this be implemented?

答:
If this is a Spring Boot project look at:

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/html/boot-features-caching.html#boot-features-caching-provider-caffeine

Body:
Related:

Spring Boot create a list of managed prototype beans from database configuration

How do I create beans programmatically in Spring Boot?

How to programatically add an @Bean definition to Spring context?

This question is pretty much the same as this, but the answer using BeanFactoryAware doesn't solve my problem as the created @Beans are not @Autowireable.

Requirements:

configure number of beans via spring configuration;

pick this configuration up via @ConfigurationProperties;

create & inject @Beans based on said config from an autoconfiguration module;

be able to @Autowire created beans in application.

Example:
Make it possible to declare number of caffeine-based Cache @Beans via spring config. Following is implementation based on the accepted answer from the similar question:

First, the boot autoconfiguration module:

@Component
@ConfigurationProperties
@Data
public class Props {

    private LocalCacheConf cache = new LocalCacheConf();

    @Data
    public static class LocalCacheConf {

        /**
        * List of caches to create, with accompanying configuration.
        */
        private List<CacheDef> caches = new ArrayList<>();

        @Data
        public static class CacheDef {

            private String name;
            private CaffeineCacheConf properties;
        }

        @Data
        public static class CaffeineCacheConf {

            private long maximumSize = -1;
        }
    }
}

@Configuration
@Slf4j
public class LocalCacheConfig implements BeanFactoryAware {

    @Autowired private Props props;
    @Setter private BeanFactory beanFactory;
    private CaffeineCacheManager localCacheManager;

    @PostConstruct
    public void configure() {
        setCacheManager();
        createCaches( props.getCache() );
    }

    private void createCaches( LocalCacheConf locCacheConf ) {
        ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;

        for ( CacheDef cacheProps : locCacheConf.getCaches() ) {
            Cache cache = createAndConfigureCache(
                    cacheProps.getName(),
                    cacheProps.getProperties()
            );
            configurableBeanFactory.registerSingleton( cacheProps.getName(), cache );
        }
    }

    private Cache createAndConfigureCache( String name, CaffeineCacheConf props ) {
        Caffeine<Object, Object> c = Caffeine.newBuilder().recordStats();

        if ( props.getMaximumSize() >= 0 ) {
            c.maximumSize( props.getMaximumSize() );
        }
        // can extend config to include additional properties

        localCacheManager.setCaffeine( c );
        log.info( "building [{}] cache with config: [{}]", name, c.toString() );

        return localCacheManager.getCache( name );
    }

    private void setCacheManager() {
        log.info( "creating {}...", "localCacheManager" );
        localCacheManager = new CaffeineCacheManager();
        ( (ConfigurableBeanFactory) beanFactory )
                .registerSingleton( "localCacheManager", localCacheManager );
    }
}

And finally, the using application would define its caches via configuration (yaml here):

cache:
  caches:
    - name: c1
      properties:
        maximumSize: 50
    - name: c2
      properties:
        maximumSize: 5000

This example is based on the answer from the similar question, but the cache @Beans created this way can't be autowired in the application.

Feels like registering bean definitions in ImportBeanDefinitionRegistrar could work, but don't think beanDefs can be used with Caffeine instances, as those are created via builder, not property setters.

How could this be implemented?


问:
ExtJS: Limiting the number of rows on a GridPanel
I have a grid panel that loads data through a XML store. I cannot control how many items the XML will return, but I want to limit the grid to showing x number of rows.

Sorry if this is basic, I couldnt find it via google

Cheers

答: Just use getRange () method in Store (XmlStore) when load data to GridPanel</p>


问:
Is there a way in C# to trigger a onclick() event and still be able to detect onDrag() event while still holding mouse click down
I tried the dragOver event handler but it didn't work as it should.

I am working on a piano and I want to be able to play the note even if the mousedown didn't happen on that key.

Is there an event handler for this?

The below is a picture of the piano I am working on.

答:
Yes you're trying to click and drag like here :  </p>

```<code>private void MyMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
               //Bla bla bla , do whatever you want
            }
        }
</code>```

Body:
Yes you're trying to click and drag like here :

private void MyMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
               //Bla bla bla , do whatever you want
            }
        }


问:
NS2 New AQM implementation
I am currently working on NS2 about different queue managers including RED. I am trying to incorporate queue managers not built-in with NS2 like FRED and BLUE. I have been trying several methods and instructions including the ones that can only be found inside the actual research papers of said queue managers. I have also searched here but of no luck. I am getting this error by the way.

invalid command name "Queue/FRED"
    while executing
"Queue/FRED create _o42 "
    invoked from within
"catch "$className create $o $args" msg"
    invoked from within
"if [catch "$className create $o $args" msg] {
if [string match "__FAILED_SHADOW_OBJECT_" $msg] {
delete $o
return ""
}
global errorInfo
error "class $..."
    (procedure "new" line 3)
    invoked from within
"new Queue/$qtype"
    ("default" arm line 3)
    invoked from within
"switch -exact $qtype {
ErrorModule {
if { [llength $args] > 0 } {
set q [eval new $qtype $args]
} else {
set q [new $qtype Fid]
}
}
intserv {
set qtyp..."
    (procedure "_o3" line 14)
    (Simulator simplex-link line 14)
    invoked from within
"_o3 simplex-link _o13 _o16 1Mb 10ms FRED"
    ("eval" body line 1)
    invoked from within
"eval $self simplex-link $n1 $n2 $bw $delay $type $args"
    (procedure "_o3" line 8)
    (Simulator duplex-link line 8)
    invoked from within
"$ns duplex-link $n1 $n2 1Mb 10ms FRED"
    (file "fred.tcl" line 31)```

These are a few of the instructions I've tried to add FRED and BLUE but returns the same error.

Berkeley Instructions |
NS2 instructions

Any help will be greatly appreciated. Thanks!
Edit: I pasted the error in a snippet to present the error code neatly.

答:
Example building ns2 + FRED

```<code>tar xvf ns-allinone-2.34.tar.gz
cd ns-allinone-2.34/
patch -p0 < FRED_ns234.patch
</code>```

https://drive.google.com/file/d/1sriJu2VjvxzT63XAdrohgCppx1nzu5j8/view?usp=sharing

```<code>export CC=gcc34 CXX=g++34 && ./install
cd ns-2.34/
cp ns ns234-FRED    (This is your backup and safe identifier for ns+FRED)
sudo cp ns234-FRED /usr/local/bin/
</code>```

Simulation : $ ns234-FRED [simulation].tcl

And ns-2.35 → ns-allinone-2.35_gcc5.tar.gz
https://drive.google.com/file/d/0B7S255p3kFXNVVlxR0ZNRGVORjQ/view?usp=sharing

Patch: FRED_ns235.patch https://drive.google.com/file/d/1xnYd0xXV53mLloL1Wjzh_HtGua71jpx5/view?usp=sharing

Ubuntu downloads ...

64bits gcc34 https://drive.google.com/file/d/0B7S255p3kFXNRTkzQnRSNXZ6UVU/view?usp=sharing ... g++34 https://drive.google.com/file/d/0B7S255p3kFXNV3J3bnVoWGNWdG8/view?usp=sharing

32bits gcc34 https://drive.google.com/file/d/0B7S255p3kFXNTzNKRHBEMHFwNTg/view?usp=sharing ... g++34 https://drive.google.com/file/d/0B7S255p3kFXNT0JTTVNDSHpNVGM/view?usp=sharing

Install : $ cd Downloads/ && sudo gdebi [package]_[arch]

Howto FRED, ns-2.35, Ubuntu 16.04

```<code>tar xvf ns-allinone-2.35_gcc5.tar.gz
cd ns-allinone-2.35/
patch -p0 < FRED_ns235.patch
./install              // Stops with queue/csfq* error.
cd ns-2.35/            // Edit the Makefile line 37 to CPP = g++34
make                   // Stops with linker error (Or earlier)
                       // Edit the Makefile line 37 to CPP = g++
make
cp ns ns235-FRED
sudo cp ns235-FRED /usr/local/bin/
</code>```

Title: NS2 New AQM implementation

Body:
I am currently working on NS2 about different queue managers including RED. I am trying to incorporate queue managers not built-in with NS2 like FRED and BLUE. I have been trying several methods and instructions including the ones that can only be found inside the actual research papers of said queue managers. I have also searched here but of no luck. I am getting this error by the way.

invalid command name "Queue/FRED"
    while executing
"Queue/FRED create _o42 "
    invoked from within
"catch "$className create $o $args" msg"
    invoked from within
"if [catch "$className create $o $args" msg] {
if [string match "__FAILED_SHADOW_OBJECT_" $msg] {
delete $o
return ""
}
global errorInfo
error "class $..."
    (procedure "new" line 3)
    invoked from within
"new Queue/$qtype"
    ("default" arm line 3)
    invoked from within
"switch -exact $qtype {
ErrorModule {
if { [llength $args] > 0 } {
set q [eval new $qtype $args]
} else {
set q [new $qtype Fid]
}
}
intserv {
set qtyp..."
    (procedure "_o3" line 14)
    (Simulator simplex-link line 14)
    invoked from within
"_o3 simplex-link _o13 _o16 1Mb 10ms FRED"
    ("eval" body line 1)
    invoked from within
"eval $self simplex-link $n1 $n2 $bw $delay $type $args"
    (procedure "_o3" line 8)
    (Simulator duplex-link line 8)
    invoked from within
"$ns duplex-link $n1 $n2 1Mb 10ms FRED"
    (file "fred.tcl" line 31)

These are a few of the instructions I've tried to add FRED and BLUE but returns the same error.

Berkeley Instructions |
NS2 instructions

Any help will be greatly appreciated. Thanks!
Edit: I pasted the error in a snippet to present the error code neatly.

Body:
Example building ns2 + FRED

tar xvf ns-allinone-2.34.tar.gz
cd ns-allinone-2.34/
patch -p0 < FRED_ns234.patch

https://drive.google.com/file/d/1sriJu2VjvxzT63XAdrohgCppx1nzu5j8/view?usp=sharing

export CC=gcc34 CXX=g++34 && ./install
cd ns-2.34/
cp ns ns234-FRED    (This is your backup and safe identifier for ns+FRED)
sudo cp ns234-FRED /usr/local/bin/

Simulation : $ ns234-FRED [simulation].tcl

And ns-2.35 → ns-allinone-2.35_gcc5.tar.gz
https://drive.google.com/file/d/0B7S255p3kFXNVVlxR0ZNRGVORjQ/view?usp=sharing

Patch: FRED_ns235.patch https://drive.google.com/file/d/1xnYd0xXV53mLloL1Wjzh_HtGua71jpx5/view?usp=sharing

Ubuntu downloads ...

64bits gcc34 https://drive.google.com/file/d/0B7S255p3kFXNRTkzQnRSNXZ6UVU/view?usp=sharing ... g++34 https://drive.google.com/file/d/0B7S255p3kFXNV3J3bnVoWGNWdG8/view?usp=sharing

32bits gcc34 https://drive.google.com/file/d/0B7S255p3kFXNTzNKRHBEMHFwNTg/view?usp=sharing ... g++34 https://drive.google.com/file/d/0B7S255p3kFXNT0JTTVNDSHpNVGM/view?usp=sharing

Install : $ cd Downloads/ && sudo gdebi [package]_[arch]

Howto FRED, ns-2.35, Ubuntu 16.04

tar xvf ns-allinone-2.35_gcc5.tar.gz
cd ns-allinone-2.35/
patch -p0 < FRED_ns235.patch
./install              // Stops with queue/csfq* error.
cd ns-2.35/            // Edit the Makefile line 37 to CPP = g++34
make                   // Stops with linker error (Or earlier)
                       // Edit the Makefile line 37 to CPP = g++
make
cp ns ns235-FRED
sudo cp ns235-FRED /usr/local/bin/


问:
Rails - good way to convert string to array if not array rails
I receive a param and want it to be either a string like this :

```<code>"abc,efg"
</code>```

or an Array like this

```<code>["abc","efg"]
</code>```

In the first case I want to convert it into an Array, what would be the good way ?

Here is what I thought

```<code>if params[:ids] && params[:ids].is_a? Array
     ids = params[:ids]
else if params[:ids]
    ids = params[:ids].split(",")
</code>```

Body:
I receive a param and want it to be either a string like this :

"abc,efg"

or an Array like this

["abc","efg"]

In the first case I want to convert it into an Array, what would be the good way ?

Here is what I thought

if params[:ids] && params[:ids].is_a? Array
     ids = params[:ids]
else if params[:ids]
    ids = params[:ids].split(",")

Body: Array.wrap(params[:ids]).map{|x| x.split(',')}.flatten


问:
How to change HyperlinkButton background and foreground color when PointerEntered in UWP
Here is my sample UWP code in C# and XAML
Where i created one hyperlink button in MainPage method and set the style attributes like foreground and background.

Now i want to change the background and foreground colors when PointerEntered event triggered like mouseover, in this case only font size is changing but not the colors

```<code>public MainPage(){
    this.InitializeComponent();

    var hLinkButton = new HyperlinkButton();

    hLinkButton.Name = "LearnMoreHyperLink";
    hLinkButton.Content = "Learn More...";

    hLinkButton.Background = new SolidColorBrush(Colors.Red);
    hLinkButton.Foreground = new SolidColorBrush(Colors.White);
    hLinkButton.FontWeight = FontWeights.SemiBold;
    hLinkButton.FontSize = 18.0;

    hLinkButton.PointerEntered += OnPointerEntered;
    LayoutGrid.Children.Add(hLinkButton);
}

private void OnPointerEntered(object sender, PointerRoutedEventArgs e){
    var hLButton = sender as HyperlinkButton;
    hLButton.Background = new SolidColorBrush(Colors.White);
    hLButton.Foreground = new SolidColorBrush(Colors.Red);
    hLButton.FontSize = 30.0;
}

// Only fontsize effecting on mouseover, background and foreground is not working
</code>```

答:
You should do it this way -

```<code>hLinkButton.PointerEntered += hLinkButton_OnPointerEntered;

private void hLinkButton_OnPointerEntered(object sender, PointerRoutedEventArgs e)
{
    var hLButton = sender as HyperlinkButton;
    hLButton.Background = new SolidColorBrush(Colors.White);
    hLButton.Foreground = new SolidColorBrush(Colors.Red);
    hLButton.FontSize = 30.0;
}
</code>```

further if you want reverse all things back, you should use Pointer hLinkButton_PointerExited Event

Update

Whats is actual problem everything looks fine with your code.

Output with your codes

Further you can declare your hyper link button once like this i am done

```<code>public sealed partial class MainPage : Page
{
    HyperlinkButton hLinkButton = new HyperlinkButton();

    public MainPage()
    {
        this.InitializeComponent();

        hLinkButton.Name = "LearnMoreHyperLink";
        hLinkButton.Content = "Learn More...";
        hLinkButton.Background = new SolidColorBrush(Colors.Red);
        hLinkButton.Foreground = new SolidColorBrush(Colors.White);
        hLinkButton.FontWeight = FontWeights.SemiBold;
        hLinkButton.FontSize = 18.0;
        hLinkButton.PointerEntered += OnPointerEntered;
        LayoutGrid.Children.Add(hLinkButton);
    }

    private void OnPointerEntered(object sender, PointerRoutedEventArgs e)
    {
        hLinkButton.Background = new SolidColorBrush(Colors.White);
        hLinkButton.Foreground = new SolidColorBrush(Colors.Red);
        hLinkButton.FontSize = 30.0;
    }
}
</code>```

Body:
Here is my sample UWP code in C# and XAML
Where i created one hyperlink button in MainPage method and set the style attributes like foreground and background.

Now i want to change the background and foreground colors when PointerEntered event triggered like mouseover, in this case only font size is changing but not the colors

public MainPage(){
    this.InitializeComponent();

    var hLinkButton = new HyperlinkButton();

    hLinkButton.Name = "LearnMoreHyperLink";
    hLinkButton.Content = "Learn More...";

    hLinkButton.Background = new SolidColorBrush(Colors.Red);
    hLinkButton.Foreground = new SolidColorBrush(Colors.White);
    hLinkButton.FontWeight = FontWeights.SemiBold;
    hLinkButton.FontSize = 18.0;

    hLinkButton.PointerEntered += OnPointerEntered;
    LayoutGrid.Children.Add(hLinkButton);
}

private void OnPointerEntered(object sender, PointerRoutedEventArgs e){
    var hLButton = sender as HyperlinkButton;
    hLButton.Background = new SolidColorBrush(Colors.White);
    hLButton.Foreground = new SolidColorBrush(Colors.Red);
    hLButton.FontSize = 30.0;
}

// Only fontsize effecting on mouseover, background and foreground is not working

Body:
You should do it this way -

hLinkButton.PointerEntered += hLinkButton_OnPointerEntered;

private void hLinkButton_OnPointerEntered(object sender, PointerRoutedEventArgs e)
{
    var hLButton = sender as HyperlinkButton;
    hLButton.Background = new SolidColorBrush(Colors.White);
    hLButton.Foreground = new SolidColorBrush(Colors.Red);
    hLButton.FontSize = 30.0;
}

further if you want reverse all things back, you should use Pointer hLinkButton_PointerExited Event

Update

Whats is actual problem everything looks fine with your code.

Output with your codes

Further you can declare your hyper link button once like this i am done

public sealed partial class MainPage : Page
{
    HyperlinkButton hLinkButton = new HyperlinkButton();

    public MainPage()
    {
        this.InitializeComponent();

        hLinkButton.Name = "LearnMoreHyperLink";
        hLinkButton.Content = "Learn More...";
        hLinkButton.Background = new SolidColorBrush(Colors.Red);
        hLinkButton.Foreground = new SolidColorBrush(Colors.White);
        hLinkButton.FontWeight = FontWeights.SemiBold;
        hLinkButton.FontSize = 18.0;
        hLinkButton.PointerEntered += OnPointerEntered;
        LayoutGrid.Children.Add(hLinkButton);
    }

    private void OnPointerEntered(object sender, PointerRoutedEventArgs e)
    {
        hLinkButton.Background = new SolidColorBrush(Colors.White);
        hLinkButton.Foreground = new SolidColorBrush(Colors.Red);
        hLinkButton.FontSize = 30.0;
    }
}


问:
Java - Design Pattern, Session Management for Web Service Client
I am writing a client library for a web service using CXF. The service uses a mutable key to manage sessions and, optionally, allows a session to be kept alive.

I have built a client Client and I want to provide the ability for uses of the library to choose their type of session management i.e. either a manager which just manages keys but does not attempt to keep alive and a manager which manages keys and keeps the session alive.

I had thought of having a SessionManager field in the Client class (with a SimpleSessionManager class and a KeepAliveSessionManager class) but, in order to keep the session alive, the KeepAliveSessionManger would have to call a method of the Client class. That would mean that the Client class has a reference to the SessionManager class and the SessionManager class would have a reference to the Client class - which is obviously an inelegant design.

Can you suggest a design pattern (or altnernate implementation) that would let me implement these features in a 'better' way?

Cheers,

Pete

答:
You could use the SessionManager as a factory for "clients" that would return an interface for the client.
The client wouldn't need to "know" the SessionManager. And if the SessionMaAnager was a KeepAliveSessionMaanger, it would internally keep the session alive.

Something like this:

```<code>SessionManager sm = new KeepAliveSessionManager(int keepAliveTimeout);

IClient client = sm.GetClient();
client.InvokeSomeMethod();
</code>```

The SessionManager internally uses a thread (or something) and the client to keep the session alive. The client never "knows" about the SessionManager..

BTW, i'm thinking in .NET but it should translate to java...

Body:
You could use the SessionManager as a factory for "clients" that would return an interface for the client.
The client wouldn't need to "know" the SessionManager. And if the SessionMaAnager was a KeepAliveSessionMaanger, it would internally keep the session alive.

Something like this:

SessionManager sm = new KeepAliveSessionManager(int keepAliveTimeout);

IClient client = sm.GetClient();
client.InvokeSomeMethod();

The SessionManager internally uses a thread (or something) and the client to keep the session alive. The client never "knows" about the SessionManager..

BTW, i'm thinking in .NET but it should translate to java...


问:
Getting breakpoints to work with jest, Visual studio code and a custom typescript transformer
I can't get breakpoints to work in VSCode using ts-jest as a custom preprocessor.
If i use a debugger statement, it will break at the correct place, and show the correct sources, so the sourcemaps are being loaded and parsed.

On every breakpoint VSCode reports:
Breakpoint ignored because generated code not found (source map problem?)

This is my setup (the same setup works fine in webstorm both with debugger statements and breakpoints)

launch.json

```<code>{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug Jest",
      "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
      "args": [
        "--runInBand",
        "--no-cache"
      ],
      "cwd": "${workspaceRoot}",
      "console": "integratedTerminal",
      "sourceMaps": true,
    }
  ]
}
</code>```

.tsconfig.json:

```<code>{
  "compilerOptions": {
    "jsx": "react",
    "allowSyntheticDefaultImports": true,
    "target": "es2015",
    "moduleResolution": "node",
    "inlineSourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

package.json>jest

```<code>"jest": {
  "preset": "react-native",
  "transform": {
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
    ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
  },
  "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx)$",
  "mapCoverage": true,
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js",
    "json"
  ],
  "globals": {
    "__DEV__": true
  }
}
</code>```

.babelrc

```<code>{
  "presets": [
    "react-native"
  ],
  "sourceMaps": "inline"
}
</code>```

答:
This seems to have been fixed in later versions of ts-jest, though I'm not quite sure why. Breakpoints should work with node 8 out of the box with the above setup.

For further details see : https://github.com/kulshekhar/ts-jest/issues/212

Body:
I can't get breakpoints to work in VSCode using ts-jest as a custom preprocessor.
If i use a debugger statement, it will break at the correct place, and show the correct sources, so the sourcemaps are being loaded and parsed.

On every breakpoint VSCode reports:
Breakpoint ignored because generated code not found (source map problem?)

This is my setup (the same setup works fine in webstorm both with debugger statements and breakpoints)

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug Jest",
      "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
      "args": [
        "--runInBand",
        "--no-cache"
      ],
      "cwd": "${workspaceRoot}",
      "console": "integratedTerminal",
      "sourceMaps": true,
    }
  ]
}

.tsconfig.json:

{
  "compilerOptions": {
    "jsx": "react",
    "allowSyntheticDefaultImports": true,
    "target": "es2015",
    "moduleResolution": "node",
    "inlineSourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

package.json>jest

"jest": {
  "preset": "react-native",
  "transform": {
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
    ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
  },
  "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx)$",
  "mapCoverage": true,
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js",
    "json"
  ],
  "globals": {
    "__DEV__": true
  }
}

.babelrc

{
  "presets": [
    "react-native"
  ],
  "sourceMaps": "inline"
}


问:
IF_NAMESIZE vs. IF_NAMESIZE+1
When I use IF_NAMESIZE (from net/if.h in libc implementations) as array size, should I use it as it is or with + 1 for \0 (null byte)?

```<code>char iface[IF_NAMESIZE];
</code>```

or

```<code>char iface[IF_NAMESIZE + 1];
</code>```

I see it using both ways across various open source projects.

答:
The  header shall define the following symbolic constant for
  the length of a buffer containing an interface name (including the
  terminating NULL character):

IF_NAMESIZE Interface name length.

http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/net_if.h.html

So:

```<code>char iface[IF_NAMESIZE];
</code>```

is enough

Title: IF_NAMESIZE vs. IF_NAMESIZE+1

Body:
When I use IF_NAMESIZE (from net/if.h in libc implementations) as array size, should I use it as it is or with + 1 for \0 (null byte)?

char iface[IF_NAMESIZE];

or

char iface[IF_NAMESIZE + 1];

I see it using both ways across various open source projects.

Body:
The  header shall define the following symbolic constant for
  the length of a buffer containing an interface name (including the
  terminating NULL character):

IF_NAMESIZE Interface name length.

http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/net_if.h.html

So:

char iface[IF_NAMESIZE];

is enough


问:
Wordpress site setup SSO to support support SAML request signature
I have WordPress based site need to setup sign sign on (Identity Provider is: Ping Identity), I'm use WordPress miniOrange plugin to configure the SSO, when test the configuration, get following error:

Error: Invalid SAML Response Status.

Causes: Identity Provider has sent 'Requester' status code in SAML Response.
Please check IdP logs.

Reason: The request could not be performed due to an error on the part of the requester.

Status Message in the SAML Response: Signature required

It (the error) looks like looks like the Identity provider require the SAML request to signed, and ask service provider (WordPress site) to share the public key with Identity provider, but I'm unable to find how to set signed SAML request on miniOrange plugin and don't know which folder to store the private key on WordPress.

Have two questions:

Is WordPress miniOrange plugin support SAML request signature?

How Do I setup it up?

Any other recommended WordPress plugin for SSO?

答:
Your partner, in the PingFederate console, can disable the requirement for AuthnRequests to be signed. This will be fine as long as your AuthnRequest is telling them to send the Response+Assertion to the same URL as what they have defined in their connection. For example, if your AuthnRequest has an AssertionConsumerServiceURL in it that does not match what the IdP has defined in Ping, then Ping will not honor the request and return a failure.

All that is to say that PingFed at the IdP is configurable for this issue. Have them turn off "Require Authentication Requests to be Signed".