text:
Q: Plotting Multiple Lines Graph from DataFrame I have a large data set containing years, NFL teams, their total salaries paid out for that year, and more misc stats. I want to create a plot that has the years on the x-axis, total salaries on the y and then has multiple lines, one for each team.
The data I want to plot looks something like this except there are of course way more teams and years and the total salaries are accurate:

Year
Team
Salaries

2015
Miami
$100

2015
Denver
$150

2015
LA
$125

2016
Miami
$125

2016
Denver
$100

2016
LA
$100

I know pandas plot function and I can set the x-axis but when I set y to be total salaries it just gives me a single line. I also do not know how to set it to break up the data by each team so each team is treated as a separate line.

A: You want to use a pivot table to get a new column per team.
Once you've got the data reshaped like this, plotting is easy. Check out the documentation on pivot tables.
import pandas as pd
df = pd.DataFrame(
     {
         "Year": ["2015", "2016", "2017", "2018"] * 6,
         "Team": ["Miami", "Denver", "LA"] * 8,
         "Salaries": [100, 200, 150, 125, 100, 250] * 4,
     }
)

df.pivot_table(values="Salaries",index="Year",columns="Team").plot()

The result of the pivot table looks like this
Team    Denver  LA  Miami
Year
2015    100 150 100
2016    200 250 125
2017    100 150 100
2018    200 250 125

And the plot:

A: Alternative via seaborn:
import seaborn as sns

import pandas as pd

df = pd.DataFrame(
    {
        "Year": ["2015", "2016", "2017", "2018"] * 6,
        "Team": ["Miami", "Denver", "LA"] * 8,
        "Salaries": [100, 200, 150, 125, 100, 250] * 4,
    }
)

sns.lineplot(x='Year', y='Salaries', hue='Team', data=df)

OUTPUT:

NOTE: Thanks to @Cornelius Roemer for the model data.


text:
Q: Server side language for cpu/memory intensive process Whats a good server side language for doing some pretty cpu and memory intensive things that plays well with php and mysql. Currently, I have a php script which runs some calculations based on a large subset of a fairly large database and than updates that database based on those calculations (1.5millions rows). The current implementation is very slow, taking 1-2 hours depending on other activities on the server. I was hoping to improve this and was wondering what peoples opinions are on a good language for this type of task?

A: Where is the bottleneck? Run some real profiling, and see what exactly is causing the problem. Is it the DB I/O? Is it the cpu? Is the algorithm inefficient? Are you calling slow library methods in a tight inner loop? Could precalculation be used.
You're pretty much asking what vehicle you need to get from point A to point B, and you've offered a truck, car, bicycle, airplane, jet, and helicopter. The answer won't make sense without more context.

A: The language isn't the issue, your issue is probably where you are doing these calculations. Sounds like you may be better off writing this in SQL, if possible. Is it? What are you doing?

A: I suspect your bottleneck is not the computation. It definitely takes several hours to just update a few million records.
If that's the case, you can write a customized function in c/c++ for MySQL and execute the function in stored procedure.
We do this in our database to re-encrypt some sensitive fields during key-rotation. It shrunk key-rotation time from days to hours. However, it's a pain to maintain your own copy of MySQL.  We have been looking for alternatives but nothing is close to the performance of this approach.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lets encrypt with lighttpd and wordpress I am trying to implement let's encrypt with certbot and I am using lighttpd on CentOS 6
So this is my full conf file for my host
$SERVER["socket"] == ":443" {
  ssl.engine = "enable"
  ssl.pemfile = "/etc/letsencrypt/live/mysite.com/web.pem"
  ssl.ca-file = "/etc/letsencrypt/live/mysite.com/chain.pem"
  server.name = "mysite.com"
  server.document-root = "/home/mysite/public_html"
  server.errorlog = "/var/log/lighttpd/mysite.com_error.log"
  accesslog.filename = "/var/log/lighttpd/mysite.com_access.log"
  ssl.cipher-list = "ECDHE-RSA-CHACHA20-POLY1305 ECDHE-ECDSA-CHACHA20-POLY1305 AES128+EECDH:AES128+EDH:!aNULL:!eNULL"
  ssl.honor-cipher-order = "enable"
  ssl.disable-client-renegotiation = "enable"
  ssl.use-sslv2= "disable"
  ssl.use-sslv3 = "disable"
}

$HTTP["scheme"] == "http" {
  $HTTP["host"] =~ "^(www.)?mysite.com$" {
    server_name = "mysite.com"

    server.document-root = "/home/mysite/public_html"
    accesslog.filename = "/home/mysite/logs/access.log"

    fastcgi.server = ( ".php" =>
      ( "localhost" =>
        (
            "socket" => "/var/run/lighttpd/php-fpm.socket.mysite"
        )
      )
    )

    url.rewrite-once = (

      # Exclude some directories from rewriting
      "^/(\.well-known|wp-admin|wp-includes|wp-content|phpmyadmin)/(.*)" => "$0",

      # Exclude .php files at root from rewriting
      "^/(.*.php)" => "$0",

      # Handle search correctly
      "^/(.*)?(?s=)(.*)$" => "/search/$3",

      # Handle permalinks and feeds
      "^/(.*)$" => "/index.php/$1",

      "^/?$" => "/index.php",

    )

    alias.url = ("/phpmyadmin" => "/usr/share/phpmyadmin/")

  }
}

So first problem I am having is that when i try to go to https:// mysite.com i get content without images and style so that is a url-rewrite problem but i don't see that https is enabled. Is still get warning from browser that my site is not secure.
Second issue is when i add url.redirect = (".*" => "https://%0$0") i get too many redirect ERROR.
So I am puzzled. I think problem might be with rewrites, but it's odd that i don't even have https enabled.
P.S. And yes I got success message from certbot before all this.
THE SOLUTION was just to install WP plugin that would turn all my http links to images and styles to https and now it's working. @mrkoopie answer helped me think about the solution in that way so I am accepting it.

A: The good news is that your server is configured correct if you don't have a certificate error upon accessing the website via HTTPS. The bad news is that your website is configured incorrectly.
What is happening is that the HTML content is loaded over HTTPS. So far, so good and secure. But what goes wrong is that the objects that your HTML content is referring to, such as images, css and js, are referred with HTTP instead of HTTPS. This is bad, as browser won't download any non-encrypted file when the HTML code is loaded over HTTPS.
To resolve this make sure that your website refers to every file with HTTPS. In WordPress this can be done easily, however you did not provide what system you are using and for each system this is different.
So why is loading objects over HTTP bad when the HTML code is loaded over HTTPS? Well, the fact that you use HTTPS means that you want to load your content securely. The main objective is that nobody can alter or view the content. If you load any object over HTTP, it is vulnerable for malicious injections and anyone can see what content is being loaded (assuming that they can get your traffic). As this reduces the security by a lot, browsers simply ignore any object that is referred by HTTP when the HTML content is loaded via HTTPS. Configuring your server to redirect http traffic to https won't work as the browser will not attempt to load the objects anyways.
Hope this helps.

A: Notes:

*

*lighttpd for CentOS 7 and 8 uses different lighttpd configuration file structure (conf.d directory and modules.conf).

*CentOS 6 has the old OpenSSL version which will not work well due to OpenSSL security bug. You may need to upgrade your server to CentOS7/8 with latest OpenSSL to support TLS 1.3 version.

*Make sure you already installed lighttpd and certbot on your CentOS 7/8 Linux server with latest versions as listed here (as of Jan 2021).
lighttpd/1.4.55 (ssl)
OpenSSL 1.1.1g FIPS  21 Apr 2020
certbot 1.11.0

Here's the updated details that will work well with lighttpd, Wordpress and certbot:

*

*in your Linux, run:
openssl dhparam -out /etc/ssl/certs/dhparam.pem 4096

*Enable/add mod_openssl and mod_setenv in server.modules in /etc/lighttpd/modules.conf

*Run
certbot certonly --webroot -w /home/website -d domain.com

(Replace domain.com with your domain name)
Output:
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/domain.com/fullchain.pem

Your key file has been saved at:
/etc/letsencrypt/live/domain.com/privkey.pem

Your cert will expire on 2021-01-16. To obtain a new or tweaked
version of this certificate in the future, simply run certbot
again. To non-interactively renew *all* of your certificates, run
certbot renew

*Add
certbot renew

to cronjob and run it every month.

*Directive in lighttpd.conf for ssl
$HTTP["host"] =~ "domain\.com$" {

   server.document-root = "/home/website"

   url.rewrite = (
       "^/(.*)\.(.+)$" => "$0",
       "^/(phpMyAdmin)/?(.*)" => "$0",
       "^/(.+)/?$" => "/index.php/$1"
   )

   url.access-deny = ( "~", "xmlrpc.php")
   server.error-handler-404 = "/index.php"
   dir-listing.activate       = "disable"
}

$SERVER["socket"] == ":80" {
        $HTTP["host"] =~ "(.*)" {
                url.redirect = ( "^/(.*)" => "https://%1/$1" )
        }
}

$SERVER["socket"] == "0.0.0.0:443" {
        ssl.engine   = "enable"
        ssl.disable-client-renegotiation = "enable"

        ssl.privkey = "/etc/letsencrypt/live/domain.com/privkey.pem"
        ssl.pemfile = "/etc/letsencrypt/live/domain.com/fullchain.pem"

  $HTTP["host"] =~ "domain\.com$" {
        ssl.privkey = "/etc/letsencrypt/live/domain.com/privkey.pem"
        ssl.pemfile = "/etc/letsencrypt/live/domain.com/fullchain.pem"
  }

        ssl.dh-file = "/etc/ssl/certs/dhparam.pem"

  # ECDH/ECDHE ciphers curve strength
        ssl.ec-curve            = "secp384r1"
        ssl.use-compression     = "disable"

  # Environment flag for HTTPS enabled
  setenv.add-environment = (
           "HTTPS" => "on"
  )

  ssl.use-sslv2 = "disable"
  ssl.use-sslv3 = "disable"
  ssl.openssl.ssl-conf-cmd = ("Protocol" => "-TLSv1.1, -TLSv1, -SSLv3")
  ssl.honor-cipher-order    = "disable"
  ssl.cipher-list = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384
:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384"

  # HSTS(15768000 seconds = 6 months)

  $HTTP["scheme"] == "https" {
        setenv.add-response-header  = ( "Strict-Transport-Security" => "max-age=63072000; includeSubdomains; ")
  }

  $HTTP["host"] =~ "domain\.com$" {

     url.rewrite = (
        "^/(.*)\.(.+)$" => "$0",
        "^/(phpMyAdmin)/?(.*)" => "$0",
        "^/(.+)/?$" => "/index.php/$1"
     )

     url.access-deny = ( "~", "xmlrpc.php")
     server.error-handler-404 = "/index.php"
     dir-listing.activate       = "disable"

  }

}
## end zone - $SERVER["socket"] == "0.0.0.0:443"

Then restart your lighttpd server.
SSL Server TEST
https://www.ssllabs.com/ssltest/index.html
and enter your domain name. This SSL directive above should your site with A+ score on SSL test.


text:
Q: Creating a custom JSON API for Domino data with authentication I need to expose custom domino data as json through an url/endpoint,
I am creating an xAgent, xe:jsonRpcService or xe:restService that will expose the json
Applications from the internet/intranet will consume this data but I need them to authenticate.
How should I setup my Domino server to handle this Authentication and what kind of requests do the clients need to do to get the data as authenticated user.

A: You can use "basic authentication" for your API endpoint. If you have en existing internet site with session authentication, you can override that for your API endpoint by adding an "Override Session Authentication" web site rule for the API URLs. Here's an example:


text:
Q: spring data JPA null primary key error Here is my data entity
@Entity
@Table(name = "hotel")
@Data
public class Hotel  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "hotel_id", updatable = false)
    @JsonIgnore
    private int id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "room_price")
    private RoomPrice roomPrice;
}

@Entity
@Table(name = "room_price")
@Data
public class RoomPrice {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "room_price_id", updatable = false)
    @JsonIgnore
    private int roomPriceId;

    @Column(name = "price")
    @Min(0)
    private double price;

    @Column(name = "currency_type")
    @NotEmpty
    @Size(min = 3, max = 3)
    private String currency;
}

SQL:
CREATE TABLE IF NOT EXISTS room_price (
  room_price_id INTEGER PRIMARY KEY,
  price         SMALLINT,
  currency_type VARCHAR(3) NOT NULL
);
ALTER TABLE hotel
  ADD
  COLUMN room_price INTEGER REFERENCES room_price (room_price_id);

hotel.setRoomPrice(price); hotelDao.save(hotel); throw room_price_id null value error message.
With cascade.all, when storing a hotel entity, it should also store price entity. What have I been doing wrong?
Thanks.

A: Since you're using GenerationType.IDENTITY strategy, you should use serial or bigserial type for room_price_id to let Postgres to auto generate your primary key.


text:
Q: Why is Stripe not giving me a Payment Intents requires_action status when I use a 3D Secure test card number? In following the Stripe documentation for Billing and Subscriptions, I'm using PaymentIntents to create a subscription. It works fine if I enter a test card that doesn't require 3D Secure. But it I use one that does, instead of giving me a status of requires_action, it just gives a error on the card.
//Create customer
$customer = \Stripe\Customer::create(array(
      "source" => $token,
      "email" => $subscriber_email)
    );

    // Get customer variables from Stripe response
    $payment_livemode = $customer->livemode;
    $payer_id = $customer->id;

    // Now put customer on subs plan
    try {
        $subscription = \Stripe\Subscription::create([
          "customer" => $payer_id,
          "items" => [
            [
              "plan" => $subscription_plan
            ],
          ],
           "expand" => ["latest_invoice.payment_intent"],
        ]);

        $subscription_id = $subscription->id;
        $subscription_plan_id = $subscription->items->data[0]->plan->id;
        $subscription_latest_invoice_status = $subscription->latest_invoice->status;
        $subscription_latest_invoice_id = $subscription->latest_invoice->id;
        $subscription_latest_invoice_payment_intent_status = $subscription->latest_invoice->payment_intent->status;
        $subscription_latest_invoice_payment_intent_client_secret = $subscription->latest_invoice->payment_intent->client_secret;

        $_SESSION['subscription_latest_invoice_payment_intent_client_secret'] = $subscription_latest_invoice_payment_intent_client_secret;

        if ($subscription_latest_invoice_payment_intent_status=='succeeded') {
             header("Location: ../payment-success");
        }
        if ($subscription_latest_invoice_payment_intent_status=='requires_payment_method') {
             header("Location: ../payment?payment_status=failed&inv=$subscription_latest_invoice_id");
        }
        if ($subscription_latest_invoice_payment_intent_status=='requires_action') {
             header("Location: ../payment?payment_status=requires_action");
        }
    } catch(\Stripe\Error\Card $e) {

          $body = $e->getJsonBody();
          $err  = $body['error'];

          if ($err['code']=="subscription_payment_intent_requires_action") {
              header("Location: ../payment/requires_action");
          }

        } catch (\Stripe\Error\RateLimit $e) {
          // Too many requests made to the API too quickly
        } catch (\Stripe\Error\InvalidRequest $e) {
          // Invalid parameters were supplied to Stripe's API
        } catch (\Stripe\Error\Authentication $e) {
          // Authentication with Stripe's API failed
          // (maybe you changed API keys recently)
        } catch (\Stripe\Error\ApiConnection $e) {
          // Network communication with Stripe failed
        } catch (\Stripe\Error\Base $e) {
          // Display a very generic error to the user, and maybe send
          // yourself an email
        } catch (Exception $e) {
          // Something else happened, completely unrelated to Stripe
        }

I'm using test cards on this page:
https://stripe.com/docs/testing#three-ds-cards
I have chosen the card with this number:
4000 0000 0000 3220
Here's my error details:
Status:402
Type:card_error
Code:subscription_payment_intent_requires_action
Message:Payment for this subscription requires additional user action before it can be completed successfully. Please refer to the use of the enable_incomplete_payments parameter here: https://stripe.com/docs/billing/lifecycle#incomplete-opt-in
My API version is 2018-05-21.
Can anyone give me a clue to what I'm doing wrong?

A: Answered in the comments, just posting here for visibility:
Hi Andy, since you are on an older API version, to support 3DS on subscriptions, you should be using this guide instead: https://stripe.com/docs/billing/migration/strong-customer-authentication#upgrading-integration.
This means updating your API version or passing the enable_incomplete_payments flag when creating the subscription, as the error message points out.

A: I had the same problem and actually, the API version is not the version of the library you download, you have to change it in your dashboard, https://dashboard.stripe.com/developers


text:
Q: Flexbox item with overflowing content only works on Chrome Please take a look at this pen:
https://codepen.io/linck5/pen/gRKJbY?editors=1100

body{ margin: 0;}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.top-bar {
  background-color: darksalmon;
  height: 50px;
}

.inner-container {
  flex: 1;
  background-color: chocolate;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.top {
  background-color: blueviolet;
  flex: 1;
  overflow: auto;
  font-size: 40px;
  line-height: 5rem;
}

.bottom {
  background-color: darkkhaki;
  height: 200px;
}

Top bar

      O
v
e
r
f
l
o
w
i
n
g
C
o
n
t
e
n
t

Bottom part

I want to have only the .top div be scrollable, not the entire page. I don't want the .top div to push down the .bottom div.
And this is exactly what happens on Chrome, everything works perfectly. But on Firefox and Edge, a scrollbar appears on the entire page, and the .bottom div is pushed down.
Also the .top-bar div gets shrunk down instead of having its desired 50px height.
Could you guys help me with this?

A: Three things to consider:

*

*An initial setting on flex items is flex-shrink: 1. This means that items are permitted to shrink in order to create more space in the container. To disable this feature use flex-shrink: 0.
See this post for a full explanation: What are the differences between flex-basis and width?

*An initial setting on flex items is min-height: auto. This means that items cannot be smaller than the height of their content. To override this behavior use min-height: 0.
See this post for a full explanation: Why doesn't flex item shrink past content size?

*In your code, Firefox and Edge are adhering strictly to the spec. Chrome, it appears, considers the spec a foundation, but factors in common sense scenarios and expected user behavior.
For your layout to work across browsers, make the following adjustments:

body{ margin: 0;}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.top-bar {
  background-color: darksalmon;
  height: 50px;
  flex-shrink: 0; /* NEW */
  /* Or remove height and flex-shrink and just use this:
     flex: 0 0 50px; */
}

.inner-container {
  flex: 1;
  background-color: chocolate;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0; /* NEW */
}

.top {
  background-color: blueviolet;
  flex: 1;
  overflow: auto;
  font-size: 40px;
  line-height: 5rem;
}

.bottom {
  background-color: darkkhaki;
  /* height: 200px; */
  flex: 0 0 200px; /* NEW */

}

Top bar

O
v
e
r
f
l
o
w
i
n
g
C
o
n
t
e
n
t

Bottom part

revised pen


text:
Q: Is there a way to timeout a Postgres commit? We have an app that is using psycopg2 to write records to RDS Postgres.  Occasionally when a scale-down event occurs and the container stops during an insert commit, this creates a deadlock on the table.  We are using a threaded connection pool with some standard timeouts as seen below:
    self._pool = pool.ThreadedConnectionPool(
        mincount,
        maxcount,
        dsn,
        cursor_factory=cursor_factory,
        application_name=application_name or name,
        keepalives_idle=1,
        keepalives_interval=1,
        keepalives_count=5,
        options=f"-c statement_timeout={statement_timeout}s -c idle_in_transaction_session_timeout={idle_in_transaction_session_timeout}s",

The idle in transaction timeout seems to be working as transactions occurring after throw a timeout error rather than waiting silently, but we're still getting lock issues.  Is there a different timeout we should use to have Postgres kill these transactions?
Update on issue:
We have 2 different applications.  One that writes to the table and another that reads from it. We're see this error occasionally pop up in the write application:
deadlock detected
DETAIL:  Process 31504 waits for ShareLock on transaction 33994594; blocked by process 28310.
Process 28310 waits for ShareLock on transaction 33994595; blocked by process 31504.
HINT:  See server log for query details.
CONTEXT:  while inserting

Which if I pull the pg_stat_activity for those pids, I get this:
[
  {
    "datid": 262668,
    "datname": "app_db",
    "pid": 31504,
    "usename": "app",
    "application_name": "app-Writer",
    "query_start": "2020-10-28 23:16:23.859818",
    "state_change": "2020-10-28 23:16:23.865455",
    "wait_event_type": "Client",
    "wait_event": "ClientRead",
    "state": "idle",
    "backend_xid": null,
    "backend_xmin": null,
    "query": "COMMIT",
    "backend_type": "client backend"
  },
  {
    "datid": 262668,
    "datname": "app_db",
    "pid": 28310,
    "usename": "app",
    "application_name": "app-Writer",
    "query_start": "2020-10-28 23:12:01.232097",
    "state_change": "2020-10-28 23:12:01.234281",
    "wait_event_type": "Client",
    "wait_event": "ClientRead",
    "state": "idle",
    "backend_xid": null,
    "backend_xmin": null,
    "query": "COMMIT",
    "backend_type": "client backend"
  }
]

The reader app later fails with this error:
psycopg2.InternalError: terminating connection due to idle-in-transaction timeout
SSL connection has been closed unexpectedly

Both the reader and writer apps have the same timeout settings.

A: First, if the deadlock occurs only rarely, don't worry too much: all you have to do is teach your application to repeat the transaction if it encounters the deadlock. Read on if you need to get rid of the deadlock.
The COMMIT you are seeing in pg_stat_activity is a red herring: the query column contains the last statement that was sent on that connection, and that probably was the COMMIT that ended the transaction after the deadlock happened.
Readers and writers never block each other in PostgreSQL, so the deadlock must be between two data modifying transactions.
You should do what the error message tells you and consult the PostgreSQL log file. There you find more information, in particular the statements that were being executed when the deadlock happened. This information is not sent to the client because it may contain sensitive data.
To debug the problem, you have to consider all the statements that were executed in these transactions, because it may well be that earlier statements in the transaction took locks that contributed to the deadlock. Remember that locks are held until the end of the transaction.
If you cannot identify the transactions and what they did from your application code, you could set log_statement = 'all' in PostgreSQL and make sure that the transaction ID (%x) is included in log_prefix. That will cause all statements to be logged (beware of performance problems), and when the error happens, you can find all the statements that belong to the involved transactions in the log.
This is cumbersome, but the only way if you cannot find the statements from your application end.
Once you know the statements, you can reproduce and debug the problem.


text:
Q: run a function again when screen is resized I'm trying to do an animation which runs by clicking on aside tag. after this, I want to run the asideAnime function again when resizing screen (window).
this my JS code :
var image_url = $('aside').css('background-image'),image;
// Removing url() or in case of Chrome url("")
image_url = image_url.match(/^url\("?(.+?)"?\)$/);

if (image_url[1]) {
    image_url = image_url[1];
    image = new Image();

    $(image).load(function () {
        var a = image.width;
        var b = image.height;
        var c = $(window).width();
        var d = $(window).height();
        var e = ((d-b)/b); //height inscrease amount ratio
        var f = a+(e*a); //changing width based on height change

        $('aside').click(function(){
            asideAnime(a,b,c,d,e,f);
            $(this).addClass('done');
        });
    });
    image.src = image_url;
}

var asideAnime = function(a,b,c,d,e,f) {
    var g = $('aside').width();
    var h = (e*a); //the amount change in width
    var condition = h > -100;
    $('aside').animate({
        width: f,
        maxWidth: c
    });

    if(condition) {
        $('.main').animate({
            right: -f,
            left: f,
            marginLeft: "0"
        });
    } else {
        $('.main').animate({
            right: "0",
            left: f,
            marginLeft: "0"
        });
    };
}

I tried to do this by using if statement before the resize function, but it didn't work..
if ($('aside').hasClass('done')) {
    $(window).resize(function(){
        asideAnime(a,b,c,d,e,f);
    });
}

anybody has any idea ? thanks
To explain more:
there is aside tag with 30% width and a background image with background-size:cover .
by clicking aside, the aside opens and shows the full image. all this lines of codes are because I'm trying to open aside according to the change in bg made by background-size:cover while keeping the ratio.

A: Once the event handler is attached, it doesn't care about the if condidition surrounding it, it will still always fire when the event happens, so you have to place the condition inside the event handler :
$(window).resize(function(){
    if ($('aside').hasClass('done')) {
        asideAnime(a,b,c,d,e,f);
    }
});

Also note that placing an event handler inside another event handler is bad practice, as a new resize event handler will be attached every time someone clicks the aside, and clicking the aside three times will fire the asideAnime function three times when the window is resized.

A: Event might not trigger inside if statement.
But, once you bind, the event, it will be always triggered when window is resized. You can check condition ad execute code inside event.
Try:
$(window).resize(function(){
    if ($('aside').hasClass('done')) {
        asideAnime(a,b,c,d,e,f);
    }
});

A: I would suggest define var a,b,c,d,e,f globally first.and then trigger click event of aside tag on resize of window.
$(window).resize(function(){
$(aside).trigger( "click");
});


text:
Q: Тег в атрибуте (alt="html tag") У меня есть вопрос по HTML.
Как исправить эту ошибку?
 <area shape="poly" alt="<img src="folder/image.png">">

A: Привет!
Видимо ты не совсем разобрался с использованием , там синтаксис чуть сложнее - по классике нужно ОТДЕЛЬНО задать картинку и поверх нее отрисовать области.
Атрибут alt - он для альтернативного текста для области, не для картинки
Вот ценна ссылка, с примером внутри - https://webref.ru/html/area
Сделай подобно и будет всё работать )


text:
Q: Missing some packages? I am trying to use a program written by someone else.  When I run the program, I am supposed to get a number as a result, however, what I got is some complicated result with "InterpolatingFunction" and "Developer`PackedArrayForm".  I am wondering whether there is any package I should load in that causes this problem?  I upload the program I am trying to run in the following link:
https://user.iter.org/filesharing/?uid=d2bc26f7-c4c4-406b-8337-cb2d26772db4
Thank you very much for your help!

A: I tested your notebook with Mathematica 9.0.1 on Linux and everything works as expected. Here is a screenshot of what you try to do. Note that I only adapted the package location to my download folder


text:
Q: Find a Base for Map(R,R) I have trouble finding a basis for $Map(\mathbb{R},\mathbb{R})$.
While I know what a/the (standard)basis is for $\mathbb{R}^{2\times1}$, that should be $\left(\begin{array}{c} 1 \\ 0 \end{array}\right),\left(\begin{array}{c} 0 \\ 1 \end{array}\right) $ I can't seem to grasp how exactly a basis for $Map(\mathbb{R},\mathbb{R})$ could look like.
I have the following Vectorspace $V := \{ f : \mathbb{R} \to \mathbb{R} \mid \textrm{ there exists } a_0,\ldots,a_4 \in \mathbb{R}$ and $f(x) = \sum_{i=0}^4 a_i x^i$ for all  $ x \in \mathbb{R}\}$
and there is a linear Map $\varphi: V \to V$ with $\varphi(f)(x) = f''(x) - x \cdot f'(x) + f(x-1).$
I have problems with the following two questions:
1) Calculate the matrix $M_{\mathcal{B}}^{\mathcal{B}}(\varphi)$ with respect to a base $\mathcal{B}$ of $V$.
2) Find a basis for $ker(\varphi)$
Now how does a base B for $Map(\mathbb{R},\mathbb{R})$ look like? Is there something like a canonic basis for $Map(\mathbb{R},\mathbb{R})$? I'm stuck and I'd be grateful for any hint into the right direction!
Could I assume that there is some $e$ which is the canonic base for $Map(\mathbb{R},\mathbb{R})$ such that $M_{\mathcal{B}}^{\mathcal{B}}(\varphi)  = e*(f''(x) - x \cdot f'(x) + f(x-1)) $?
For clarity: $M_{\mathcal{B}}^{\mathcal{B}}(\varphi)$ is the Transformation matrix.


text:
Q: Need to push a mass desktop background change I need to find a quick way to change the background on all computers on my domain other than going to each one of them.
I have already tried gpedit.msc user configuration/administrative templates/desktop/active desktop and enabled active desktop and maped the active desktop wallpaper

A: make sure the wall paper file is in a network share that all users have access to.

A: The usual problem with this change is that the background image is either the wrong format, or located in a non-shared location.

A: I've always found the Active Desktop GPO settings to be a little flaky in the past.  This logon script should do it:
Dim WshShell

Set WshShell = WScript.CreateObject("Wscript.Shell")
WshShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper", mybitmap.bmp
WshShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll, _
    UpdatePerUserSystemParameters", 1, False

Set WshShell = Nothing

Althernatively - if you're comfortable with creating MSI files - you could create one containing the necessary registry settings and deploy it via AD.

A: You can create a GPO with the setting "User Configuration\Administrative Templates\Desktop\Desktop\Desktop Wallpaper" with whatever wallpaper you want to define you just have to make sure the file you reference for the wallpaper is available to the user once they login.
One implementation solution would be to create a GPO and link it into the AD at a level where the users you want to be affected all live within then assign the GPO's security filtering to the group "Domain Users" (the default is authenticated users which will also work). You may also set the GPO Status to disable all computer settings.


text:
Q: Is it good to define all the constants in one file or in header file of the class being used in? In Objective C, is it a good practice to define all the constants in one Constanst.h file or putting constants in .h file of the classes where they are used.
What is the general convention ?
For example:
Shall I define enums used in a custom view in the .h file of the view or in one central file.
Also in cases where I have Constants for hostname and routes for APIs, this should be in the module of the class interfacing with API  or again in the central file.

A: I use a Constants.h/.m file for the constants that are shared by multiple classes. (e.g constants about NSUserDefaults or NSNotificationCenter)
For the constants that are needed only in one class I define them into the class. (e.g. CELL_HEIGHT)
Morover, you could actually use a Constants.h and import it in Name-Prefix.pch so it will be automatically imported into all classes.


text:
Q: NetBeans can't run maven I tried to open a netbeans waven project, when I tried to build the project, it failed with the following message,
Cannot run program "C:\apache-maven-3.2.3\bin\mvn.bat" (in directory "F:\my_project\Source\Application\main"): CreateProcess error=2, The system cannot find the file specified
I am sure the mvn.bat exists in C:\apache-maven-3.2.3\bin directory. I also tried the bundled maven within netbeans, I got the same error.
Has anyone seen such problems?
Thanks


text:
Q: Netbeans форматирование кода PHP + HTML в Netbeans есть замечательная возможность форматирования кода, команда находится здесь: Источник -> Формат (ALT+SHIFT+F)
Это прекрасно форматирует код (HTML, PHP, CSS, JS ...), но только не в случае мульти-языкового (PHP+HTML) кода - в этом случае чаще всего форматирование не дает хорошего результата.
Пример кода: здесь
PHP+HTML это данность моей работы (работаю с CMS Bitrix).
Есть адекватное решение этой проблемы?

A: Меня могут заминусовать, но я бы посоветовал использовать mvc что бы избежать месива в коде из php вставок тогда можно использовать конструкции <?= $out_var ?> и не делать в все в представлении.

A: Выделяй только форматируемую часть кода, и будет тебе счастье. А лучше почитай стилевые рекомендации, известные как PSR-0, PSR-1 и PSR-2.


text:
Q: Running model.save() method asynchronously? I am wondering if it is possible to run a save method for a model that I've overwritten asynchronously? If so how would you implement it?

A: for web development you have to return a response quickly and using threads or multiprocessing won't help (user will reach timeout and your task will fail
the solution is writing a background task runner (using something like celery)
when user sends a request you send a task call to celery and invoke the background task, the task will run in another process (creating those rows) and you can return a response to user saying your request is being processed.

A: why not use multiprocessing
from multiprocessing import Pool

pool = Pool(processes=1)
result = pool.apply_async(model.save)

to spawn a new process to save your model. you can pass whatever parameters like a path using other arguments in apply_async aswell.


text:
Q: How to make a JSON Curl request to an api url, getting null This should be simple I think but I just can't fathom it.
I need to make a request to a url in the following format:
http://ratings.api.co.uk/business/{lang}/{fhrsid}/{format}  where lang will be set to en-GB the fhrsid is an identifier and format is json.
I tried the following but I am just getting null in return:
$data = array("lang" => "en-GB", "fhrsid" => "80928");
$data_string = json_encode($data);

$ch = curl_init('http://ratings.api.co.uk/business/json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))                                                 );

$Jsonresult = curl_exec($ch);
curl_close($ch);

var_dump(json_decode($Jsonresult));

Any help gratefully received

A: You are currently posting the data to the URL, while you say you want to put the data in the URL itself.
I.e. now you submit {"lang:"en-GB","fhrsid":80928} to the URL http://ratings.api.co.uk/business/json, but instead you want to retrieve the URL http://ratings.api.co.uk/business/en-GB/80928/json.
Don't use POST as request type, don't specify postfields, don't specify content-length, and do put the data in your URL.

A: Sending data as arguments is different than sending it within the URL.
If you require a url format of http://ratings.api.co.uk/{lang}/{fhrsid}/{format}, then you must make your curl_init string match that format.


text:
Q: Custom Mapping tool for txt or excel I have an excel dokument (tab delimitted). Every time before i can insert the excel in my program, i need to map the clients column names to the ones in my app.
So before i begin developing a mapping tool - it would be better if such already existed. But, i don't know i didn't find it.
This tool would actually read an excel or txt file, allow me to name all the names of the new columns on the right and drag and drop (for example).
Maybe this tool has an xml or something where i can define my custom columns, and then it would show op on the right side.
I hope you know what i mean and that someone also had the need for this.
Thanks
info update
I wanted to mention a few things as an update to my question if it's not to late: I have about 50 headers/columns (example: First Name, Middle Name, Street1, Street2,..). So what i always need do every time a client gives me his excel file (contacts backup) is manually copy data for each of his column to the one on my side. And the problem is, every client has different column names, and also some of the columns of the client can go to multiple columns on my side.
So i think, if i can't find a solution, i would make a c++/qt app, which takes an excell and lets me to assign (dragdrop,etc..) every column of his side to on or more columns of my side.
I haven't done any vb programming, so if you can be a bit more detailed about how to aproach the solution i vb that would be great.

A: Firs part of answer: You can achieve it with a simple vbscript. Copy this code in a vbs extension text file and double click.
Dim oCN As Connection
Dim fs As Scripting.FileSystemObject

Set oCN = New Connection
Set fs = New Scripting.FileSystemObject

sCSVFileName = "C:\Temp\Test1.csv"
sSourceSql = "SELECT field1 as f1, field2 as f2, ... FROM " &
             fs.GetFileName(sCSVFileName )
sDestinationTable = "yourAppTable"

With oCN
    .Provider = "Microsoft.Jet.OLEDB.4.0"
    .Properties("Extended Properties").Value =
          "TEXT;HDR=YES;FMT=TabDelimited;MAXSCANROWS=0"
    .Open fs.GetFile(sCSVFileName).ParentFolder
End With

sSql = "INSERT INTO [ODBC;DRIVER={SQL Server};Server=" &
       ServerName & ";Database=" & DBName & _
        IIf(IntegratedSecurity, ";Trusted_Connection=Yes;", _
            ";UID=" & UID & ";PWD=" & PWD & ";") & _
        "]." & sDestinationTable & " " & sSourceSql

oCN.Execute sSql, , adExecuteNoRecords

More info at microsoft social forums
Also, you can parametrize mapping (source and destination tables and mapping fields) with a external xml file.
Second part of answer: You ask if somebody else have this needed and if this is a good idea. Well, this is a very good proposal. And for this reason they are some solutions with this functionality.
First of all, this kind of technology is named ETL. Extract - Transform - Load.
Each database has its own tool

*

*SQL Server Import and Export Wizard

*Oracle data pump and loader

*etc.

Also exists specific technologies:

*

*SSIS from microsoft.

*IBM WebSphere DataStage

*etc.

All this tools have mapping columns capabilities.

A: i use a generic mapping mechanism for that, configured by a couple arrays where you put the names used in your app (aDsNames) with these in your source, the csv file in your case (aDbNames)
I walk the fields in the source, check if the getDbName(name) is in aDsNames and if so write the value in the insertstring to the database.
You can do this both ways, usually my app requests a field to the databasemodule on the server, this module translates to the databasename and does the select.
Hope this is helpfull..
Cheers
select case store
  case "store1Midoc"
    aDbNames = array("id"    , "beheerder", "datumlijst", "rnr13" , "datvan", "dattot", "opmerking", "status" , "waarde", "kode"  , "type")
    aDsNames = array("id"    , "persnr   ", "datum     ", "rnr13" , "datvan", "dattot", "opmerking", "status" , "waarde", "kode"  , "type")
    aTypes   = array("number", "string",    "date"      , "string", "date"  , "date"  , "string"   , "number",  "number", "string", "string")
  case .....
end select

Function getDbName(dsName)
  Dim a
  getDbName = "undefined"
  If instr(join(aDsNames,","),dsName) Then
    For a = 0 to UBound(aDbNames)
      If aDsNames(a) = dsName Then
        getDbName = aDbNames(a)
      End If
    Next
  End If
End Function


text:
Q: Quicksight Date Picker I am unable to select a date range when using my date picker on Quicksight. Ideally I will be able to select a range of dates on my date picker which will be reflected on my visuals. As of now, I can only select one date. Please provide a step to step guide if possible

A: As it is today, the date picker does not support choosing range. To get your desired result you would need to use two date picker controls with one set as a start date parameter and one set as an end date parameter.
You can read more about setting up parameters in the Amazon User Guide Here: https://docs.aws.amazon.com/quicksight/latest/user/parameters-in-quicksight.html

A: Since October 5, 2020, you can create a range filter and then add it to your sheet, as per the visual below.

If you want to have the range filter in your control bar, you can add it to the control bar from the sheet by clicking on "Pin to top".


text:
Q: What "standing on the moon" means? What "She was standing on the moon" means in the passage:
"So," Clee said loudly. I stopped. "I don't really know a lot about health
and stuff? But I figure you probably know what I should be eating. Like
vitamins or whatever."
I turned and looked at her from my bedroom door. She was standing on the
moon and if I responded I would be on the moon too, right next to her. With
her and away from everything else. It looks so far away, but you can just
reach your hand out and touch it.


text:
Q: Handling 10,000 concurrent requests at once with node.js I'm working on a node.js application that has to provide real-time server push to around 10,000 users. My goal is to minimize the time difference between the first receiver and the last receiver. Right now, I am developing locally on my machine.
I use a loop to generate requests and then hold back server response until it hits 10,0000 requests. I want the server to broadcast to all requests at once and measure the difference.
request.js
var http = require('http')
, a = http.getAgent('127.0.0.1', 9202);

var util = require('util');
var connections = [];
var NUM_CONCURR = 1000;

// Max and Min
Array.prototype.max = function(){
  var max = this[0];
  var len = this.length;
  for(var i=0; i<len;i++)
    if(this[i]>max)
     max = this[i];
  return max;
};

 Array.prototype.min = function(){
   var min = this[0];
   var len = this.length;
   for(var i=0; i<len; i++)
     if(this[i]<min)
       min = this[i];
   return min;
 };

// Number of socket tested
a.maxSockets = Infinity;

for(var i =0; i<NUM_CONCURR; i++){
  http.get({
     agent: a,
     path: '/',
     port: 9202,
     host: '127.0.0.1'
   },function(res){
   connections.push(microtime(true));

   });

   util.log("Connected Clients: "+i);
 }

 util.log("Server running at port 9202");

 setInterval(function(){
    util.log("Total Diff Time = "+(connections.max()-connections.min()));
    connections =[];
 }, 1000*10);

 // Time function
 function microtime(get_as_float) {
     var now = new Date().getTime() / 1000;
     var s = parseInt(now);
     return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
 }

server.js
var http = require('http'),
    HOST = 'localhost',
    PORT = '9202';

var connections = [], i;
var server = http.createServer(function(req, res){
  connections[connections.length] = {req:req, res:res};
  console.log('established connections: '+ ++i);
});

// Send msg to stored connections

function message(){
  var i = connections.length,
      connection;

  while(i--){
    connection = connections[i];
    connection.res.writeHead(200);
    connection.res.write('weeeee');
  }
};

//Broadcast after 40 sec

setTimeout(function(){
  message();
}, 1000*40);

server.listen(PORT);
console.log('listening on 9202');

This for some reason didn't work for me. Is there a better approach? Can anyone share his idea? What's the time difference for you? Thanks.

A: Depends on all kinds of things. You don't want to test both request/client and server side code like this on the same box for real world perf. You could also be running out of sockets easily. MacOS, for instance, has an artificial limit that once it gets hit, will bork everything.
Also, with regards to the client side, I think I'd use a tool like apache bench, which has concurrency and profiling built in. http://httpd.apache.org/docs/2.0/programs/ab.html

A: You can use ab benchmark as Josh suggested, or go npmjs.org, there is a load testing tool written in node.  Or else, you can use JMeter.


text:
Q: Remove partial duplicate tuples in a list based on condition I have a list of tuples like this:
mylist = [
    ('Apple', 'Pass'),
    ('Banana', 'Fail'),
    ('Orange', 'Pass'),
    ('Apple', 'Fail')
]

I want to remove tuple ('Apple', 'Fail') as I have ('Apple', 'Pass'), meaning remove tuple which has Fail if another tuple has Pass for Apple and so on, so the new list looks like this:
newList = [
    ('Apple', 'Pass'),
    ('Banana', 'Fail'),
    ('Orange', 'Pass')
]

How would I do this?

A: Use:
# create a set to search for tuples that has Pass
pass_tuples = {e for e, s in mylist if s == 'Pass'}

# keep tuples that are Pass or doesn't have a Pass
newList = [(e, s) for e, s in mylist if s == 'Pass' or e not in pass_tuples]
print(newList)

Output
[('Apple', 'Pass'), ('Banana', 'Fail'), ('Orange', 'Pass')]

Basically you want to keep the elements in newList that are Pass or that doesn't have a Pass.
Note: The time complexity of this approach is expected O(n).

A: # your code goes here
mylist = [
    ('Apple', 'Pass'),
    ('Banana', 'Fail'),
    ('Orange', 'Pass'),
    ('Apple', 'Fail')
]

result = {}
for a, b in mylist:
    if a not in result:
        result[a] = b
    else:
        if result[a] =='Fail' and b=='Pass':
            result[a] = b

mylist =  list(result.items() )
print(mylist)

output
[('Apple', 'Pass'), ('Banana', 'Fail'), ('Orange', 'Pass')]

A: #create 2 different sets for each fail and pass...
setForPass = set()
setForFail = set()

    for i in mylist:
        if i[1] == 'Pass':
            setForPass.add(i[0])
    for i in mylist:
        if i[1] == 'Fail':
            if i[0] in setForPass:
                mylist.remove(i)

output = [('Apple','Pass'), ('Banana','Fail'), ('Orange','Pass')]

A: You can use the key-value pairs to build a dict, and use the max function to overwrite the current value of a key if the new value is greater (since Pass is greater than Fail lexicographically; otherwise use a key function). Convert the dict items back to a list of tuples for output:
d = {}
for k, v in mylist:
    d[k] = max(v, d.get(k, v))
newList = list(d.items())

Demo: https://replit.com/@blhsing/DiligentOverjoyedPlane


text:
Q: Varying number of for-loops I'm trying to write a code that could print something like this
-xv
-xvv
-xvvv
-xvvvv
-xvvvvv

-xxv
-xxvv
-xxvvv
-xxvvvv
-xxvvvvv

-xxxv
-xxxvv
-xxxvvv
-xxxvvvv
-xxxvvvvv

The extra spacing between the 3 "groups" are just for clarity's sake. The maximum number of '-' is 1, 'x' is 3, 'v' is 5, and the number of each symbol increments.
To draw this diagram, I have the following code
for (k = 1 ; k <= num_dash ; k++)
{
   for (i = 1 ; i <= num_x ; i++)
   {
      for (j = 1 ; j <= num_v ; j+++)
      {
         for (k1 = 0 ; k1 < k ; k++)
            printf("-");
         for (i1 = 0 ; i1 < i ; i++)
            printf("x");
         for (j1 = 0 ; j1 < j ; j++)
            printf("v");
         printf("\n");
      }
   }
}

This is when I know there are 3 different kinds of symbols. Is it possible to do the same if the number of symbols are only known at runtime? For example, what if I want the same program to also be able to print
xv
xvv
xvvv
xvvvv
xvvvvv

xxv
xxvv
xxvvv
xxvvvv
xxvvvvv

xxxv
xxxvv
xxxvvv
xxxvvvv
xxxvvvvv

In this case, my code would only be
   for (i = 1 ; i <= num_x ; i++)
   {
      for (j = 1 ; j <= num_v ; j+++)
      {
         for (i1 = 0 ; i1 < i ; i++)
            printf("x");
         for (j1 = 0 ; j1 < j ; j++)
            printf("v");
         printf("\n");
      }
   }

And there are only 2 for-loops instead of 3. Can I write my code such that the number of for-loops varies?

A: Use functions instead of innermost for loops and pass the characters and number of iterations as parameters to that function.

A: E.g.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_aux(char **symbols, int *times, int len, int pos, char *acc){
    int i;
    char *p;

    if(pos == len){
        printf("%s\n", acc);
        return;
    }
    p = malloc(sizeof(char)*strlen(symbols[pos])*times[pos]+strlen(acc)+1);
    for(i=0;i<times[pos];++i){
        int j;
        *p='\0';
        strcpy(p, acc);
        for(j=0;j<=i;++j){
            strcat(p, symbols[pos]);
        }
        print_aux(symbols, times, len, pos + 1, p);
    }
    if(pos + 1 == len)// when last symbol
        printf("\n",pos);
    free(p);
}

//wrap function
void print(char **symbols, int *times, int len){
    print_aux(symbols, times, len, 0, "");
}

int main() {
    int i,n;
    char **symbols;
    int  *times;

    fprintf(stderr,"number of symbols :");
    scanf("%d", &n);
    symbols=(char**)malloc(sizeof(char*)*n);
    times = (int*)malloc(sizeof(int)*n);
    for(i=0;i<n;++i){
        char wk[128];
        fprintf(stderr,"input symbol [%d]:", i+1);
        scanf(" %s", wk);
        symbols[i] = strdup(wk);
        fprintf(stderr,"maximum number of \"%s\":",wk);
        scanf(" %d", &times[i]);
    }

    print(symbols, times, n);

    {   //release the allocated area
        for(i=0;i<n;++i){
            free(symbols[i]);
        }
        free(symbols);
        free(times);
    }
    return 0;
}


text:
Q: xlPastevalues is giving me an object defined error VBA Sub foo()

Dim ws As Worksheet: Set ws = Sheets("inbd")
Dim wsDestination As Worksheet: Set wsDestination = Sheets("test")

LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    ws.Range("A1:N" & LastRow).AutoFilter Field:=1,
Criteria1:=Worksheets("test").Cells(1, 26).Value
    ws.Range("f2:f" & LastRow).SpecialCells(xlCellTypeVisible).Copy Range("C6")
DestinationRow = wsDestination.Cells(wsDestination.Rows.Count, "C").End(xlUp).Row + 1
    wsDestination.Range("C" & DestinationRow).PasteSpecial xlPasteValues

Application.CutCopyMode = False
ws.Range("A1:N" & LastRow).AutoFilter Field:=1

End Sub

Good evening, Paste values part is giving me an object defined error and I don't know why

A: You want a test to ensure there are visible cells to copy from:
If Application.WorksheetFunction.Countif(ws.Range("A1:N" & LastRow),Worksheets("test").Cells(1, 26).Value) > 0

. A test that you have more than one cell for your filter
If LastRow > 1

and you also have already pasted with this line:
ws.Range("F2:F" & LastRow).SpecialCells(xlCellTypeVisible).Copy Range("C6")

You pasted to C6 and now have an empty clipboard so cannot paste again.
Perhaps you wanted:
ws.Range("F2:F" & LastRow).SpecialCells(xlCellTypeVisible).Copy
DestinationRow = wsDestination.Cells(wsDestination.Rows.Count, "C").End(xlUp).Row + 1
wsDestination.Range("C" & DestinationRow).PasteSpecial xlPasteValues

A: You have already pasted the copied cells into the inbd sheet C6.
Your code does not make much sense. You determine the last row of data before you filter, you copy and paste, then you paste again. I suggest you first filter, then determine the last row in both sheets, then do the copy and paste special right after one another without the wrong paste to C6 step.


text:
Q: Can't create accounts in a java program I have to write a program which creates 4 different accounts and outputs them using different constructors.
I have no idea how to use the default constructor to make an account for certain users, because there are no parameters in the constructor and the instructions did not have a method to take the name. (This is also not based on user input, but pre-set).
Any ideas would be helpful.


text:
Q: Understanding access_process_vm linux kernel? I am writing a kernel module which reads parts of the virtual memory of a process. I am trying to use the access_process_vm method in the kernel to do so, but it always ends up reading 0 bytes.
  target = get_pid_task(find_get_pid(target_pid),PIDTYPE_PID);
  if (target == NULL) {
      printk(KERN_ALERT "no such task %d\n",target_pid);
      return -1;
  }
  printk(KERN_INFO "opened task with pid %d\n",target->pid);

  len = vm_end-vm_start;
  buf = kmalloc(len ,GFP_KERNEL);
  if (!buf) {
      printk(KERN_ALERT "unable to allocate memory\n");
      return -1;
  }
  printk(KERN_INFO "allocated memory\n");

  bytes = access_process_vm(target,addr,buf,len,FOLL_FORCE);
  if (bytes != len) {
       printk(KERN_ALERT "could only read %d of %ld bytes\n",bytes,len);
       kfree(buf);
       return -1;
  }
  printk(KERN_INFO "read %d bytes successfully\n",bytes);

What am I doing wrong?

A: I don't see what's the problem tracking this down.
Let's take a look at first 2 failure modes in access_process_vm itself:
   if (addr + len < addr)
            return 0;

You compute the len based on vm_end and vm_start, but you read starting from addr. What's up with the discrepancy? Perhaps you end up failing this check?
   mm = get_task_mm(tsk);
   if (!mm)
           return 0;

How about this? What if there is no mm?
And so on.
Also note you are returning -1 instead of an actual error. You are leaking a reference to the target thread on error.


text:
Q: ThreadPool works unpredictable I have simple task:
There is list of arrays and I need to find numbers that divide by 10 in all of them using threadpool.
Here is my code
import java.util.List;
Runnable implementation:
public class MyRunnable implements Runnable {
    private List<Integer> numbers;
    private int[] arrayToFind;

    public MyRunnable(List<Integer> numbers, int[] arrayToFind) {
        this.numbers = numbers;
        this.arrayToFind = arrayToFind;
    }

    private boolean isNumber(int n) {
        return n % 10 == 0;
    }

    @Override
    public void run() {
        for (int i = 0; i < arrayToFind.length; i++) {
            if (isNumber(arrayToFind[i]))
                numbers.add(arrayToFind[i]);
        }
    }
}

Main class:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

    public static void main(String... args) throws InterruptedException{
        int[] arr1 = new int[] {10};
        int[] arr2 = new int[] {400};
        int[] arr3 = new int[] {20};
        int[] arr4 = new int[] {40};
        List<int[]> list = new ArrayList<int[]>();
        list.add(arr1);
        list.add(arr2);
        list.add(arr3);
        list.add(arr4);

        List<Integer> result = new ArrayList<Integer>();

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int[] array : list) {
            executorService.execute(new MyRunnable(result, array));
        }
        executorService.shutdown();

        System.out.println(result);
    }
}

The problem is that output sometimes is correct as it should be {10, 20, 40, 400} but sometimes it is {}, sometimes it is {40, 20} etc..
How could you explain this?

A: Insertions into a list by default are not synchronized, thus not thread safe.  If you want to achieve thread safety (so you don't lose data), then wrap your instance inside of Collections.synchronizedList.
List<Integer> result = Collections.synchronizedList(new ArrayList<Integer>());

Now your results will all appear (still in nondeterministic order, of course).

A: In the API for ExecutorService.shutdown, it says: "This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that."
Try using awaitTermination. I bet that will fix your problem

A: It seems that sometimes ExecutorService shutdowns until some or your MyRunnable.run are finished. Generally speaking, ExecutorService.execute+Runnable allow you to do "some work" in parallel when you aren't interested in the result. If you need to wait until all results are calculated, use ExecutorService.invokeAll+Callable. See for example:
http://tutorials.jenkov.com/java-util-concurrent/executorservice.html
And, finally, store the result of calculation in a thread safe collection:
public static class MyCallable implements Callable<Boolean> {
    private Set<Integer> numbers;
    private int[] arrayToFind;

    public MyCallable(Set<Integer> numbers, int[] arrayToFind) {
        this.numbers = numbers;
        this.arrayToFind = arrayToFind;
    }

    private boolean isNumber(int n) {
        return n % 10 == 0;
    }

    @Override
    public Boolean call() {
        for (int i = 0; i < arrayToFind.length; i++) {
            if (isNumber(arrayToFind[i]))
                numbers.add(arrayToFind[i]);
        }
        return true;
    }
}

public static void main(String... args) throws InterruptedException{
    int[] arr1 = new int[] {10};
    int[] arr2 = new int[] {400};
    int[] arr3 = new int[] {20};
    int[] arr4 = new int[] {40};
    List<int[]> list = new ArrayList<>();
    list.add(arr1);
    list.add(arr2);
    list.add(arr3);
    list.add(arr4);

    Set<Integer> result = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());
    List<MyCallable> myCallables = new ArrayList<>();
    for (int[] array : list) {
        myCallables.add(new MyCallable(result, array));
    }
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    executorService.invokeAll(myCallables);
    executorService.shutdown();
    System.out.println(result);
}

A: You are not waiting for the tasks to complete, before printing out the result. That's why the inconsistency. Instead of execute, use submit method to submit tasks to executor as it returns you a Future instance, which can be used to wait for the task to complete.
Checkout the Future's javadoc
public static void main(String[] args) throws InterruptedException, ExecutionException {
    int[] arr1 = new int[] { 10 };
    int[] arr2 = new int[] { 400 };
    int[] arr3 = new int[] { 20 };
    int[] arr4 = new int[] { 40 };
    List<int[]> list = new ArrayList<int[]>();
    list.add(arr1);
    list.add(arr2);
    list.add(arr3);
    list.add(arr4);

    List<Integer> result = new ArrayList<Integer>();
    List<Future<?>> futures = new ArrayList<Future<?>>();
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    for (int[] array : list) {
        futures.add(executorService.submit(new MyRunnable(result, array)));
    }
    executorService.shutdown();

    for (Future<?> future : futures) {
        future.get();
    }

    System.out.println(result);
}


text:
Q: Upload Image Firebase Ionic 3 I would like to save image in Storage and database Firebase with ionic , but I don't to save in this page I get Image data I have takePicure that get image and uploadInformation that send datas to service
help someone my code bellow
takeImage.ts
    takePicture() {
    this.photo = '';
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      allowEdit: true,
      // correctOrientation: false,
      targetWidth: 1000,
      targetHeight: 1000
    }
    this.camera.getPicture(options)
              .then((imageDate) => {
                let base64image = 'data:image/jpeg;base64,' + imageDate;
                this.photo = base64image;
                // this.userService.uploadToStorage(this.user.user_id, this.photo, 'citizens')
                this.uploadInformation(this.photo);
                console.log(this.photo)
              }, (error) => {
                console.log(error)
              })
              .catch((error) => {
                console.log(error)
              })
  }

    uploadInformation(info) {
     let upload = this.userService.uploadToStorage(info);
     upload.then().then(res => {
       this.userService.storeInfoToDatabase(this.user.key, res.metadata)
         .then(() => {
           alert('Inserido com sucesso so colocar o toast depois')
         })
     })
   }

Now in my service I have this code and the storeInfoToDatabase method received 2 parameters user.key and image name
service.ts
    uploadToStorage(information: any): AngularFireUploadTask {
    let newName = information + '.png';
    return this.afs.ref(`users/citizens/${newName}`).putString(information, 'base64');
  }

  storeInfoToDatabase(user_id, metainfo) {
    let toSAve = {
      url: metainfo.downloadURLs[0],
      fullPath: metainfo.fullPath,
      contentType: metainfo.contentType,
    }
    return this.db.list(`${this.PATH}/citizens`).update(user_id, (toSAve))
  }

help me someone how can I to save in Firestora and Database ...?

A: you can use angular-firebase npm package it is simple and easy to use
npm install angular-firebase

you can simply upload the captured base 64 image
with this code
this.firebase.uploadString(encodedFile,'images/1.jpg','base64',
(value)=>{
    console.log('Upload progress :'+ value + '% uploaded');
    // event detect the data uploaded  used to monitor the persentage of the download process
    // this will return 'Upload progress : 24% uploaded'
    // this part will run multiple times until the upload complete
// for example
}).then((url)=>{
    console.log(url);
    // the URL of uploaded file or image,
    // this part run once when the upload complete
});


text:
Q: If the number of positive integer $n$ for which $n \leq 1991$ and $6$ is a factor of $n^2 + 3n + 2$ is given by $K$, Find the value of $\sqrt{K - 32}$ I tried by factorising $n^2 + 3n + 2$ into $(n + 1)(n + 2)$ and tried by
assuming $ n = 2k + 1 $ and $ n = 2k $ for odd and even respectively and puting them in place of n
For odd : $(2k + 2)(2k+ 3)$ $\Rightarrow$ $2k + 3$ should be divisible by 3
For even :
$(2k + 1)(2k + 2)$ $\Rightarrow$ $2k + 1$ should be divisible by 3
But I can't proceed any further... Can anyone explain how to go through this question?

A: Hint: for positive integer $n$, $(n+1)(n+2)$ is divisible by $6$ if and only if $n$ is not divisible by $3$.
This is because $(n+1)(n+2)$ is even, and if $n$ is not divisible by $3$, one of $ n+1, n+2$ would be. If $n$ is divisible by $3$, the situation reverses.

A: Observe that:
$$(n+6)^2 + 3(n+6) + 2 = n^2+12n+36+3n+18+2 = (n^2+3n+2) + 12n+36+18$$
$$ = (n^2+3n+2) + 6(2n+6+3).$$
Therefore, if $n^2+3n+2$ is divisible by $6$, then $(n+6)^2 + 3(n+6) + 2$ is as well. If $n^2+3n+6$ is not divisible by $6$, $(n+6)^2 + 3(n+6) + 2$ is also not divisible by $6$.
Find which $n$ where $1 ≤ n ≤ 6$ the statement is true for. Then, since all natural numbers have remainders from $1$ to $6$ ($0$) when divided by $6$, you can extend this to all natural numbers.

A: Let $f(n)=(n+1)(n+2)$. Each six consecutive integers from $n=1$ till $n=1991$ contains two numbers $f(n)$ which have not $6$ as a factor and these are $$3,6,9,12,\cdots,1989$$ They formed an evident arithmetic progression so there are $1989:3=663$ numbers involved that are not multiples of $6$. It follows that one has $1991-663=1328$ numbers having $6$ as a factor.
Thus $K=1328$ and the asked number is then $\sqrt{1296}=36$.


text:
Q: execute method from referenced class library before build .NET application for license checking I'm developing a class library which should be licensed to specific developer computers. There are no components so that the design time licensing checks can't be done.
This check is in fact unavailable for pure class libraries:
if( LicenseContext.UsageMode == LicenseUsageMode.Designtime ) ...

One has suggested to use Debugger.IsAttached to check if the lib is used on the developer machine:
Design-Time validation of library
But I'm looking after a solution on the build stage, so that the program won't build if the license is invalid (e.G. this machine is not licensed). Any suggestions?

A: I think it is impossible or very hard to do license check in compile / build time. It is hard for you to force something to happen (like license check) in build time.
For licensing take a look at Rhino Licensing. Maybe you can make an obfuscated version without license check, and an normal version with a license check.
But any license protection can be hacked.


text:
Q: How to I make sure that curl doesn't fail a script? How do I make sure curl errors doesn't fail a script? I want to send all errors from curl to Dev null so that it doesn't fail a script and the script keeps going
What's the proper curl command to do that.
I tried curl --fail http://...
For curl to fail silently

A: Have you tried:
curl http://.../ || true

And if you want to hide any error output, have you tried:
curl http://.../ 2>/dev/null || true

(Note: Untested.)


text:
Q: Jupyter Notebook - Attribute Error: 'module' object has no attribute 'F_OK' Whenever I type in the command "jupyter notebook" it is giving me the attribute error listed above. I am running it through the Anaconda Prompt.
What is in the prompt window:
(base) C:\Users\jj891w>jupyter notebook
Traceback (most recent call last):
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\Scripts\jupyter-notebo
ok-script.py", line 10, in <module>
    sys.exit(main())
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\jupy
ter_core\application.py", line 266, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\trai
tlets\config\application.py", line 657, in launch_instance
    app.initialize(argv)
  File "<decorator-gen-7>", line 2, in initialize
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\trai
tlets\config\application.py", line 87, in catch_config_error
    return method(app, *args, **kwargs)
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\note
book\notebookapp.py", line 1630, in initialize
    self.init_terminals()
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\note
book\notebookapp.py", line 1459, in init_terminals
    from .terminal import initialize
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\note
book\terminal\__init__.py", line 3, in <module>
    import terminado
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\term
inado\__init__.py", line 8, in <module>
    from .management import (TermManagerBase, SingleTermManager,
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\term
inado\management.py", line 25, in <module>
    from winpty import PtyProcess as PtyProcessUnicode
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\winp
ty\__init__.py", line 11, in <module>
    from .ptyprocess import PtyProcess
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\winp
ty\ptyprocess.py", line 17, in <module>
    from backports.shutil_which import which
  File "C:\Users\jj891w\AppData\Local\Continuum\anaconda2\lib\site-packages\back
ports\shutil_which.py", line 12, in <module>
    def backport_which(cmd, mode=os.F_OK | os.X_OK, path=None):
AttributeError: 'module' object has no attribute 'F_OK'

A: I came across the same problem. I got around it by downgrading anaconda and Python.
conda install anaconda=5.2.0 python=3.6


text:
Q: How to read and insert correct highchart number in selectors using Selenium Webdriver with Python? I am testing a web application that uses highcharts. The selectors look like this, and the highchart number of the same chart is always different.
#highcharts-3 >div:nth-child(1) > span > div > span

How can I get the right highchart number of the chart I am on and then insert that number it in my selectors?

A: You do not need to "extract" the number, instead you can use the CSS3 [attribute^=value] Selector:
[id^='highcharts-'] > div:nth-child(1) > span > div > span

This will select the first element where the id begins with the string 'highcharts-'.


text:
Q: Permanently Disable a button on a button click I have been trying to disable a button completely (even when the app is closed).
I have been trying to disable a button completely (even when the app is closed) using shared preference and it worked. However, I accidentally deleted the file and cannot get it to work again. I have looked at the examples from the same question but it does not work for me.
com.example.new.app;

import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

SharedPreferences spStateButton;
SharedPreferences.Editor spEditor;
int clickcount=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText passWord = (EditText) findViewById(R.id.edittext);
    final Button loginButton = (Button) findViewById(R.id.button);
    spStateButton= getApplicationContext().getSharedPreferences("Button_State", 0);
    spEditor = spStateButton.edit();

    loginButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if(passWord.getText().toString().equals("123456")) {
                Intent i = new Intent();
                i.setComponent(new ComponentName(MainActivity.this,Unlocked.class));
                startActivity(i);

            }else{
                passWord.setText("");
                Toast.makeText(getBaseContext(),  "Wrong", Toast.LENGTH_LONG).show();
                clickcount=clickcount+1;

            }if (clickcount==5){
                        setButtonState(false);

        }
    };

        public void setButtonState(boolean enabled) {
            spEditor.putBoolean("btn_state", enabled);
            loginButton.setEnabled(getButtonState());

            spEditor.commit();
        }

        public boolean getButtonState(){
            return spStateButton.getBoolean("btn_state", true);
        }

    });

}}

A: Your state is not committed so you are working with old value. You are committing after setting button state. You can reuse the value you are setting your next button state
public void setButtonState(boolean enabled) {
    spEditor.putBoolean("btn_state", enabled);
    loginButton.setEnabled(enabled);

    spEditor.commit();
}

You asked for explanation:

*

*You are setting a new value of btn_state in shared preferences editor

*You want to read that value from shared preferences (spStateButton.getBoolean("btn_state", true);) but it's not there yet because you haven't committed it.

*You are committing value/writing value to shared preferences this is executed async.

A: You forgot to call loginButton.setEnabled(getButtonState()); when the app starts. Also, you need to move the setButtonState and getButtonState out of the onCreate() method.
Here is the correct MainActivity:
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    SharedPreferences spStateButton;
    SharedPreferences.Editor spEditor;
    int clickcount = 0;

    Button loginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText passWord = (EditText) findViewById(R.id.edittext);
        loginButton = (Button) findViewById(R.id.button);
        spStateButton = getApplicationContext().getSharedPreferences("Button_State", 0);
        spEditor = spStateButton.edit();

        loginButton.setEnabled(getButtonState()); // You forgot it :)

        loginButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (passWord.getText().toString().equals("123456")) {
                    Intent i = new Intent();
                    i.setComponent(new ComponentName(MainActivity.this, Unlocked.class));
                    startActivity(i);

                } else {
                    passWord.setText("");
                    Toast.makeText(getBaseContext(), "Wrong", Toast.LENGTH_LONG).show();
                    clickcount = clickcount + 1;

                }
                if (clickcount == 5) {
                    setButtonState(false);

                }
            }

        });
    }

    public void setButtonState(boolean enabled){
        spEditor.putBoolean("btn_state", enabled);
        loginButton.setEnabled(getButtonState());

        spEditor.commit();
    }

    public boolean getButtonState() {
        return spStateButton.getBoolean("btn_state", true);
    }
}

A: If(isDisabled()){
button.setEnabled(false);}
isDisabled(){
// get state from shrdPref
}


text:
Q: How can I change facebook share button image? I am using Facebook share button in my website. But it's a default share button from facebook developer site. I don't know how can i use my own custom png image in place of default share button. I studied the facebook developer tutorials too but couldn't get any help from there. I also googled and searched in various websites, but no help is there regarding my existing code. I guess, its not included there. Here is my code:
In header.php:

In one of my dynamic page, i have facebook share button:

bus_url . '/' . $this->deal_url . '" data-layout="button">

So how can I use my own custom png image by modifying this existing code?

A: You can use your own image for the Share Button by opening a popup for sharer.php with Javascript or by using the FB.ui Share Dialog: https://developers.facebook.com/docs/sharing/reference/share-dialog
sharer.php does not even need an App: https://www.facebook.com/sharer/sharer.php?u=[urlencoded-url]

A: 1) Create a simple anchor tag link with the image you want to show. Have a onclick method on anchor tag which would actually do the real job.

2) Next, we create the Javascript function which will show the actual popup and will fetch the complete user information, if user allows. We also handle the scenario if user disallows our facebook app.
 window.fbAsyncInit = function() {
FB.init({
    appId   : 'YOUR_APP_ID',
    oauth   : true,
    status  : true, // check login status
    cookie  : true, // enable cookies to allow the server to access the session
    xfbml   : true // parse XFBML
});

 };

function fb_login(){
FB.login(function(response) {

    if (response.authResponse) {
        console.log('Welcome!  Fetching your information.... ');
        //console.log(response); // dump complete info
        access_token = response.authResponse.accessToken; //get access token
        user_id = response.authResponse.userID; //get FB UID

        FB.api('/me', function(response) {
            user_email = response.email; //get user email
      // you can store this data into your database
        });

    } else {
        //user hit cancel button
        console.log('User cancelled login or did not fully authorize.');

    }
}, {
    scope: 'publish_stream,email'
});
}
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());

A: right click on the button that you want to change "Inspect element" and find out if it really is an image or a CSS if it's an image find where the image is and upload your file with the same name ontop of the old one or if it's a CSS look for a button generator in google and just paste the code from there.


text:
Q: Spring Redis Stream consumer stops consuming messages (Address already in use) I tried to test redis streams with spring-data-redis.
I've implemented two aplications - first one adds records to the stream, second one consumes messages from the stream.
It works, but after some time (usually after already 80000+ messages were processed) the 'consumer app' throws an exception: "org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis; nested exception is java.util.concurrent.CompletionException: io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379"
I have installed Redis 6.2.1 on Ubuntu (win10 linux subsystem) and run it with default configuration (port is 6379). The same happens when I run Redis in Docker.
I have tested Redis performance, so messages were added in a loop with no delay.
I add messages to stream as:
ObjectRecord<String, String> record = StreamRecords.newRecord()
                .ofObject(message)
                .withStreamKey("my-stream");

redisTemplate.opsForStream()
                .add(record);

I consume the messages as:
StreamReceiver.StreamReceiverOptions<String, MapRecord<String, String, String>> options =
                StreamReceiver.StreamReceiverOptions.builder()
                        .pollTimeout(Duration.ofSeconds(2))
                        .build();

StreamReceiver<String, MapRecord<String, String, String>> receiver = StreamReceiver.create(connectionFactory, options);
        Flux<MapRecord<String, String, String>> messages = receiver.receive(StreamOffset.fromStart("my-tream"));

messages.subscribe(new StreamSubscriber());

where StreamSubscriber is just my org.reactivestreams.Subscriber implementation. I tried also StreamMessageListenerContainer approach, but the result is the same.
org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis; nested exception is java.util.concurrent.CompletionException: io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379
    at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.translateException(LettuceConnectionFactory.java:1553)
    at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.lambda$getConnectionAsync$0(LettuceConnectionFactory.java:1491)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
    at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2088)
    at io.lettuce.core.DefaultConnectionFuture.lambda$null$0(DefaultConnectionFuture.java:257)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenCompleteStage(CompletableFuture.java:883)
    at java.base/java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:2251)
    at java.base/java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:143)
    at io.lettuce.core.DefaultConnectionFuture.lambda$thenCompose$1(DefaultConnectionFuture.java:254)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
    at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2088)
    at io.lettuce.core.AbstractRedisClient.lambda$initializeChannelAsync0$4(AbstractRedisClient.java:405)
    at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:578)
    at io.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:571)
    at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:550)
    at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:491)
    at io.netty.util.concurrent.DefaultPromise.setValue0(DefaultPromise.java:616)
    at io.netty.util.concurrent.DefaultPromise.setFailure0(DefaultPromise.java:609)
    at io.netty.util.concurrent.DefaultPromise.tryFailure(DefaultPromise.java:117)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.fulfillConnectPromise(AbstractNioChannel.java:321)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:337)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:707)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.util.concurrent.CompletionException: io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379
    at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:331)
    at java.base/java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:346)
    at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:632)
    ... 30 more
Caused by: io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379
    at io.lettuce.core.RedisConnectionException.create(RedisConnectionException.java:78)
    at io.lettuce.core.RedisConnectionException.create(RedisConnectionException.java:56)
    at io.lettuce.core.RedisClient.lambda$transformAsyncConnectionException$20(RedisClient.java:767)
    at io.lettuce.core.DefaultConnectionFuture.lambda$thenCompose$1(DefaultConnectionFuture.java:253)
    ... 22 more
Caused by: java.util.concurrent.CompletionException: io.netty.channel.AbstractChannel$AnnotatedSocketException: Address already in use: no further information: localhost/127.0.0.1:6379
    at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:331)
    at java.base/java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:346)
    at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:632)
    ... 20 more
Caused by: io.netty.channel.AbstractChannel$AnnotatedSocketException: Address already in use: no further information: localhost/127.0.0.1:6379
Caused by: java.net.BindException: Address already in use: no further information
    at java.base/sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at java.base/sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:779)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:330)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:707)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.base/java.lang.Thread.run(Thread.java:834)

RedisTemplate and LettuceConnectionFactory were created and autoconfigured by springboot (i have tried some also custom configuration, but with no success)
What I have also observed is that redis connection is closed after message was send to the stream and new connection is created when the new message is going to be sent.
2021-04-11 09:12:11.455 DEBUG 20952 --- [input/provider1] sk.kedros.learn.camel.redis.Publisher    : sending message: {"obuSn":"eeee00a5-616e-46ad-80e4-50780fab1336","lon":0.0,"lat":0.0,"data":"99761 - provider1"}
2021-04-11 09:12:11.455 DEBUG 20952 --- [input/provider1] o.s.d.redis.core.RedisConnectionUtils    : Fetching Redis Connection from RedisConnectionFactory
2021-04-11 09:12:11.455 DEBUG 20952 --- [input/provider1] io.lettuce.core.RedisChannelHandler      : dispatching command AsyncCommand [type=XADD, output=StatusOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command]
2021-04-11 09:12:11.455 DEBUG 20952 --- [input/provider1] i.lettuce.core.protocol.DefaultEndpoint  : [channel=0xbb31e231, /127.0.0.1:51322 -> localhost/127.0.0.1:6379, epid=0x1] write() writeAndFlush command AsyncCommand [type=XADD, output=StatusOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command]
2021-04-11 09:12:11.455 DEBUG 20952 --- [input/provider1] i.lettuce.core.protocol.DefaultEndpoint  : [channel=0xbb31e231, /127.0.0.1:51322 -> localhost/127.0.0.1:6379, epid=0x1] write() done
2021-04-11 09:12:11.455 DEBUG 20952 --- [ioEventLoop-4-1] io.lettuce.core.protocol.CommandHandler  : [channel=0xbb31e231, /127.0.0.1:51322 -> localhost/127.0.0.1:6379, chid=0x1] write(ctx, AsyncCommand [type=XADD, output=StatusOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command], promise)
2021-04-11 09:12:11.455 DEBUG 20952 --- [ioEventLoop-4-1] io.lettuce.core.protocol.CommandEncoder  : [channel=0xbb31e231, /127.0.0.1:51322 -> localhost/127.0.0.1:6379] writing command AsyncCommand [type=XADD, output=StatusOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command]
2021-04-11 09:12:11.455 DEBUG 20952 --- [ioEventLoop-4-1] io.lettuce.core.protocol.CommandHandler  : [channel=0xbb31e231, /127.0.0.1:51322 -> localhost/127.0.0.1:6379, chid=0x1] Received: 22 bytes, 1 commands in the stack
2021-04-11 09:12:11.455 DEBUG 20952 --- [ioEventLoop-4-1] io.lettuce.core.protocol.CommandHandler  : [channel=0xbb31e231, /127.0.0.1:51322 -> localhost/127.0.0.1:6379, chid=0x1] Stack contains: 1 commands
2021-04-11 09:12:11.455 DEBUG 20952 --- [ioEventLoop-4-1] i.l.core.protocol.RedisStateMachine      : Decode done, empty stack: true
2021-04-11 09:12:11.455 DEBUG 20952 --- [ioEventLoop-4-1] io.lettuce.core.protocol.CommandHandler  : [channel=0xbb31e231, /127.0.0.1:51322 -> localhost/127.0.0.1:6379, chid=0x1] Completing command AsyncCommand [type=XADD, output=StatusOutput [output=1618125131455-2, error='null'], commandType=io.lettuce.core.protocol.Command]
2021-04-11 09:12:11.455 DEBUG 20952 --- [input/provider1] o.s.d.redis.core.RedisConnectionUtils    : Closing Redis Connection.

that also influences Redis connection of the 'consumer app' - where the redis connections are opened and closed periodically.
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] o.s.d.r.stream.DefaultStreamReceiver     : [stream: loc] onStreamMessage(MapBackedRecord{recordId=1618125112425-0, kvMap={payload={"obuSn":"d066bdd7-21b5-46f0-81ca-09afe4fd6596","lon":0.0,"lat":1.0,"data":"68541 - provider1"}}}): Emitting item, slow-path
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] i.l.core.protocol.RedisStateMachine      : Decode done, empty stack: true
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] io.lettuce.core.protocol.CommandHandler  : [channel=0x896e94aa, /127.0.0.1:65535 -> localhost/127.0.0.1:6379, chid=0x3bdf] Completing command SubscriptionCommand [type=XREAD, output=StreamReadOutput [output=[], error='null'], commandType=io.lettuce.core.protocol.Command]
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] io.lettuce.core.RedisChannelHandler      : closeAsync()
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] i.lettuce.core.protocol.DefaultEndpoint  : [channel=0x896e94aa, /127.0.0.1:65535 -> localhost/127.0.0.1:6379, epid=0x3bdf] closeAsync()
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] o.s.d.r.stream.DefaultStreamReceiver     : [stream: loc] onComplete()
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] o.s.d.r.stream.DefaultStreamReceiver     : [stream: loc] scheduleIfRequired()
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] o.s.d.r.stream.DefaultStreamReceiver     : [stream: loc] scheduleIfRequired(): Activating subscription
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] o.s.d.r.stream.DefaultStreamReceiver     : [stream: loc] scheduleIfRequired(): Activating subscription, offset ReadOffset(offset=1618125112425-0)
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] io.lettuce.core.RedisClient              : Trying to get a Redis connection for: redis://localhost
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] io.lettuce.core.RedisClient              : Resolved SocketAddress localhost:6379 using redis://localhost
2021-04-11 09:11:52.426 DEBUG 21636 --- [ioEventLoop-4-7] io.lettuce.core.AbstractRedisClient      : Connecting to Redis at localhost:6379
2021-04-11 09:11:52.427 DEBUG 21636 --- [ioEventLoop-4-7] io.lettuce.core.protocol.CommandHandler  : [channel=0x896e94aa, /127.0.0.1:65535 -> localhost/127.0.0.1:6379, chid=0x3bdf] channelInactive()
2021-04-11 09:11:52.427 DEBUG 21636 --- [ioEventLoop-4-8] io.lettuce.core.protocol.CommandHandler  : [channel=0x87e269ec, [id: 0x6e14c57c] (inactive), chid=0x3be0] channelRegistered()
2021-04-11 09:11:52.427 DEBUG 21636 --- [ioEventLoop-4-7] i.lettuce.core.protocol.DefaultEndpoint  : [channel=0x896e94aa, /127.0.0.1:65535 -> localhost/127.0.0.1:6379, epid=0x3bdf] deactivating endpoint handler
2021-04-11 09:11:52.427 DEBUG 21636 --- [ioEventLoop-4-7] io.lettuce.core.protocol.CommandHandler  : [channel=0x896e94aa, /127.0.0.1:65535 -> localhost/127.0.0.1:6379, chid=0x3bdf] channelInactive() done
2021-04-11 09:11:52.427 DEBUG 21636 --- [ioEventLoop-4-7] i.l.core.protocol.ConnectionWatchdog     : [channel=0x896e94aa, /127.0.0.1:65535 -> localhost/127.0.0.1:6379, last known addr=localhost/127.0.0.1:6379] channelInactive()
2021-04-11 09:11:52.427 DEBUG 21636 --- [ioEventLoop-4-7] i.l.core.protocol.ConnectionWatchdog     : [channel=0x896e94aa, /127.0.0.1:65535 -> localhost/127.0.0.1:6379, last known addr=localhost/127.0.0.1:6379] Reconnect scheduling disabled
2021-04-11 09:11:52.427 DEBUG 21636 --- [ioEventLoop-4-7] io.lettuce.core.protocol.CommandHandler  : [channel=0x896e94aa, /127.0.0.1:65535 -> localhost/127.0.0.1:6379, chid=0x3bdf] channelUnregistered()
2021-04-11 09:11:52.432 DEBUG 21636 --- [ioEventLoop-4-8] io.lettuce.core.AbstractRedisClient      : Connecting to Redis at localhost:6379: localhost:6379

io.netty.channel.AbstractChannel$AnnotatedSocketException: Address already in use: no further information: localhost/127.0.0.1:6379
Caused by: java.net.BindException: Address already in use: no further information
    at java.base/sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[na:na]

As I mentioned, it works fine for some time, but finally it ends with Address already in use: no further information
Am I missing something? Is it Redis installation/configuration problem? Or is it lettuce client problem? Or?

A: Probably Your Redis server gets crashed due to lack of memory. allocate more memory to your server or you can perform stream maxlen operation either for Redis stream so that the Redis server has the consistency of memory size.


text:
Q: Snap.svg — consecutive transformations saving previous state I'm trying to apply some transformations as reaction for user input to a group of elements and I'm pretty sure I do it wrong:
var SVG_WIDTH = window.innerWidth,
    SVG_HEIGHT = window.innerHeight,
    SVG_CENTER_X = Math.floor(SVG_WIDTH / 2),
    SVG_CENTER_Y = Math.floor(SVG_HEIGHT / 2),
    s = Snap(SVG_WIDTH, SVG_HEIGHT),

    obj = new myObj(SVG_CENTER_X, SVG_CENTER_Y);
    obj.drawIt();

function myObj( x, y ) {

    var that = this;

    this.x = x;
    this.y = y;

    this.is_scaled = false;
    this.angle = 0;

    this.g = s.group();

    this.drawIt = function() {
        var a = s.rect(this.x, this.y, 50, 50, 0, 0).attr({'fill':'#E82941'});
        a.appendTo(this.g);
    };

    this.moveIt = function( dx, dy ) {

        var relative_dx = dx,
            relative_dy = dy;

        switch ( that.angle ) {
            case 0: {
                break;
            }
            case 90: {
                relative_dx = dy;
                relative_dy = -dx;
                break;
            }
            case 180: {
                relative_dx = -dx;
                relative_dy = -dy;
                break;
            }
            case 270: {
                relative_dx = -dy;
                relative_dy = dx;
                break;
            }
        }

        var old_matrix = that.g.transform().localMatrix,
            new_matrix = old_matrix.translate(relative_dx, relative_dy),
            new_string = new_matrix.toTransformString();

            that.g.animate({'transform':new_string}, 200, mina.linear);
   };

    this.rotateIt = function( angle ) {
        var old_matrix = that.g.transform().localMatrix,
            new_matrix = old_matrix.rotate(angle, that.x + 25, that.y + 25),
            new_string = new_matrix.toTransformString();

            that.g.animate({'transform':new_string}, 200, mina.linear);

            that.angle = Math.abs((that.angle + angle) % 360);
    };

    this.scaleIt = function() {

        var factor = 2;

        if (that.is_scaled) {
            factor = 0.5;
            that.is_scaled = false;
        } else {
            that.is_scaled = true;
        }

        var old_matrix = that.g.transform().localMatrix,
            new_matrix = old_matrix.scale(factor, factor, that.x + 25, that.y +25),
            new_string = new_matrix.toTransformString();

            that.g.animate({'transform':new_string}, 200, mina.linear);
    };
}

document.onkeypress = function ( e ) {

    switch ( e.charCode ) {
        case 97: { // A
            obj.moveIt(-50, 0);
            break;
        }
        case 100: { // D
            obj.moveIt(50, 0);
            break;
        }
        case 114: { // R
            obj.rotateIt(90);
            break;
        }
        case 115: { // S
            obj.moveIt(0, 50);
            break;
        }
        case 119: { // W
            obj.moveIt(0, -50);
            break;
        }
        case 122: { // Z
            obj.scaleIt(2);
            break;
        }
    }
};

Here is a codepen: http://codepen.io/GeMir/pen/GJMPQP?editors=001
WASD-Translations work just well.
Scaling works well too (zoom in/zoom out with object center as origin point).
Rotation works almost well, but only after some scalings (???).
The rectangle should rotate clockwise around its center and there should be no "jump" while rotating from 270 to 360 degrees (now it rotates to 0 degrees counterclockwise instead).


text:
Q: Two Images Running in 1 Container in Azure Container Instance I have two images uploaded into the same Azure Container Registry and the same repoistory. How do I run these two images together in a same container.
Thanks in advance :)
Currently this is my YAML code.
apiVersion: 2018-10-01
location: eastus
name: web-mongo
properties:
  containers:
  - name: web
    properties:
      image: *.azurecr.io/phase1:1357
      resources:
        requests:
          cpu: 2
          memoryInGb: 10
      ports:
      - port: 80
  - name: mongo
    properties:
      image: *.azurecr.io/phase1:latest
      resources:
        requests:
          cpu: 2
          memoryInGb: 10
  osType: Linux
  ipAddress:
    type: Public
    ports:
    - protocol: tcp
      port: '80'
type: Microsoft.ContainerInstance/containerGroups
imageRegistryCredentials:
  - server: *.azurecr.io
    username: *
    password: ***

A: For your requirements, you can use the YAML file to achieve it. I assume you upload the two images to the ACR in the same repository with different tags. Then you can run the two images together in the only one container group like this:
apiVersion: 2018-10-01
location: eastus
name: myContainerGroup
properties:
  containers:
  - name: aci-tutorial-app
    properties:
      image: acr_name.azurecr.io/image_name:tag1
      resources:
        requests:
          cpu: 1
          memoryInGb: 1.5
      ports:
      - port: 80
      - port: 8080
  - name: aci-tutorial-sidecar
    properties:
      image: acr_name.azurecr.io/image_name:tag2
      resources:
        requests:
          cpu: 1
          memoryInGb: 1.5
  osType: Linux
  ipAddress:
    type: Public
    ports:
    - protocol: tcp
      port: '80'
    - protocol: tcp
      port: '8080'
tags: null
type: Microsoft.ContainerInstance/containerGroups
imageRegistryCredentials:
  - server: imageRegistryLoginServer
    username: imageRegistryUsername
    password: imageRegistryPassword

You can get more details about Deploy a multi-container group using a YAML file. The Azure Template also can achieve it. You can choose one as you want.