问:
Add a custom text to specific email notification for local pickup Woocommerce orders
I tried the following code that is displaying a message to all those customers who should receive a customer_processing_order and customer_completed_order when local_pickup is the chosen shipping method.

I noticed I do not store any _shipping_method item within any order meta, but only a thing like: order_item_type: shipping > method_id > local_pickup:3

How can I retrieve it?

I tried this of code without success:

```<code>// testo per Ritiro in Sede

add_action( 'woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4 );
function my_completed_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {

if( 'customer_processing_order' != $email->id ) return;

if ( method_exists( $order, 'get_id' ) ) {
    $order_id = $order->get_id();
} else {
    $order_id = $order->id;
}

$shipping_method_arr = get_post_meta($order_id, '_shipping_method', false);
$method_id = explode( ':', $shipping_method_arr[0][0] );
$method_id = $method_id[0];  // We get the slug type method

if ( 'local_pickup' == $method_id ){
    echo '<p><strong>Ritiro in sede</strong></p>';
   }
}
</code>```

答:
This can be done iterating through order shipping items, this way:

```<code>add_action( 'woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4 );
function my_completed_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {
    // Only for processing and completed email notifications to customer
    if( ! ( 'customer_processing_order' == $email->id || 'customer_completed_order' == $email->id ) ) return;

    foreach( $order->get_items('shipping') as $shipping_item ){
        $shipping_rate_id = $shipping_item->get_method_id();
        $method_array = explode(':', $shipping_rate_id );
        $shipping_method_id = reset($method_array);
        // Display a custom text for local pickup shipping method only
        if( 'local_pickup' == $shipping_method_id ){
            echo '<p><strong>Ritiro in sede</strong></p>';
            break;
        }
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.

Body:
I tried the following code that is displaying a message to all those customers who should receive a customer_processing_order and customer_completed_order when local_pickup is the chosen shipping method.

I noticed I do not store any _shipping_method item within any order meta, but only a thing like: order_item_type: shipping > method_id > local_pickup:3

How can I retrieve it?

I tried this of code without success:

// testo per Ritiro in Sede

add_action( 'woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4 );
function my_completed_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {

if( 'customer_processing_order' != $email->id ) return;

if ( method_exists( $order, 'get_id' ) ) {
    $order_id = $order->get_id();
} else {
    $order_id = $order->id;
}

$shipping_method_arr = get_post_meta($order_id, '_shipping_method', false);
$method_id = explode( ':', $shipping_method_arr[0][0] );
$method_id = $method_id[0];  // We get the slug type method

if ( 'local_pickup' == $method_id ){
    echo '
Ritiro in sede
';
   }
}

Body:
This can be done iterating through order shipping items, this way:

add_action( 'woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4 );
function my_completed_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {
    // Only for processing and completed email notifications to customer
    if( ! ( 'customer_processing_order' == $email->id || 'customer_completed_order' == $email->id ) ) return;

    foreach( $order->get_items('shipping') as $shipping_item ){
        $shipping_rate_id = $shipping_item->get_method_id();
        $method_array = explode(':', $shipping_rate_id );
        $shipping_method_id = reset($method_array);
        // Display a custom text for local pickup shipping method only
        if( 'local_pickup' == $shipping_method_id ){
            echo '<p><strong>Ritiro in sede</strong></p>';
            break;
        }
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.


来源: stackexchange

问:
How to replace an object property value in redux
I am trying to create an online shop using redux. I have got it so that a person can add an item to their basket. However, having difficulty with adding quantity. I have a method that works that wont let someone add the same product twice, I just need to now make it increase the quantity for that same product.

My basket state is stored as an array of objects.

This is my basket reducer:

```<code>const initialState = [];

const isProductInBasket = (state, action) => {
  for (var i=0; i < state.length; i++){
    if(state[i].product.id == action.data.product.id){
      return true;
    }
  }
}

export default (state = initialState, action) => {
  switch(action.type) {
    case "ADD_TO_BASKET":
      if (isProductInBasket(state, action)) {
        for (var i=0; i < state.length; i++){
          if(state[i].product.id = action.data.product.id){
            console.log(state, 'stst');
            const basketState = state[i].product.quantity + 1;
            return {...state, basketState}; //problem is here
          }
        }
      }
      else {
        const basketState = [].concat(state).concat(action.data)
        return basketState;
        break;
      }
    default:
        return state
  };
};
</code>```

Clearly what im doing is wrong as im returning an object, but im wondering how i can return that new object in place of the old object. i need to return it as an object but inside an array...

just to be uber clear, when I have this:

```<code>{name: "Rucksack", price: "15.00", id: 1, quantity: 0}
</code>```

and I click add to basket, it should then come back as:

```<code>{name: "Rucksack", price: "15.00", id: 1, quantity: 1}
</code>```

答:
You could use findIndex to check if the object already exists and update it else push the payload data into state</p>

```<code>switch(action.type) {
    case "ADD_TO_BASKET":
      const index = state.findIndex(productData => productData.product.id === action.data.product.id);
     if(index > -1) {
        return [
            ...state.slice(0, index),
            {
                ...state[index],
                product: {
                    ...state.product,
                    quantity: state[index].product.quantity + 1
                }
            },
            ...state.slice(index + 1)
        ]
     }
     return [...state, action.data]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create an online shop using redux. I have got it so that a person can add an item to their basket. However, having difficulty with adding quantity. I have a method that works that wont let someone add the same product twice, I just need to now make it increase the quantity for that same product.

My basket state is stored as an array of objects.

This is my basket reducer:

const initialState = [];

const isProductInBasket = (state, action) => {
  for (var i=0; i < state.length; i++){
    if(state[i].product.id == action.data.product.id){
      return true;
    }
  }
}

export default (state = initialState, action) => {
  switch(action.type) {
    case "ADD_TO_BASKET":
      if (isProductInBasket(state, action)) {
        for (var i=0; i < state.length; i++){
          if(state[i].product.id = action.data.product.id){
            console.log(state, 'stst');
            const basketState = state[i].product.quantity + 1;
            return {...state, basketState}; //problem is here
          }
        }
      }
      else {
        const basketState = [].concat(state).concat(action.data)
        return basketState;
        break;
      }
    default:
        return state
  };
};

Clearly what im doing is wrong as im returning an object, but im wondering how i can return that new object in place of the old object. i need to return it as an object but inside an array...

just to be uber clear, when I have this:

{name: "Rucksack", price: "15.00", id: 1, quantity: 0}

and I click add to basket, it should then come back as:

{name: "Rucksack", price: "15.00", id: 1, quantity: 1}

Body:
You could use findIndex to check if the object already exists and update it else push the payload data into state

switch(action.type) {
    case "ADD_TO_BASKET":
      const index = state.findIndex(productData => productData.product.id === action.data.product.id);
     if(index > -1) {
        return [
            ...state.slice(0, index),
            {
                ...state[index],
                product: {
                    ...state.product,
                    quantity: state[index].product.quantity + 1
                }
            },
            ...state.slice(index + 1)
        ]
     }
     return [...state, action.data]


问:
[Obj-C]How do i do an IBAlert after using NSTask?
i use NSTask, works 100% but after running it (when running it, i also use an MBProcessHUD) i want to do an IBAlert with somethings in it...

here is my code

```<code>-(void) runScript {
    task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/bash"];
    NSString *script;
    script = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"a2cy.sh"];
    NSArray *arguments = [NSArray arrayWithObjects:script, [sourcerepo text], nil];
    [task setArguments: arguments];
    [task launch];
    sleep(1);
    HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkmark.png"]] autorelease];
    HUD.mode = MBProgressHUDModeCustomView;
    HUD.labelText = @"Complete!";
    NSString *loggy;
    loggy = [NSString stringWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/log.txt"]];
    UIAlertView *log = [[UIAlertView alloc] initWithTitle:@"Result" message:loggy delegate:self cancelButtonTitle:@"Ok!" otherButtonTitles:nil];
    [loggy show];
    [loggy release];
}
</code>```

but after running, it doesn't show up :/ any help? thanks

答:
You need to call the alert's show method on log, not loggy..

[log show];

ContentLicense: CC BY-SA 2.5

Body:
i use NSTask, works 100% but after running it (when running it, i also use an MBProcessHUD) i want to do an IBAlert with somethings in it...

here is my code

-(void) runScript {
    task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/bash"];
    NSString *script;
    script = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"a2cy.sh"];
    NSArray *arguments = [NSArray arrayWithObjects:script, [sourcerepo text], nil];
    [task setArguments: arguments];
    [task launch];
    sleep(1);
    HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkmark.png"]] autorelease];
    HUD.mode = MBProgressHUDModeCustomView;
    HUD.labelText = @"Complete!";
    NSString *loggy;
    loggy = [NSString stringWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/log.txt"]];
    UIAlertView *log = [[UIAlertView alloc] initWithTitle:@"Result" message:loggy delegate:self cancelButtonTitle:@"Ok!" otherButtonTitles:nil];
    [loggy show];
    [loggy release];
}

but after running, it doesn't show up :/ any help? thanks


问:
Button Click inside TableView Header is ignore in iOS
I am making TableView with the custom Header. in the custom header I have 1 ImageView, 2 UILabel and 1 UIButton. When i set TouchUpInSide event on the UIButton it will not fire.

I see many post on the SO and google but nothing is getting help me.

Here What i have tried :

1). Swift - Custom TableView Not Executing Click on UIButton

2). UIButton in UITableView tableHeaderView not responding to touches

3). UIButton in a UITableView header ignores most touches

Here is my code for Custom header.

Code :

```<code>public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            TableView.Frame = new RectangleF((float)TableView.Frame.Left, 130, (float)TableView.Frame.Width, (float)(View.Frame.Size.Height - 130));
            headerView = new UIView();
            headerView.Frame = new CoreGraphics.CGRect(0, 0, TableView.Frame.Width, 140);

            UIImageView backgroundImage = new UIImageView();
            backgroundImage.Image = UIImage.FromFile("drawerbg");
            backgroundImage.Frame = new CoreGraphics.CGRect(0, 0, TableView.Frame.Width, 140);
            headerView.AddSubview(backgroundImage);

            profileImage = new UIImageView();
            profileImage.Frame = new CoreGraphics.CGRect(10, 10, 70, 70);
            profileImage.Layer.CornerRadius = 35;
            profileImage.ClipsToBounds = true;
            profileImage.Image = UIImage.FromBundle("default_user");
            backgroundImage.AddSubview(profileImage);

            userName = new UILabel();
            userName.Frame = new CoreGraphics.CGRect(10, 90, TableView.Frame.Width - 20, 20);
            userName.Font = GargiFontAndSize.B14();
            userName.TextColor = UIColor.White;
            backgroundImage.AddSubview(userName);

            userOrganization = new UILabel();
            userOrganization.Frame = new CoreGraphics.CGRect(10, 110, TableView.Frame.Width - 50, 20);
            userOrganization.Font = GargiFontAndSize.B14();
            userOrganization.TextColor = UIColor.White;
            userOrganization.Text = "Organizaton";
            backgroundImage.AddSubview(userOrganization);

            organizationArrowButton = new UIButton();
            organizationArrowButton.Frame = new CoreGraphics.CGRect(260, 110, 20, 20);
            organizationArrowButton.SetImage(UIImage.FromBundle("sort_down"), UIControlState.Normal);
            organizationArrowButton.UserInteractionEnabled = true;
            organizationArrowButton.ClipsToBounds = false;
            backgroundImage.AddSubview(organizationArrowButton);
            organizationArrowButton.BringSubviewToFront(headerView);

            TableView.SectionHeaderHeight = 0;
            TableView.SectionFooterHeight = 0;

            var gradient = new CAGradientLayer();
            gradient.Frame = headerView.Frame;
            gradient.Colors = new CoreGraphics.CGColor[] { GargiColor.PrimaryColor().CGColor, GargiColor.SecondaryColor().CGColor };
            headerView.Layer.InsertSublayer(gradient, 0);

            TableView.TableHeaderView = headerView;

}
</code>```

One more thing My viewController is extend DialogViewController.

Any Help will be Appreciated..

答: UIImageView's userInteraction is disabled by default, and you are adding button to image view, set userInteractionEnabled to true for UIImageView.</p>

Body:
I am making TableView with the custom Header. in the custom header I have 1 ImageView, 2 UILabel and 1 UIButton. When i set TouchUpInSide event on the UIButton it will not fire.

I see many post on the SO and google but nothing is getting help me.

Here What i have tried :

1). Swift - Custom TableView Not Executing Click on UIButton

2). UIButton in UITableView tableHeaderView not responding to touches

3). UIButton in a UITableView header ignores most touches

Here is my code for Custom header.

Code :

public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            TableView.Frame = new RectangleF((float)TableView.Frame.Left, 130, (float)TableView.Frame.Width, (float)(View.Frame.Size.Height - 130));
            headerView = new UIView();
            headerView.Frame = new CoreGraphics.CGRect(0, 0, TableView.Frame.Width, 140);

            UIImageView backgroundImage = new UIImageView();
            backgroundImage.Image = UIImage.FromFile("drawerbg");
            backgroundImage.Frame = new CoreGraphics.CGRect(0, 0, TableView.Frame.Width, 140);
            headerView.AddSubview(backgroundImage);

            profileImage = new UIImageView();
            profileImage.Frame = new CoreGraphics.CGRect(10, 10, 70, 70);
            profileImage.Layer.CornerRadius = 35;
            profileImage.ClipsToBounds = true;
            profileImage.Image = UIImage.FromBundle("default_user");
            backgroundImage.AddSubview(profileImage);

            userName = new UILabel();
            userName.Frame = new CoreGraphics.CGRect(10, 90, TableView.Frame.Width - 20, 20);
            userName.Font = GargiFontAndSize.B14();
            userName.TextColor = UIColor.White;
            backgroundImage.AddSubview(userName);

            userOrganization = new UILabel();
            userOrganization.Frame = new CoreGraphics.CGRect(10, 110, TableView.Frame.Width - 50, 20);
            userOrganization.Font = GargiFontAndSize.B14();
            userOrganization.TextColor = UIColor.White;
            userOrganization.Text = "Organizaton";
            backgroundImage.AddSubview(userOrganization);

            organizationArrowButton = new UIButton();
            organizationArrowButton.Frame = new CoreGraphics.CGRect(260, 110, 20, 20);
            organizationArrowButton.SetImage(UIImage.FromBundle("sort_down"), UIControlState.Normal);
            organizationArrowButton.UserInteractionEnabled = true;
            organizationArrowButton.ClipsToBounds = false;
            backgroundImage.AddSubview(organizationArrowButton);
            organizationArrowButton.BringSubviewToFront(headerView);

            TableView.SectionHeaderHeight = 0;
            TableView.SectionFooterHeight = 0;

            var gradient = new CAGradientLayer();
            gradient.Frame = headerView.Frame;
            gradient.Colors = new CoreGraphics.CGColor[] { GargiColor.PrimaryColor().CGColor, GargiColor.SecondaryColor().CGColor };
            headerView.Layer.InsertSublayer(gradient, 0);

            TableView.TableHeaderView = headerView;

}

One more thing My viewController is extend DialogViewController.

Any Help will be Appreciated..


问:
Drag & drop item from one timeline calendar to other react
I am using react-calendar-timeline for my project. I have requirements where i need to drag and drop item(s) from one calendar to other. Currently react-calendar-timeline library doesn't support such a thing from my findings.

Question is how can i drag and drop item(s) between calendars using react-calendar-timeline library? I am pretty sure it's doable but can't find out myself.

I would greatly appreciate if anyone guide me or provide me a hint.

Thanks

答:
I think your question is irrelevant ( or almost impossible ). Looking at the demo of react-calendar-timeline here, the only component being rendered is the <Timeline> component, and all items are being passed to it using items prop. That being the case, you can implement drag-and-drop only using any of the following ways:

Fork your own copy of react-calendar-timeline and implement draggability of items between calendars. It's not that difficult a task as it may seem, as the library is designed in a component based manner. Actually, digging further, I found this thread on that repo, in which one of the participants had forked and implemented drag and drop in his/her version. So you might draw inspiration from there :)

Use any other library like jQuery or D3 to implement drag and drop feature to individual elements by inspecting and selecting them via selectors. This is not at all recommended , as manipulating the DOM directly eliminates the whole point of using React, and it may interfere seriously with React's algorithms.

So that's it. Basically, as the library doesn't support the feature, you can't have the feature out of the box :)


问:
Error while loading shared libraries while running sqlplus
I am trying to install and run sqlplus in my ubuntu machine. I get the above error

```<code>error while loading shared libraries: libclntsh.so.12.1: cannot open shared object file: No such file or directory
</code>```

when I run

```<code>sudo sqlplus64 <user>/<pass>@//<ip>:<port>/db
</code>```

despite following the steps mentioned in the oracle install client document https://help.ubuntu.com/community/Oracle%20Instant%20Client

I have correctly set ORACLE_HOME and LD_LIBRARY_PATH
My strace sqlplus /nolog output shows below error

```<code>write(2, "SP2-0667: Message file sp1<lang>"..., 47SP2-0667: Message file sp1<lang>.msb not found
) = 47
write(2, "SP2-0750: You may need to set OR"..., 76SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
) = 76
</code>```

I can also attach complete strace if needed. Can someone help me fix the issue ?

答: Alternatively  Downloaded and installed sql developer from oracle from the link http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html</p>

Body:
I am trying to install and run sqlplus in my ubuntu machine. I get the above error

error while loading shared libraries: libclntsh.so.12.1: cannot open shared object file: No such file or directory

when I run

sudo sqlplus64 <user>/<pass>@//<ip>:<port>/db

despite following the steps mentioned in the oracle install client document https://help.ubuntu.com/community/Oracle%20Instant%20Client

I have correctly set ORACLE_HOME and LD_LIBRARY_PATH
My strace sqlplus /nolog output shows below error

write(2, "SP2-0667: Message file sp1<lang>"..., 47SP2-0667: Message file sp1<lang>.msb not found
) = 47
write(2, "SP2-0750: You may need to set OR"..., 76SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
) = 76

I can also attach complete strace if needed. Can someone help me fix the issue ?


答:
I'd recommend reading this section of the Redux docs - it shows you how to update an individual element in an array without mutation.

Effectively, what you need to do is create a new array that has a modified copy of your basket item. When you need to perform a transformation on an array without mutating, Array.prototype.map is your friend:

```<code>if (isProductInBasket(state, action)) {
    return state.map(product => {
        if (product.id == action.data.product.id) {
            return { ...product, quantity: product.quantity + 1 };
        }
        return product;
    });
}
</code>```

Title: How to replace an object property value in redux

Body:
I'd recommend reading this section of the Redux docs - it shows you how to update an individual element in an array without mutation.

Effectively, what you need to do is create a new array that has a modified copy of your basket item. When you need to perform a transformation on an array without mutating, Array.prototype.map is your friend:

if (isProductInBasket(state, action)) {
    return state.map(product => {
        if (product.id == action.data.product.id) {
            return { ...product, quantity: product.quantity + 1 };
        }
        return product;
    });
}


问:
Creating variable names using the contents of another variable
I have a simple foreach loop in Perl that logs into a few different remote hosts and runs a command which returns a numeric value. I want to save this value to a variable. The variable will be named after the individual hostnames (which are being looped through),
like below:

host01_backup

host02_backup

etc...

Therefore my question - is it possible to do this within the loop.

```<code>foreach $i (@hosts) {
  print "hostname is: $i \n";
  ssh("ins\@$i", "$cmd"); # this is where I want to assign a variable which is part named using the contents of $i (hostname).
</code>```

Cheers in advance!

答:
Do not create dynamically named variables. They are far more trouble then they are worth. We have arrays and hashes which are designed for this.

```<code>use strict;
use warnings;
use v5.10;

my @hosts = get_hosts();
my %hostnames = (
    host01_backup => "some value",
    host02_backup => "some value",
)
foreach my $hostname (@hosts) {
    say "hostname is: $hostname";
    ssh($hostnames{"host" . $hostname . "_backup"}, $cmd);
}
</code>```

I then want to save the output of the command that I run over the ssh connection in a variable that is named with the convention you've shown in the hash

This is the synopsis of Net::SSH::Perl:

```<code>use Net::SSH::Perl;
my $ssh = Net::SSH::Perl->new($host);
$ssh->login($user, $pass);
my($stdout, $stderr, $exit) = $ssh->cmd($cmd);
</code>```

So you have the output from that in some variables.

You can store them in the hash (previously created with my %ssh_output) with:

```<code>$ssh_output{$hostname} = $stdout;
</code>```

Body:
I have a simple foreach loop in Perl that logs into a few different remote hosts and runs a command which returns a numeric value. I want to save this value to a variable. The variable will be named after the individual hostnames (which are being looped through),
like below:

host01_backup

host02_backup

etc...

Therefore my question - is it possible to do this within the loop.

foreach $i (@hosts) {
  print "hostname is: $i \n";
  ssh("ins\@$i", "$cmd"); # this is where I want to assign a variable which is part named using the contents of $i (hostname).

Cheers in advance!

Body:
Do not create dynamically named variables. They are far more trouble then they are worth. We have arrays and hashes which are designed for this.

use strict;
use warnings;
use v5.10;

my @hosts = get_hosts();
my %hostnames = (
    host01_backup => "some value",
    host02_backup => "some value",
)
foreach my $hostname (@hosts) {
    say "hostname is: $hostname";
    ssh($hostnames{"host" . $hostname . "_backup"}, $cmd);
}

I then want to save the output of the command that I run over the ssh connection in a variable that is named with the convention you've shown in the hash

This is the synopsis of Net::SSH::Perl:

use Net::SSH::Perl;
my $ssh = Net::SSH::Perl->new($host);
$ssh->login($user, $pass);
my($stdout, $stderr, $exit) = $ssh->cmd($cmd);

So you have the output from that in some variables.

You can store them in the hash (previously created with my %ssh_output) with:

$ssh_output{$hostname} = $stdout;


问:
Storing ONLY MONTH and DATE in a single Column in MYSQL
Hi I am trying to store Month and Date in a single column.

UseCase

I am dumping data into mysql for reporting purpose and report is monthly.

I will be using Hibernate later to retreive data

答:
I'm not entirely clear regarding the format you wish to use but assuming storing the month as a number followed by the date and separated by some sort of delimiter is OK then something like the following would do. Just the second INSERT statement actually does the storing you asked about.

Having said that though, if you have the original data in a suitable format, I would suggest you use a single datetime column for storage and split it if necessary into month and date when you recover it later to use it.

```<code>-- make a table to hold some dates
CREATE TABLE testdates ( thedate DATE DEFAULT NULL) ;

-- make a table to hold just the month and date in one column as requested
CREATE TABLE tbl_month_and_date (the_month_and_date VARCHAR(14) DEFAULT NULL );

-- put some dummy dates into the testdates table
INSERT INTO testdates (thedate)
VALUES
('2017-09-14'),
('2017-10-13'),
('2017-11-27'),
('2017-08-20');

-- insert the month and date into a single column in the tbl_month_and_date table
-- in this case separated my <space> <colon> <space>
INSERT INTO tbl_month_and_date (the_month_and_date)
SELECT CONCAT(MONTH(thedate),' : ', thedate)
FROM testdates;

    -- show what is now in tbl_month_and_date
SELECT the_month_and_date
FROM tbl_month_and_date
</code>```

The contents of table tbl_month_and_date are now

```<code>the_month_and_date
9 : 2017-09-14
10 : 2017-10-1
11 : 2017-11-2
8 : 2017-08-20
</code>```

Body:
I'm not entirely clear regarding the format you wish to use but assuming storing the month as a number followed by the date and separated by some sort of delimiter is OK then something like the following would do. Just the second INSERT statement actually does the storing you asked about.

Having said that though, if you have the original data in a suitable format, I would suggest you use a single datetime column for storage and split it if necessary into month and date when you recover it later to use it.

-- make a table to hold some dates
CREATE TABLE testdates ( thedate DATE DEFAULT NULL) ;

-- make a table to hold just the month and date in one column as requested
CREATE TABLE tbl_month_and_date (the_month_and_date VARCHAR(14) DEFAULT NULL );

-- put some dummy dates into the testdates table
INSERT INTO testdates (thedate)
VALUES
('2017-09-14'),
('2017-10-13'),
('2017-11-27'),
('2017-08-20');

-- insert the month and date into a single column in the tbl_month_and_date table
-- in this case separated my <space> <colon> <space>
INSERT INTO tbl_month_and_date (the_month_and_date)
SELECT CONCAT(MONTH(thedate),' : ', thedate)
FROM testdates;

    -- show what is now in tbl_month_and_date
SELECT the_month_and_date
FROM tbl_month_and_date

The contents of table tbl_month_and_date are now

the_month_and_date
9 : 2017-09-14
10 : 2017-10-1
11 : 2017-11-2
8 : 2017-08-20


问:
How can I check that an element is visible with Puppeteer and pure JavaScript?
I wish to check that a DOM element is visible with Puppeteer and pure JavaScript (not jQuery), how can I do this? By visible I mean that the element is displayed through CSS, and not hidden (f.ex. by display: none).

For example, I can determine whether my element #menu is not hidden via CSS rule display: none, in the following way:

```<code>const isNotHidden = await page.$eval('#menu', (elem) => {
  return elem.style.display !== 'none'
})
</code>```

How can I determine in general though if the element is hidden or not, and not just through display: none?

答:
I found that Puppeteer has an API method for this purpose: Page.waitForSelector, via its visible option. I wasn't aware of the latter option, but it lets you wait until an element is visible.

```<code>await page.waitForSelector('#element', {
  visible: true,
})
</code>```

Conversely you can wait for an element to be hidden, via the hidden option.

I think this is the idiomatic answer, with regards to the Puppeteer API. Thanks to Colin Cline though as I think his answer is probably useful as a general JavaScript solution.

Body:
I wish to check that a DOM element is visible with Puppeteer and pure JavaScript (not jQuery), how can I do this? By visible I mean that the element is displayed through CSS, and not hidden (f.ex. by display: none).

For example, I can determine whether my element #menu is not hidden via CSS rule display: none, in the following way:

const isNotHidden = await page.$eval('#menu', (elem) => {
  return elem.style.display !== 'none'
})

How can I determine in general though if the element is hidden or not, and not just through display: none?

Body:
I found that Puppeteer has an API method for this purpose: Page.waitForSelector, via its visible option. I wasn't aware of the latter option, but it lets you wait until an element is visible.

await page.waitForSelector('#element', {
  visible: true,
})

Conversely you can wait for an element to be hidden, via the hidden option.

I think this is the idiomatic answer, with regards to the Puppeteer API. Thanks to Colin Cline though as I think his answer is probably useful as a general JavaScript solution.


问:
How do I convert a digit Char (0-9) to its numeric value?
Char.toInt() returns the ASCII code of the character, rather than its numeric value. So how do I convert the Char to an integer with the correct numeric value instead?

答:
You could also convert it to a String and then use toInt() which might be more obvious.

```<code>fun Char.getNumericValue(): Int {
    if (!isDigit()) {
        throw NumberFormatException()
    }
    return this.toString().toInt()
}
</code>```

Body:
You could also convert it to a String and then use toInt() which might be more obvious.

fun Char.getNumericValue(): Int {
    if (!isDigit()) {
        throw NumberFormatException()
    }
    return this.toString().toInt()
}


问:
Convert Column of List to Dataframe
I have a column of lists in a spark dataframe. </p>

<pre class="lang-python prettyprint-override"><code>+-----------------+
|features         |
+-----------------+
|[0,45,63,0,0,0,0]|
|[0,0,0,85,0,69,0]|
|[0,89,56,0,0,0,0]|
+-----------------+
</code>```

<p>How do I convert that to a spark dataframe where each element in the list is a column in the dataframe? We can assume that the lists will be the same size. </p>

<p>For Example, </p>

<pre class="lang-python prettyprint-override"><code>+--------------------+
|c1|c2|c3|c4|c5|c6|c7|
+--------------------+
|0 |45|63|0 |0 |0 |0 |
|0 |0 |0 |85|0 |69|0 |
|0 |89|56|0 |0 |0 |0 |
+--------------------+
</code>```

答:
Here's an alternative without converting to rdd,

from pyspark.sql import functions as F

##Not incase of vectorAssembeler.
stop = df.select(F.max(F.size('features')).alias('size')).first().size ## if having a list of varying size, this might be useful.

udf1 = F.udf(lambda x : x.toArray().tolist(),ArrayType(FloatType()))
df = df.withColumn('features1',udf1('features'))

df.select(*[df.features1[i].alias('col_{}'.format(i)) for i in range(1,stop)]).show()
+-----+-----+-----+-----+-----+-----+
|col_1|col_2|col_3|col_4|col_5|col_6|
+-----+-----+-----+-----+-----+-----+
|   45|   63|    0|    0|    0|    0|
|    0|    0|   85|    0|   69|    0|
+-----+-----+-----+-----+-----+-----+
```

Title: Convert Column of List to Dataframe

Body:
I have a column of lists in a spark dataframe.

+-----------------+
|features         |
+-----------------+
|[0,45,63,0,0,0,0]|
|[0,0,0,85,0,69,0]|
|[0,89,56,0,0,0,0]|
+-----------------+

How do I convert that to a spark dataframe where each element in the list is a column in the dataframe? We can assume that the lists will be the same size.

For Example,

+--------------------+
|c1|c2|c3|c4|c5|c6|c7|
+--------------------+
|0 |45|63|0 |0 |0 |0 |
|0 |0 |0 |85|0 |69|0 |
|0 |89|56|0 |0 |0 |0 |
+--------------------+


问:
tcpdump capture on port 80, but apache doesn't responds
I have a problem that I don't understand.
See my configurations, port 80 is Listen on apache:

```<code># grep -Rin Listen /etc/apache2/*
/etc/apache2/ports.conf:5:Listen 80
</code>```

/etc/apache2/sites-enabled/global.conf

```<code><VirtualHost *:80>
        ServerName global.grupoconstruserv.com.br
        DocumentRoot /var/www/global
        LogLevel debug
        ErrorLog /var/log/apache2/global-error.log
        CustomLog /var/log/apache2/global-access.log combined
</VirtualHost>
<Directory /var/www/global/>
    Options FollowSymLinks
    AllowOverride All
    Require all Granted
    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*) index.php/$1 [L]
  </IfModule>

 <IfModule !mod_rewrite.c>
      ErrorDocument 404 /404.php
  </IfModule>

</Directory>
# netstat -an|grep :80
tcp6       0      0 :::80                   :::*                    LISTEN
tcp6       0      0 :::8080                 :::*                    LISTEN
</code>```

Firewall is ok:

```<code># iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
LOG        tcp  --  anywhere             anywhere             tcp dpt:http LOG level warning

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
</code>```

tcpdump capture packts:

```<code># tcpdump -nvvvi ens32 'port 80'
15:55:37.211374 IP (tos 0x0, ttl 55, id 6978, offset 0, flags [DF], proto TCP (6), length 60)
    189.58.39.2.9656 > 192.168.1.12.80: Flags [S], cksum 0x46b1 (correct), seq 848450420, win 29200, options [mss 1452,sackOK,TS val 4134684372 ecr 0,nop,wscale 7], length 0
15:55:38.215987 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 60)
    192.168.1.12.80 > 189.58.39.2.9656: Flags [S.], cksum 0xa61f (incorrect -> 0x03bb), seq 1603885177, ack 848450421, win 28960, options [mss 1460,sackOK,TS val 3782191690 ecr 4134684372,nop,wscale 7], length 0
15:55:38.241102 IP (tos 0x0, ttl 55, id 6979, offset 0, flags [DF], proto TCP (6), length 60)
    189.58.39.2.9656 > 192.168.1.12.80: Flags [S], cksum 0x45af (correct), seq 848450420, win 29200, options [mss 1452,sackOK,TS val 4134684630 ecr 0,nop,wscale 7], length 0
</code>```

But on httping ou browser (on other device) returns timeout:

```<code>httping http://global.grupoconstruserv.com.br:80/ -t2
PING global.grupoconstruserv.com.br:80 (/):
connect time out
</code>```

答:
I found the problem.
I have 2 routes. The packets was IN by one route and OUT by another route,
causing traffic loss.
So I adjusted to OUT to the same route that the packets IN.</p>

Body:
I have a problem that I don't understand.
See my configurations, port 80 is Listen on apache:

# grep -Rin Listen /etc/apache2/*
/etc/apache2/ports.conf:5:Listen 80

/etc/apache2/sites-enabled/global.conf

<VirtualHost *:80>
        ServerName global.grupoconstruserv.com.br
        DocumentRoot /var/www/global
        LogLevel debug
        ErrorLog /var/log/apache2/global-error.log
        CustomLog /var/log/apache2/global-access.log combined
</VirtualHost>
<Directory /var/www/global/>
    Options FollowSymLinks
    AllowOverride All
    Require all Granted
    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*) index.php/$1 [L]
  </IfModule>

 <IfModule !mod_rewrite.c>
      ErrorDocument 404 /404.php
  </IfModule>

</Directory>
# netstat -an|grep :80
tcp6       0      0 :::80                   :::*                    LISTEN
tcp6       0      0 :::8080                 :::*                    LISTEN

Firewall is ok:

# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
LOG        tcp  --  anywhere             anywhere             tcp dpt:http LOG level warning

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

tcpdump capture packts:

# tcpdump -nvvvi ens32 'port 80'
15:55:37.211374 IP (tos 0x0, ttl 55, id 6978, offset 0, flags [DF], proto TCP (6), length 60)
    189.58.39.2.9656 > 192.168.1.12.80: Flags [S], cksum 0x46b1 (correct), seq 848450420, win 29200, options [mss 1452,sackOK,TS val 4134684372 ecr 0,nop,wscale 7], length 0
15:55:38.215987 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 60)
    192.168.1.12.80 > 189.58.39.2.9656: Flags [S.], cksum 0xa61f (incorrect -> 0x03bb), seq 1603885177, ack 848450421, win 28960, options [mss 1460,sackOK,TS val 3782191690 ecr 4134684372,nop,wscale 7], length 0
15:55:38.241102 IP (tos 0x0, ttl 55, id 6979, offset 0, flags [DF], proto TCP (6), length 60)
    189.58.39.2.9656 > 192.168.1.12.80: Flags [S], cksum 0x45af (correct), seq 848450420, win 29200, options [mss 1452,sackOK,TS val 4134684630 ecr 0,nop,wscale 7], length 0

But on httping ou browser (on other device) returns timeout:

httping http://global.grupoconstruserv.com.br:80/ -t2
PING global.grupoconstruserv.com.br:80 (/):
connect time out


问:
Connectivity change in android 7
I m developing an application for targeting android 7 and i m have to do  something on connectivity change. How i can  do this.

Can any one help me with sample code.
Thanks in advance.

答:
As of Android 7 (Nougat) receivers that are registered with the manifest will no longer be called.

You need to register it with

```<code>Context.registerReceiver()
</code>```

Refer to the documentation here

That means that you will need to register for those in your Actviity/Fragment where you need them.

Title: Connectivity change in android 7

Body:
As of Android 7 (Nougat) receivers that are registered with the manifest will no longer be called.

You need to register it with

Context.registerReceiver()

Refer to the documentation here

That means that you will need to register for those in your Actviity/Fragment where you need them.


问:
Javascript compare arrays to mark occurrences of a specific element
I have an array that contains n arrays that hold a car information (color, company) as follows:

el[0] -> color value

el[1] -> company value

My goal is to show for how many car companies a color can be found.

For example this array

```<code>var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];
</code>```

Should be changed as follows:

```<code> result = [
  ['red', 'Ford', '3: Ford, Renault, Opel'],
  ['blue', 'Ford', '2: Ford, Renault'],
  ['green', 'Ford', '2: Ford, Open'],
  ['red', 'Renault', '3: Ford, Renault, Opel'],
  ['blue', 'Renault', '2: Ford, Renault'],
  ['green', 'Opel', '2: Ford, Opel'],
  ['red', 'Opel', '3: Ford, Renault, Opel']
 ];
</code>```

Explanation:

There are 3 companies having the red color: Ford, Renault, Opel

There are 2 companies having the blue color: Ford, Renault

There are 2 companies having the green color: Ford, Opel

This is how I think it can be solved, but I'm not sure if it's the right approach:

1. Loop through each array and filter the color to get all companies that apply to it

2. Loop through the filter response and remove the duplicates

3. Loop again through the main array and assign the result from step 2 to the corresponding array that has the filtered color

答:
You can build an associative array-like object where you store a list of car by color. You can then map the original array by changing it's elements by using the associative-array-like object:

var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];

var map = array.reduce((map, row) => {
    map[row[0]] = map[row[0]] || [];
    if (!map[row[0]].includes(row[1])) {
        map[row[0]].push(row[1]);
    }
    return map;
}, {});

var result = array.map(row => (row.push(`${map[row[0]].length}: ${map[row[0]].join(', ')}`), row));

console.log(result);```
</div>
</div>
</p>

<p>In a more readable way:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];

var map = array.reduce((map, row) => {
    var [ color, car ] = row;
    map[color] = map[color] || [];
    if (!map[color].includes(car)) {
        map[color].push(car);
    }
    return map;
}, {});

var result = array.map(row => {
    var [ color, car ] = row;
    row.push(`${map[color].length}: ${map[color].join(', ')}`);
    return row;
});

console.log(result);</code>```

Body:
I have an array that contains n arrays that hold a car information (color, company) as follows:

el[0] -> color value

el[1] -> company value

My goal is to show for how many car companies a color can be found.

For example this array

var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];

Should be changed as follows:

 result = [
  ['red', 'Ford', '3: Ford, Renault, Opel'],
  ['blue', 'Ford', '2: Ford, Renault'],
  ['green', 'Ford', '2: Ford, Open'],
  ['red', 'Renault', '3: Ford, Renault, Opel'],
  ['blue', 'Renault', '2: Ford, Renault'],
  ['green', 'Opel', '2: Ford, Opel'],
  ['red', 'Opel', '3: Ford, Renault, Opel']
 ];

Explanation:

There are 3 companies having the red color: Ford, Renault, Opel

There are 2 companies having the blue color: Ford, Renault

There are 2 companies having the green color: Ford, Opel

This is how I think it can be solved, but I'm not sure if it's the right approach:

1. Loop through each array and filter the color to get all companies that apply to it

2. Loop through the filter response and remove the duplicates

3. Loop again through the main array and assign the result from step 2 to the corresponding array that has the filtered color

Body:
You can build an associative array-like object where you store a list of car by color. You can then map the original array by changing it's elements by using the associative-array-like object:

var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];

var map = array.reduce((map, row) => {
    map[row[0]] = map[row[0]] || [];
    if (!map[row[0]].includes(row[1])) {
        map[row[0]].push(row[1]);
    }
    return map;
}, {});

var result = array.map(row => (row.push(`${map[row[0]].length}: ${map[row[0]].join(', ')}`), row));

console.log(result);

In a more readable way:

var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];

var map = array.reduce((map, row) => {
    var [ color, car ] = row;
    map[color] = map[color] || [];
    if (!map[color].includes(car)) {
        map[color].push(car);
    }
    return map;
}, {});

var result = array.map(row => {
    var [ color, car ] = row;
    row.push(`${map[color].length}: ${map[color].join(', ')}`);
    return row;
});

console.log(result);


问:
import data and indexes in microsoft sql server
I am transfering data from one server to another using microsoft sql server management studio. Every time I import data from another server, it doesnt come with the indexes and constraints, it just transfers the data without importing the indexes for the table, How do I import both the data and the indexes?</p>

答:
First set the Script Indexes to true in below location.

```<code>SSMS-->Tools-->Options-->SQL Server Object Explorer-->Scripting-->Script Indexes.
</code>```

Try generating the script again by, right clicking on the table and choose "Script Table as" to generate the script

You can also export by right clicking on the database-->Tasks and choose generate scripts.

Let me know if you still face any issues.

Body:
First set the Script Indexes to true in below location.

SSMS-->Tools-->Options-->SQL Server Object Explorer-->Scripting-->Script Indexes.

Try generating the script again by, right clicking on the table and choose "Script Table as" to generate the script

You can also export by right clicking on the database-->Tasks and choose generate scripts.

Let me know if you still face any issues.


问:
mockito when method returns null in junit
I have been writing the test cases using the mockito. the below is my code in the test cases.

```<code>@RunWith(SpringRunner.class)
public class LoginControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    private LoginService loginService;

    @Mock
    private LoginController loginController;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        // Setup Spring test in standalone mode
        mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();

    }

    @Test
    public final void test() throws Exception {

        // Assign
        when(loginService.test()).thenReturn("hello");

        // act
        mockMvc.perform(get("/hello"))
                // Assertion
                .andExpect(status().isOk())
                .andExpect(content().string("Message from service: hello"));
        verify(loginService).test();
    }

    @Test
    public final void usernameInvalidAndPassword() throws Exception {

        User userData = new User();
        userData.setUserName("akhila.s@cloudium.io");
        userData.setPassword("Passw0rd");

        User userDataNew = new User();
        userDataNew.setUserName("akhila.s@cloudium.io");
        userDataNew.setPassword("Passw0rd");

        JSONObject requestBody = new JSONObject();

        requestBody.put("userName", "akhila.s@cloudium.io");
        requestBody.put("password", "Passw0rd");

        JSONObject responseBody = new JSONObject();

        responseBody.put("status_code", "200");
        responseBody.put("message", "ok");

        // Assign
        when(loginService.saveUser(userData)).thenReturn(userDataNew);

        // act
        mockMvc.perform(get("/login")
                .param("userName", "akhila.s@cloudium.io")
                .param("password", "Passw0rd"))
                // Assertion
                .andExpect(status().isOk()).andExpect(content().json(responseBody.toString())).andDo(print());
    }
</code>```

For the first test case its working fine but for the second test it is returning null always. Can anyone  please help? Thanks in advance

答:
In my opinion you have to either:

1) Introduce equals method based on username and password as the User object created inside the method under test is a different instance than the one you create and use in the test.

2) Use a wildcard in your set-up:

```<code>when(loginService.saveUser(Mockito.any(User.class))).thenReturn(userDataNew);
</code>```

Body:
I have been writing the test cases using the mockito. the below is my code in the test cases.

@RunWith(SpringRunner.class)
public class LoginControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    private LoginService loginService;

    @Mock
    private LoginController loginController;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        // Setup Spring test in standalone mode
        mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();

    }

    @Test
    public final void test() throws Exception {

        // Assign
        when(loginService.test()).thenReturn("hello");

        // act
        mockMvc.perform(get("/hello"))
                // Assertion
                .andExpect(status().isOk())
                .andExpect(content().string("Message from service: hello"));
        verify(loginService).test();
    }

    @Test
    public final void usernameInvalidAndPassword() throws Exception {

        User userData = new User();
        userData.setUserName("akhila.s@cloudium.io");
        userData.setPassword("Passw0rd");

        User userDataNew = new User();
        userDataNew.setUserName("akhila.s@cloudium.io");
        userDataNew.setPassword("Passw0rd");

        JSONObject requestBody = new JSONObject();

        requestBody.put("userName", "akhila.s@cloudium.io");
        requestBody.put("password", "Passw0rd");

        JSONObject responseBody = new JSONObject();

        responseBody.put("status_code", "200");
        responseBody.put("message", "ok");

        // Assign
        when(loginService.saveUser(userData)).thenReturn(userDataNew);

        // act
        mockMvc.perform(get("/login")
                .param("userName", "akhila.s@cloudium.io")
                .param("password", "Passw0rd"))
                // Assertion
                .andExpect(status().isOk()).andExpect(content().json(responseBody.toString())).andDo(print());
    }

For the first test case its working fine but for the second test it is returning null always. Can anyone  please help? Thanks in advance

Body:
In my opinion you have to either:

1) Introduce equals method based on username and password as the User object created inside the method under test is a different instance than the one you create and use in the test.

2) Use a wildcard in your set-up:

when(loginService.saveUser(Mockito.any(User.class))).thenReturn(userDataNew);


问:
Create Dynamic Proxies objects
Is there a way to create WCF proxy objects on the fly without using codedom? By on the fly I mean during runtime. So lets say I have a smart client application that is accessing a WCF service. The Data Contract for the WCF service is changed while the client is running. I want to dynamically create a new proxy object that reflects the changed data contract.</p>

答:
I came up with a solution, using a shared assembly for contracts and endpoint interfaces.

So The Projects Would Be

Host

Contacts & Endpoints

Client With Proxy

public class YourProxy : ClientBase {}

OwnerDisplayName: CoderGuy

Title: Create Dynamic Proxies objects

LastEditorDisplayName: CoderGuy

OwnerDisplayName: Elroy


问:
Magento: How to show only products with a custom binary attribute
I created some custom attributes for my Products in the backend, put together in a single attribute set. Attributes are like:

"Can be used to fill holes in teeth"
"Can be used to to cover up fillings"
"Is absorbable"

All of those attributes are of the "yes/no" kind.

I made all of them searchable, yet when I search for "fillings" or "teeth" or whatever they have as a text, no product is found, even so I have one product which has all of these attributes attached and all of them set to "yes".

How would I go about if I wanted to have a link that displayed me all products that, say, had "is absorbable" set to "yes"?

答:
I know this has an answer but I solved this like this:

1) Create a category for the yes/no attribute but hidden from the navigation (You can set it to show in the layered navigation if you want to)
2) Add your products that have Yes in the attribute to this category.
2) Create a URL mapping to this category (Optional). Example /mycategory.html
3) Create a search term for the attribute and put the new URL mapping in the redirect page field.

I have for example a Yes/No attribute for Waterproof. My Search term is waterproof and redirects to my URL mapping of my hidden category.

Then, when someone searches for the name of the attribute it will redirect them to the category which will basically be an advanced search but customers can reach it not only from a link but from a search.

Good luck


问:
Unable to use mysqldb in Python2 virtualenv on Fedora 27
My Python app that works on Fedora 26, does not work on Fedora 27.

I get this error:

```<code>ImportError: libmysqlclient.so.18: cannot open shared object file: No such file or directory
</code>```

I have created a new virtualenv after upgrading to Fedora 26. mariadb-devel is installed.

答:
Try to reinstall MySQL-python using this:</p>

```<code>sudo python -m pip install --no-binary MySQL-python MySQL-python
</code>```

Body:
My Python app that works on Fedora 26, does not work on Fedora 27.

I get this error:

ImportError: libmysqlclient.so.18: cannot open shared object file: No such file or directory

I have created a new virtualenv after upgrading to Fedora 26. mariadb-devel is installed.

Body:
Try to reinstall MySQL-python using this:

sudo python -m pip install --no-binary MySQL-python MySQL-python


问:
Unable to remove on-premise database from Azure Sync Group
The on-prem database within the Sql Data Sync software is at status 'reachable'. I submit an agent key obtained from the portal, in which test is successful, then click Unregister for one of the databases. I click Yes I'm sure, and presented with this error:

How do I unregister databases?

答:
Ok, the reason seems to be that you can't unregister a database when it's still involved in sync setup, as seen below:

Go into the sync group and Delete it first.


问:
How to parse a firebase real time database
How I can parse firebase realtime database?

So far my code is:

```<code>var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("data").observe(.childAdded) { (snapshot) in
   print("snapshot = \(snapshot)")
}
</code>```

I can not enter the condition.

```<code>print("url = \(ref.url)")
url = "https://gdenamaz.firebaseio.com"
</code>```

this variant don't work too

```<code>var ref: DatabaseReference!
    ref = Database.database().reference().child("data")

    ref.observeSingleEvent(of: .value) { (snapshot) in
        for data in snapshot.children {
            print("data = \(data)")
        }
    }
</code>```

答:
To reference the official docs -

```<code>refHandle = postRef.observe(DataEventType.value, with: { (snapshot) in
  let postDict = snapshot.value as? [String : AnyObject] ?? [:]
  // ...
})
</code>```

You want to be looking for the snapshot.value not snapshot.children

A further example

```<code>let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
  // Get user value
  let value = snapshot.value as? NSDictionary
  let username = value?["username"] as? String ?? ""
  let user = User(username: username)

  // ...
  }) { (error) in
    print(error.localizedDescription)
}
</code>```

also, .childAdded will only trigger when a child is added. IE, nothing will happen until you actually change something in that node reference.

Body:
How I can parse firebase realtime database?

So far my code is:

var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("data").observe(.childAdded) { (snapshot) in
   print("snapshot = \(snapshot)")
}

I can not enter the condition.

print("url = \(ref.url)")
url = "https://gdenamaz.firebaseio.com"

this variant don't work too

var ref: DatabaseReference!
    ref = Database.database().reference().child("data")

    ref.observeSingleEvent(of: .value) { (snapshot) in
        for data in snapshot.children {
            print("data = \(data)")
        }
    }

Body:
To reference the official docs -

refHandle = postRef.observe(DataEventType.value, with: { (snapshot) in
  let postDict = snapshot.value as? [String : AnyObject] ?? [:]
  // ...
})

You want to be looking for the snapshot.value not snapshot.children

A further example

let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
  // Get user value
  let value = snapshot.value as? NSDictionary
  let username = value?["username"] as? String ?? ""
  let user = User(username: username)

  // ...
  }) { (error) in
    print(error.localizedDescription)
}

also, .childAdded will only trigger when a child is added. IE, nothing will happen until you actually change something in that node reference.


问:
Overwrite images when clicked
I'm developing a site for buying clothes. I need to create a product that, on clicking in the pocket image, change immediately in the preview. How can I do that? I am using Angular 2

Example of how I want to do

答:
```<code><img [src]="imageUrl">
<button (click)="imageUrl='http://example.com/path/image1.png'">Image 1</button>
<button (click)="imageUrl='http://example.com/path/image2.png'">Image 2</button>
<button (click)="imageUrl='http://example.com/path/image3.png'">Image 3</button>
</code>```

```<code>export class MyComponent {
  imageUrl:string;
}
</code>```

Title: Overwrite images when clicked

Body:
<img [src]="imageUrl">
<button (click)="imageUrl='http://example.com/path/image1.png'">Image 1</button>
<button (click)="imageUrl='http://example.com/path/image2.png'">Image 2</button>
<button (click)="imageUrl='http://example.com/path/image3.png'">Image 3</button>

export class MyComponent {
  imageUrl:string;
}


答:
You could take a double loop approach with a hash table for collecting the second element of the array.

var array = [['red', 'Ford'], ['blue', 'Ford'], ['green', 'Ford'], ['red', 'Ford'], ['red', 'Renault'], ['blue', 'Renault'], ['green', 'Opel'], ['red', 'Opel']],
    hash = Object.create(null);

array.forEach(function (a) {
    hash[a[0]] = hash[a[0]] || {};
    hash[a[0]][a[1]] = true;
});
array.forEach(function (a, i, aa) {
    var keys = Object.keys(hash[a[0]]);
    aa[i][2] = keys.length + ': ' + keys.join(', ');
});

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Javascript compare arrays to mark occurrences of a specific element

Body:
You could take a double loop approach with a hash table for collecting the second element of the array.

var array = [['red', 'Ford'], ['blue', 'Ford'], ['green', 'Ford'], ['red', 'Ford'], ['red', 'Renault'], ['blue', 'Renault'], ['green', 'Opel'], ['red', 'Opel']],
    hash = Object.create(null);

array.forEach(function (a) {
    hash[a[0]] = hash[a[0]] || {};
    hash[a[0]][a[1]] = true;
});
array.forEach(function (a, i, aa) {
    var keys = Object.keys(hash[a[0]]);
    aa[i][2] = keys.length + ': ' + keys.join(', ');
});

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Justify the last line of a div?
I don't think the "why?" of this question is important...but what I need to do is to text-align:justify the last line of text from a DIV. Normally, the last line (or the first if there are no other lines, which is the current case) of a div isn't justified, but aligned left. I know it might not make sense at all, but I absolutely need the last line to be justified!

答:
Let's say I'm working with divs that "for some reason" (there is one pretty good reason) can only have one line....and I want to justify them.

Why don't you use text-align: justify;? It does justify every line. Even if there is just one line.

Edit: I think you are looking for this, as scragz said. Anyway, this works only in IE 5.5 and IE 6.

Title: Justify the last line of a div?


问:
how to move div scroll position based on button click in angular 2
in app.component.html file i have one div element with horizontal scroll and two buttons as Next and Previous. based on these button click i want to move scroll.

app.component.html

```<code><div id="th-infinite-scroll-tracker" style="overflow-y:scroll; height: 200px;" scrollTracker (scroll)="onScroll($event)" (mouseup)="searchLog($event)">
        <div *ngFor="let log of arr; let i = index" innerHTML="{{log}}" [id]="i"></div>
</div>
<button (click)="onPreviousSearchPosition()" [disabled]="disablePreviousBtn">Previous</button>
<button (click)="onNextSearchPosition()" [disabled]="disableNextBtn">Next</button>
</code>```

app.component.ts

```<code>@HostListener('scroll', ['$event'])
onScroll(event){
    this.scrollObject = event;
}
onPreviousSearchPosition(){
    this.disableNextBtn = false;

    this.scrollObject.target.scrollTop = 20 * --this.idCount;
  }
onPreviousNextPosition(){
    this.disableNextBtn = false;

    this.scrollObject.target.scrollTop = 20 * ++this.idCount;
  }
</code>```

using above code we can move the scroll but we need scroll event object which will get after scrolling manually.
Please suggest me, how to create scroll event object in component class

答:
I would prefer to use scrollIntoView() method. This method provides smooth scrolling transition effect in the browser when we click on the corresponding element.

```<code>    @Component({
    selector: 'my-app',
    template: `
      <div #panel class="some-class">
        <div *ngFor="let log of arr; let i = index" innerHTML="{{log}}" [id]="i"></div>
      </div>
      <button (click)="moveToSpecificView()">Move</button>
    `
})
export class AppComponent {
    public arr = ['foo', 'bar', 'baz'];
    @ViewChild('panel') public panel:ElementRef;

    public moveToSpecificView()(): void {
        setTimeout(() => {
            this.panel.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
        });
    }

  }
</code>```

Body:
in app.component.html file i have one div element with horizontal scroll and two buttons as Next and Previous. based on these button click i want to move scroll.

app.component.html

<button (click)="onPreviousSearchPosition()" [disabled]="disablePreviousBtn">Previous</button>
<button (click)="onNextSearchPosition()" [disabled]="disableNextBtn">Next</button>

app.component.ts

@HostListener('scroll', ['$event'])
onScroll(event){
    this.scrollObject = event;
}
onPreviousSearchPosition(){
    this.disableNextBtn = false;

    this.scrollObject.target.scrollTop = 20 * --this.idCount;
  }
onPreviousNextPosition(){
    this.disableNextBtn = false;

    this.scrollObject.target.scrollTop = 20 * ++this.idCount;
  }

using above code we can move the scroll but we need scroll event object which will get after scrolling manually.
Please suggest me, how to create scroll event object in component class

Body:
I would prefer to use scrollIntoView() method. This method provides smooth scrolling transition effect in the browser when we click on the corresponding element.

    @Component({
    selector: 'my-app',
    template: `
      <div #panel class="some-class">
        <div *ngFor="let log of arr; let i = index" innerHTML="{{log}}" [id]="i"></div>
      </div>
      <button (click)="moveToSpecificView()">Move</button>
    `
})
export class AppComponent {
    public arr = ['foo', 'bar', 'baz'];
    @ViewChild('panel') public panel:ElementRef;

    public moveToSpecificView()(): void {
        setTimeout(() => {
            this.panel.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
        });
    }

  }

ContentLicense: CC BY-SA 4.0


问:
Does SQL Server 2008 R2 play nice with VS2010?
I know from firsthand experience that if you wanted to install both SQL Server 2008 and Visual Studio 2008 on the same machine, you had to jump through all sorts of service packs and installation orders to ensure that both programs ran properly.

In my case, I have VS 2010 installed on my PC currently, and find I'm in need of the SQL Enterprise Manager, which is not included from the Visual Studio installation. What, if anything, do I need to do before installing SQL Server 2008 R2?

Related question: Does it matter which sub-version of SQL Server I install? (Thanks to my University connection, I have my pick between Developer, Enterprise, Standard, and Web; is one preferred in my case?)

答: Install SQL Server before Visual Studio 2010, if for no reason other than avoiding accidentally installing SQL Server Express during the VS installer. I'd also recommend using the Developer edition of SQL Server since that's what it's designed for</p>


问:
Losing session data in ASP.NET
I moved an ASP.NET site running on a server with .NET 1.1 to another server running with .NET 2.0.

In one of the pages I have the following code to detect an expired session:

```<code>  protected void Page_Init(object sender, System.EventArgs e) {

    if ( Session["XBCPEmail"] == null ) {
      Response.Redirect("signin.aspx?expired=yes");
      return;
    }
  }
</code>```

(Session["XBCPEmail"] == null) is resolving as true (as if the session had expired) in one unexpected case, after clicking one of the buttons of the page.  It happens with only one of the buttons.  Just like other buttons in the same page, the button event handler ends with this code redirecting to the same page:

```<code>Response.Redirect("cpanel.aspx");
</code>```

I checked and at the time of Response.Redirect("cpanel.aspx"); the value of (string)Session["XBCPEmail"] is a valid string, so I'm not sure what can happen between the Response.Redirect and the Page_Init that could be making the Session["XBCPEmail"] become null.

Which could make a Session variable in .NET 2.0 become null?  This code does not have that issue in 1.1 and, even in 2.0, it only affects one button on the page.

UPDATE: The issue only occurs if the button event handler calls an external .exe program, with the code below.  If this code is commented out, the Session variable is not null.  How can the creation of an external process to run a command line program have any impact on if a Session variable is null or not?

```<code>private string CallBridge3(string task, string arg1, string arg2, string arg3) {

    Process process = new Process();

    process.StartInfo.FileName = MapPath("bridgefcp.exe");
    process.StartInfo.Arguments = "-" + task + " \"" + arg1 + "\" \"" + arg2 + "\" \"" + arg3 + "\"";
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.UseShellExecute = false;

    process.Start();

    string output = process.StandardOutput.ReadToEnd();
    process.WaitForExit();
    return output;
  }
</code>```

UPDATE 2:  The problem has vanished after installing .NET 4.5 on the Windows 2008 R2 with IIS 7.5 machine, instead of using the one that came by default, which was .NET 2.0.

答:
```<code><httpCookies requireSSL="false" />
</code>```

Removing this from the local web.config worked for me. The issue was only happening when running the app locally.

Removed the setting from web.config

Added it to the web.staging.config and web.production.config

Title: Losing session data in ASP.NET

Body:
I moved an ASP.NET site running on a server with .NET 1.1 to another server running with .NET 2.0.

In one of the pages I have the following code to detect an expired session:

  protected void Page_Init(object sender, System.EventArgs e) {

    if ( Session["XBCPEmail"] == null ) {
      Response.Redirect("signin.aspx?expired=yes");
      return;
    }
  }

(Session["XBCPEmail"] == null) is resolving as true (as if the session had expired) in one unexpected case, after clicking one of the buttons of the page.  It happens with only one of the buttons.  Just like other buttons in the same page, the button event handler ends with this code redirecting to the same page:

Response.Redirect("cpanel.aspx");

I checked and at the time of Response.Redirect("cpanel.aspx"); the value of (string)Session["XBCPEmail"] is a valid string, so I'm not sure what can happen between the Response.Redirect and the Page_Init that could be making the Session["XBCPEmail"] become null.

Which could make a Session variable in .NET 2.0 become null?  This code does not have that issue in 1.1 and, even in 2.0, it only affects one button on the page.

UPDATE: The issue only occurs if the button event handler calls an external .exe program, with the code below.  If this code is commented out, the Session variable is not null.  How can the creation of an external process to run a command line program have any impact on if a Session variable is null or not?

private string CallBridge3(string task, string arg1, string arg2, string arg3) {

    Process process = new Process();

    process.StartInfo.FileName = MapPath("bridgefcp.exe");
    process.StartInfo.Arguments = "-" + task + " \"" + arg1 + "\" \"" + arg2 + "\" \"" + arg3 + "\"";
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.UseShellExecute = false;

    process.Start();

    string output = process.StandardOutput.ReadToEnd();
    process.WaitForExit();
    return output;
  }

UPDATE 2:  The problem has vanished after installing .NET 4.5 on the Windows 2008 R2 with IIS 7.5 machine, instead of using the one that came by default, which was .NET 2.0.

Body:
<httpCookies requireSSL="false" />

Removing this from the local web.config worked for me. The issue was only happening when running the app locally.

Removed the setting from web.config

Added it to the web.staging.config and web.production.config


问:
How can I use mongoose $lookup operator for lookup chaining and then grouping the result?
Lets consider I have three pseudo collections like following

users:

```<code>{ "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"), "uid" : 1234,
     "name" : "ashish", "email" : "info@gmail.com" },
{ "_id" : ObjectId("5a2a2c51cf7961800e44dfca"), "uid" : 1235,
     "name" : "swapnil", "email" : "info@femail.com" }
</code>```

bank_details:

```<code>{ "_id" : ObjectId("5a2a2c9bcf7961800e44dfcb"), "uid" : 1234, "acc_no" : 1111 },
{ "_id" : ObjectId("5a2a2cc9cf7961800e44dfcc"), "uid" : 1234, "acc_no" : 2222 },
{ "_id" : ObjectId("5a2a2cd7cf7961800e44dfcd"), "uid" : 1235, "acc_no" : 3333 },
{ "_id" : ObjectId("5a2a2cdccf7961800e44dfce"), "uid" : 1235, "acc_no" : 4444 }
</code>```

bank

```<code>{ "_id" : ObjectId("5a2a2d05cf7961800e44dfcf"), "acc_no" : 1111, "balance" : 100 },
{ "_id" : ObjectId("5a2a2d10cf7961800e44dfd0"), "acc_no" : 2222, "balance" : 200 },
{ "_id" : ObjectId("5a2a2d19cf7961800e44dfd1"), "acc_no" : 3333, "balance" : 300 },
{ "_id" : ObjectId("5a2a2d21cf7961800e44dfd2"), "acc_no" : 4444, "balance" : 400 }
</code>```

I wanna have output as following

```<code>{ "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"), "uid" : "1234",
  "name" : "ashish", "email" : "info@gmail.com" ,
bank_details: [{
  acc_no:'1111',
  balance:'100'
},{
  acc_no:'2222',
  balance:'200'
}]}
</code>```

for each profile of user, I'm sure this can be done using $lookup and $group operator but I could never achieve it, I have tried to do this using several ways. Can anybody please write a sample query for the required result.

I'm trying to write the query using mongoose in NodeJs

答:
You can do that using two lookups and grouping. Check out the following query:

```<code>db.getCollection('users').aggregate([{
  $lookup:
    {
      from: "bank_details",
      localField: "uid",
      foreignField: "uid",
      as: "bank_details"
    }
},
{   $unwind:{ path: "$bank_details", preserveNullAndEmptyArrays: true }},
{
    $lookup:{
        from: "bank",
        localField: "bank_details.acc_no",
        foreignField: "acc_no",
        as: "banks"
    }
},
{ $unwind: { path: "$banks", preserveNullAndEmptyArrays: true } },
{
    $group: {
        _id: "$_id",
        uid: {$first: "$uid"},
        name: {$first: "$name"},
        email: {$first: "$email"},
        bank_details: {$push: {acc_no: "$banks.acc_no", balance: "$banks.balance"}}
        }
    },
{
   "$project": {
      uid: 1,
      name: 1,
      email: 1,
      bank_details: { "$setDifference": [ "$bank_details", [{}, null] ] }
   }
}
])
</code>```

Results:

```<code>/* 1 */
{
"_id" : ObjectId("5a2a2c51cf7961800e44dfca"),
"uid" : 1235.0,
"name" : "swapnil",
"email" : "info@femail.com",
"bank_details" : [
    {
        "acc_no" : 3333.0,
        "balance" : 300.0
    },
    {
        "acc_no" : 4444.0,
        "balance" : 400.0
    }
]
}

/* 2 */
{
"_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"),
"uid" : 1234.0,
"name" : "ashish",
"email" : "info@gmail.com",
"bank_details" : [
    {
        "acc_no" : 1111.0,
        "balance" : 100.0
    },
    {
        "acc_no" : 2222.0,
        "balance" : 200.0
    }
 ]
}
</code>```

Body:
Lets consider I have three pseudo collections like following

users:

{ "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"), "uid" : 1234,
     "name" : "ashish", "email" : "info@gmail.com" },
{ "_id" : ObjectId("5a2a2c51cf7961800e44dfca"), "uid" : 1235,
     "name" : "swapnil", "email" : "info@femail.com" }

bank_details:

{ "_id" : ObjectId("5a2a2c9bcf7961800e44dfcb"), "uid" : 1234, "acc_no" : 1111 },
{ "_id" : ObjectId("5a2a2cc9cf7961800e44dfcc"), "uid" : 1234, "acc_no" : 2222 },
{ "_id" : ObjectId("5a2a2cd7cf7961800e44dfcd"), "uid" : 1235, "acc_no" : 3333 },
{ "_id" : ObjectId("5a2a2cdccf7961800e44dfce"), "uid" : 1235, "acc_no" : 4444 }

bank

{ "_id" : ObjectId("5a2a2d05cf7961800e44dfcf"), "acc_no" : 1111, "balance" : 100 },
{ "_id" : ObjectId("5a2a2d10cf7961800e44dfd0"), "acc_no" : 2222, "balance" : 200 },
{ "_id" : ObjectId("5a2a2d19cf7961800e44dfd1"), "acc_no" : 3333, "balance" : 300 },
{ "_id" : ObjectId("5a2a2d21cf7961800e44dfd2"), "acc_no" : 4444, "balance" : 400 }

I wanna have output as following

{ "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"), "uid" : "1234",
  "name" : "ashish", "email" : "info@gmail.com" ,
bank_details: [{
  acc_no:'1111',
  balance:'100'
},{
  acc_no:'2222',
  balance:'200'
}]}

for each profile of user, I'm sure this can be done using $lookup and $group operator but I could never achieve it, I have tried to do this using several ways. Can anybody please write a sample query for the required result.

I'm trying to write the query using mongoose in NodeJs

Body:
You can do that using two lookups and grouping. Check out the following query:

db.getCollection('users').aggregate([{
  $lookup:
    {
      from: "bank_details",
      localField: "uid",
      foreignField: "uid",
      as: "bank_details"
    }
},
{   $unwind:{ path: "$bank_details", preserveNullAndEmptyArrays: true }},
{
    $lookup:{
        from: "bank",
        localField: "bank_details.acc_no",
        foreignField: "acc_no",
        as: "banks"
    }
},
{ $unwind: { path: "$banks", preserveNullAndEmptyArrays: true } },
{
    $group: {
        _id: "$_id",
        uid: {$first: "$uid"},
        name: {$first: "$name"},
        email: {$first: "$email"},
        bank_details: {$push: {acc_no: "$banks.acc_no", balance: "$banks.balance"}}
        }
    },
{
   "$project": {
      uid: 1,
      name: 1,
      email: 1,
      bank_details: { "$setDifference": [ "$bank_details", [{}, null] ] }
   }
}
])

Results:

/* 1 */
{
"_id" : ObjectId("5a2a2c51cf7961800e44dfca"),
"uid" : 1235.0,
"name" : "swapnil",
"email" : "info@femail.com",
"bank_details" : [
    {
        "acc_no" : 3333.0,
        "balance" : 300.0
    },
    {
        "acc_no" : 4444.0,
        "balance" : 400.0
    }
]
}

/* 2 */
{
"_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"),
"uid" : 1234.0,
"name" : "ashish",
"email" : "info@gmail.com",
"bank_details" : [
    {
        "acc_no" : 1111.0,
        "balance" : 100.0
    },
    {
        "acc_no" : 2222.0,
        "balance" : 200.0
    }
 ]
}


问:
JavaFX GUI thread and locked screen on Windows
I have my JavaFx application that reads data from API on background thread ( or for testing it is preloaded from local storage on application start ) and then it processes and sets data to model that is directly binded on properties in my view. Because processing and setting data to model changes text shown in components, it is called with Platform.runLater(). Normally when it is called it consumes around 2% of CPU, but if i run application for longer time, consumption of CPU on data processing goes higher a little bit(probably data processing is too much for GUI thread). It gets for example around +4% in 1 hour.

However what I see as strange behaviour is that when i lock my Windows and go away for few minutes and then come back, CPU usage on data processing changes from 8% to 17% for example and then stays that high. Does it mean that when Windows screen is locked then GUI thread doesn't run? It seems to me like not and then when it unlocks, GUI thread gets overwhelmed byPlatform.runLater() calls. But when it is not processing data, it consumes 0% of CPU, so i'm really confused.

Does anyone know what could cause this? Does GUI thread really stops working when windows are locked?

EDIT:

I've already found that processing received data is probably too intensive task for UI thread and I'm trying to optimize it (do most of processing on background thread and then just call setting data with Platform.runLater.
Code for background download is really simple PoF at this moment and looks like this:

```<code>    Thread updateDaemon = new Thread(() -> {
      try {
        while (true) {
          TimeUnit.SECONDS.sleep(5);
            processMarketStateData(view.getTable(), data);
          }
        }
      }
      catch (InterruptedException e) {
        logger.error("Background worker interrupted", e);
      }
    });
    updateDaemon.setDaemon(true);
    updateDaemon.start();
</code>```

In processMarketStateData i do some processing and then set data to model on UI thread. But what i'm actually curious about is that strange CPU usage behaviour. When update thread is sleeping and i do not interact with UI then CPU usage is 0%. When processMarketStateData it takes few % of CPU and then it is again 0% till update thread ends its sleep. But for some strange reason after several processMarketStateData calls CPU usage goes up more and more. I goes up by small percentage, like 1% after 50 calls, maybe more. Even weirder is it takes way less calls to produce this strange behaviour when windows screen is locked. When it goes really insane and it takes already around 20% of CPU for call, it goes that high only on processMarketStateData call, for rest of the time it is 0%. After really long ( few hours ) test i ended up in state where application took 25% of CPU permanently and UI was inresponsive. Note that there are 2 these threads running at same time.

My actual question is not "why my ui lags when i process data", that was not hard to find, but it is "why it acts the way it does?"
I hope this edit made my question better.

EDIT2: Another strange behaviour as well is that if I leave application minimalized for a while with auto updating and open it then, it is black window for a while, but application that doesn't have auto update is ok. This really makes me think that javaFX UI thread doesn't run when application is minimalized or windows screen is locked. Sadly i could not find much about this.

答:
probly  these links may help you
Execute task in background in JavaFX
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm
https://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm

This may be you are doing a cpu intensive task in UI thread . please provide some code samples.

you can use a service class to do the cpu intensive calculation and then update the ui in the plateform.runlater call.

Body:
I have my JavaFx application that reads data from API on background thread ( or for testing it is preloaded from local storage on application start ) and then it processes and sets data to model that is directly binded on properties in my view. Because processing and setting data to model changes text shown in components, it is called with Platform.runLater(). Normally when it is called it consumes around 2% of CPU, but if i run application for longer time, consumption of CPU on data processing goes higher a little bit(probably data processing is too much for GUI thread). It gets for example around +4% in 1 hour.

However what I see as strange behaviour is that when i lock my Windows and go away for few minutes and then come back, CPU usage on data processing changes from 8% to 17% for example and then stays that high. Does it mean that when Windows screen is locked then GUI thread doesn't run? It seems to me like not and then when it unlocks, GUI thread gets overwhelmed byPlatform.runLater() calls. But when it is not processing data, it consumes 0% of CPU, so i'm really confused.

Does anyone know what could cause this? Does GUI thread really stops working when windows are locked?

EDIT:

I've already found that processing received data is probably too intensive task for UI thread and I'm trying to optimize it (do most of processing on background thread and then just call setting data with Platform.runLater.
Code for background download is really simple PoF at this moment and looks like this:

    Thread updateDaemon = new Thread(() -> {
      try {
        while (true) {
          TimeUnit.SECONDS.sleep(5);
            processMarketStateData(view.getTable(), data);
          }
        }
      }
      catch (InterruptedException e) {
        logger.error("Background worker interrupted", e);
      }
    });
    updateDaemon.setDaemon(true);
    updateDaemon.start();

In processMarketStateData i do some processing and then set data to model on UI thread. But what i'm actually curious about is that strange CPU usage behaviour. When update thread is sleeping and i do not interact with UI then CPU usage is 0%. When processMarketStateData it takes few % of CPU and then it is again 0% till update thread ends its sleep. But for some strange reason after several processMarketStateData calls CPU usage goes up more and more. I goes up by small percentage, like 1% after 50 calls, maybe more. Even weirder is it takes way less calls to produce this strange behaviour when windows screen is locked. When it goes really insane and it takes already around 20% of CPU for call, it goes that high only on processMarketStateData call, for rest of the time it is 0%. After really long ( few hours ) test i ended up in state where application took 25% of CPU permanently and UI was inresponsive. Note that there are 2 these threads running at same time.

My actual question is not "why my ui lags when i process data", that was not hard to find, but it is "why it acts the way it does?"
I hope this edit made my question better.

EDIT2: Another strange behaviour as well is that if I leave application minimalized for a while with auto updating and open it then, it is black window for a while, but application that doesn't have auto update is ok. This really makes me think that javaFX UI thread doesn't run when application is minimalized or windows screen is locked. Sadly i could not find much about this.


问:
Merge two DataFrames and aggregate matching columns
I have two dataframes with unique ids and matching columns like these:

```<code>df1 = pd.DataFrame({"ID" : [1,2,3], "Col1": [12,7,4], "Col2": [1,7,2]})

ID  Col1  Col2
1    12    1
2    7     7
3    4     2

df2 = pd.DataFrame({"ID" : [2,3,5], "Col1": [3,4,3], "Col2": [5,5,2], "Col3": [0,11,3]})

ID  Col1  Col2  Col3
2     3     5    0
3     4     5    11
5     3     2    3
</code>```

What I would like to do is merge those dataframes on the ID column and sum the matching ones. The not matching columns should remain as they are.

It should become something like this

```<code>ID  Col1  Col2 Col3
1    12    1    NaN
2    10    12   0
3    8     7    11
5    3     2    3
</code>```

I tried adding the one df to the other, but it doesn't work.

答:
Use concat, groupby and sum i.e

```<code>ndf = pd.concat([df1,df2]).groupby('ID').sum()

   Col1  Col2  Col3
ID
1     12     1   NaN
2     10    12   0.0
3      8     7  11.0
5      3     2   3.0
</code>```

Body:
I have two dataframes with unique ids and matching columns like these:

df1 = pd.DataFrame({"ID" : [1,2,3], "Col1": [12,7,4], "Col2": [1,7,2]})

ID  Col1  Col2
1    12    1
2    7     7
3    4     2

df2 = pd.DataFrame({"ID" : [2,3,5], "Col1": [3,4,3], "Col2": [5,5,2], "Col3": [0,11,3]})

ID  Col1  Col2  Col3
2     3     5    0
3     4     5    11
5     3     2    3

What I would like to do is merge those dataframes on the ID column and sum the matching ones. The not matching columns should remain as they are.

It should become something like this

ID  Col1  Col2 Col3
1    12    1    NaN
2    10    12   0
3    8     7    11
5    3     2    3

I tried adding the one df to the other, but it doesn't work.

Body:
Use concat, groupby and sum i.e

ndf = pd.concat([df1,df2]).groupby('ID').sum()

   Col1  Col2  Col3
ID
1     12     1   NaN
2     10    12   0.0
3      8     7  11.0
5      3     2   3.0


问:
Imparting expert knowledge for predicting branch statements in C# or C++
I know some CPUs attempt to predict branch statements when deciding what code to pre-fetch, I was wondering if there was a way to help or hard code those branch predictions in C# (or C++). An example would be an error checking if statement which I know will return false 99.9999999% of the time, I would like to tell the CPU to always expect that branch to never happen for pre-fetching purposes.

Thanks.

答:
To the best of my knowledge there is no cross-platform solution to this problem.  I would expect that C# VM would do some sort of runtime analysis to optimize for these sorts of predictions, though I don't know this for a fact.

For C/C++, there are a few platform-specific tools to help optimize this.  You can usually find profile-guided optimizers for the code.  I know for a fact that gcc and g++ support this, and that it can make a pretty big difference in the net program performance.  gcc also supports a compiler-specific extension called __builtin_expect that lets you hardcode in your assumptions about branch prediction:

```<code>if (__builtin_expect(x == 0, 0)) { // Unlikely to occur
    /* ... */
}
</code>```

Body:
To the best of my knowledge there is no cross-platform solution to this problem.  I would expect that C# VM would do some sort of runtime analysis to optimize for these sorts of predictions, though I don't know this for a fact.

For C/C++, there are a few platform-specific tools to help optimize this.  You can usually find profile-guided optimizers for the code.  I know for a fact that gcc and g++ support this, and that it can make a pretty big difference in the net program performance.  gcc also supports a compiler-specific extension called __builtin_expect that lets you hardcode in your assumptions about branch prediction:

if (__builtin_expect(x == 0, 0)) { // Unlikely to occur
    /* ... */
}


问:
bootstrap glyphicons are not working
i downloaded bootstrap.min.css via NuGet Package manager into my project in visual studio and the glyphicons are not working(but all the other bootstrap functions work...) I referenced it in the layout page:

.

and  it does not work.
When i wrote this it worked but only when i have internet access:

what can be the problem that the glyphicons don't show up and all the other bootstrap functions work? I want to be able to work on my project even if i'm not connected to the internet.
I'm new to all of this and i would really appreciate some help.

答:
The main reason of not working "Glyphicon":

If you are using from free i.e from bootstrap fonts.

Then write is as

Without "S".

If you are using paid glyphon icons then use it with "s"

glyphicons glyphicons-book

Hope it will help you!

Title: bootstrap glyphicons are not working

Body:
The main reason of not working "Glyphicon":

If you are using from free i.e from bootstrap fonts.

Then write is as <i class="glyphicon  glyphicon-arrow-down"></i>

Without "S".

If you are using paid glyphon icons then use it with "s"

glyphicons glyphicons-book

Hope it will help you!


问:
Component Interaction angular
Need some help. I have a product catalog and shopping cart on similar page, and I want to show item in the cart when "Buy" button will be pressed. When button is pressed the item goes to localStorage and it appears in shopping cart only after F5. I think I should use Input decorater, but how to implement it? Maybe the right way is to use services and observables but I weak at angular for now to do it. Also need to remove item from cart, I shoul rewrite localstorage for that, right?

catalog

```<code>  <div class="content">
<div class="item" *ngFor="let auto of auto; let i=index">
    <div> <img src="../../assets/db/{{auto.photo}}" alt=""></div>
  <div class="text">
    <p>{{auto.name}} - {{auto.price}} руб.</p>
    <p><input type="submit" value="Купить" (click)="toCart(i)"></p></div>
</div>
</code>```

```<code>  auto: any;
cart=[];
price=[];

constructor(private service:DataService) { }

ngOnInit() {
  this.getItems();
}
getItems(){
  this.service
     .getItems()
     .subscribe(goods => {
       this.auto = goods;
     } )
}

toCart(i){
  this.cart.push(this.auto[i]);
  this.price.push(this.auto[i].price);
  localStorage.setItem("cart",JSON.stringify(this.cart));
  localStorage.setItem("price",JSON.stringify(this.price));

}
</code>```

cart component

```<code>export class CartComponent implements OnInit {
list = localStorage.getItem("cart");
names = JSON.parse(this.list);
len = this.names.length;
price = this.names.price;
Message: string;

constructor() { }

 ngOnInit() {
 }

send(){
  this.Message = "Готово";
  localStorage.setItem('cart',JSON.stringify(""));
 }

// remove(i){
//     let newlist = this.names.slice(this.names[i],1);
//     console.log(newlist);
//     this.len = this.names.length - 1;
//  }

}
</code>```

cart template

```<code><div class="content">
<li *ngFor="let name of names; let i=index">
  <p>{{name.name}} - {{name.price}}руб.</p>
<button (click)="remove(i)">Удалить</button>
  <!-- <button (click)= "add(i)">Добавить </button>   -->
</li>
<p>Количество: {{len}}  </p>
{{Message}}
<p><input type="submit" value="Оформить заказ" (click)="send()"></p>
</code>```

答:
Please try moving list = localStorage.getItem("cart");
names = JSON.parse(this.list); to ngOnInit() in cart.component.

This ensures that every time cart page is loaded , the value is updated from local storage.

Title: Component Interaction angular

Body:
Need some help. I have a product catalog and shopping cart on similar page, and I want to show item in the cart when "Buy" button will be pressed. When button is pressed the item goes to localStorage and it appears in shopping cart only after F5. I think I should use Input decorater, but how to implement it? Maybe the right way is to use services and observables but I weak at angular for now to do it. Also need to remove item from cart, I shoul rewrite localstorage for that, right?

catalog

{{auto.name}} - {{auto.price}} руб.

<input type="submit" value="Купить" (click)="toCart(i)">

  auto: any;
cart=[];
price=[];

constructor(private service:DataService) { }

ngOnInit() {
  this.getItems();
}
getItems(){
  this.service
     .getItems()
     .subscribe(goods => {
       this.auto = goods;
     } )
}

toCart(i){
  this.cart.push(this.auto[i]);
  this.price.push(this.auto[i].price);
  localStorage.setItem("cart",JSON.stringify(this.cart));
  localStorage.setItem("price",JSON.stringify(this.price));

}

cart component

export class CartComponent implements OnInit {
list = localStorage.getItem("cart");
names = JSON.parse(this.list);
len = this.names.length;
price = this.names.price;
Message: string;

constructor() { }

 ngOnInit() {
 }

send(){
  this.Message = "Готово";
  localStorage.setItem('cart',JSON.stringify(""));
 }

// remove(i){
//     let newlist = this.names.slice(this.names[i],1);
//     console.log(newlist);
//     this.len = this.names.length - 1;
//  }

}

cart template

{{name.name}} - {{name.price}}руб.

<button (click)="remove(i)">Удалить</button>

Количество: {{len}}

{{Message}}

<input type="submit" value="Оформить заказ" (click)="send()">


问:
CSS before and after pseudo elements not working in Edge and IE 11
I'm having issue to display a button with angled sides with css using :before and :after pseudo elements. It is working in Chrome and Firefox but not in Edge and IE 11.
What might be the problem?

a { text-decoration: none }
.container { margin: 20px; }
.font-jos {
  font-family: Verdana;
}
.btn-ribbon {
  position: relative;
  display:inline-block;
  padding: 13px 11px;
  background-color: #b46b78;
  color: #fff;
  font-size: 15px;
  line-height: 18px;
  font-weight: 700;
  letter-spacing: 0.05em;
  border-radius: 0;
  border: none;
  margin-left: 20px;
  text-transform: uppercase;
}
.btn-ribbon:before {
    content: "";
    position: absolute;
    top: 0;
    left: -10px;
    display: block;
    width: 0;
    height: 0;
    border-top: 22px solid #b46b78;
    border-bottom: 22px solid #b46b78;
    border-left: 10px solid #fff0;
    z-index: 1;
}
.btn-ribbon:after {
    content: "";
    position: absolute;
    top: 0;
    right: -10px;
    display: block;
    width: 0;
    height: 0;
    border-top: 22px solid #b46b78;
    border-bottom: 22px solid #b46b78;
    border-right: 10px solid #fff0;
    z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  Read more
</div></code>```

https://codepen.io/nidus/pen/gXJYLg

答:
You need to change #fff0 to rgba(255, 255, 255, 0) or transparent in your CSS border-right: 10px solid transparent; and border-left: 10px solid transparent;. It's not liking the formatting of the colors.

IE and Edge don't seem to support that format.

Here's a working example:

a { text-decoration: none }
.container { margin: 20px; }
.font-jos {
  font-family: Verdana;
}
.btn-ribbon {
  position: relative;
  display:inline-block;
  padding: 13px 11px;
  background-color: #b46b78;
  color: #fff;
  font-size: 15px;
  line-height: 18px;
  font-weight: 700;
  letter-spacing: 0.05em;
  border-radius: 0;
  border: none;
  margin-left: 20px;
  text-transform: uppercase;
}
.btn-ribbon:before {
    content: "";
    position: absolute;
    top: 0;
    left: -10px;
    display: block;
    width: 0;
    height: 0;
    border-top: 22px solid #b46b78;
    border-bottom: 22px solid #b46b78;
    border-left: 10px solid transparent;
    z-index: 1;
}
.btn-ribbon:after {
    content: "";
    position: absolute;
    top: 0;
    right: -10px;
    display: block;
    width: 0;
    height: 0;
    border-top: 22px solid #b46b78;
    border-bottom: 22px solid #b46b78;
    border-right: 10px solid transparent;
    z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  Read more
</div></code>```

Body:
I'm having issue to display a button with angled sides with css using :before and :after pseudo elements. It is working in Chrome and Firefox but not in Edge and IE 11.
What might be the problem?

a { text-decoration: none }
.container { margin: 20px; }
.font-jos {
  font-family: Verdana;
}
.btn-ribbon {
  position: relative;
  display:inline-block;
  padding: 13px 11px;
  background-color: #b46b78;
  color: #fff;
  font-size: 15px;
  line-height: 18px;
  font-weight: 700;
  letter-spacing: 0.05em;
  border-radius: 0;
  border: none;
  margin-left: 20px;
  text-transform: uppercase;
}
.btn-ribbon:before {
    content: "";
    position: absolute;
    top: 0;
    left: -10px;
    display: block;
    width: 0;
    height: 0;
    border-top: 22px solid #b46b78;
    border-bottom: 22px solid #b46b78;
    border-left: 10px solid #fff0;
    z-index: 1;
}
.btn-ribbon:after {
    content: "";
    position: absolute;
    top: 0;
    right: -10px;
    display: block;
    width: 0;
    height: 0;
    border-top: 22px solid #b46b78;
    border-bottom: 22px solid #b46b78;
    border-right: 10px solid #fff0;
    z-index: 1;
}

  Read more

https://codepen.io/nidus/pen/gXJYLg

Body:
You need to change #fff0 to rgba(255, 255, 255, 0) or transparent in your CSS border-right: 10px solid transparent; and border-left: 10px solid transparent;. It's not liking the formatting of the colors.

IE and Edge don't seem to support that format.

Here's a working example:

a { text-decoration: none }
.container { margin: 20px; }
.font-jos {
  font-family: Verdana;
}
.btn-ribbon {
  position: relative;
  display:inline-block;
  padding: 13px 11px;
  background-color: #b46b78;
  color: #fff;
  font-size: 15px;
  line-height: 18px;
  font-weight: 700;
  letter-spacing: 0.05em;
  border-radius: 0;
  border: none;
  margin-left: 20px;
  text-transform: uppercase;
}
.btn-ribbon:before {
    content: "";
    position: absolute;
    top: 0;
    left: -10px;
    display: block;
    width: 0;
    height: 0;
    border-top: 22px solid #b46b78;
    border-bottom: 22px solid #b46b78;
    border-left: 10px solid transparent;
    z-index: 1;
}
.btn-ribbon:after {
    content: "";
    position: absolute;
    top: 0;
    right: -10px;
    display: block;
    width: 0;
    height: 0;
    border-top: 22px solid #b46b78;
    border-bottom: 22px solid #b46b78;
    border-right: 10px solid transparent;
    z-index: 1;
}

<div class="container">
  <a href="#" class="btn font-jos btn-ribbon">Read more</a>
</div>