text:
Q: Histogram highchart series not correctly displaying on the first load in angular application I have implemented histogram highchart in angular 4 application. I basically want to enable toggling of the legends. So at any one point of time,one legend would be enabled which means only the series of that legend should be enabled. The toggling works perfectly fine, but the first time the histogram loads it shows a faded background drawn over the selected series. Please note that as soon as i click the legend the series loads fine. I guess the issue is that the series are not correctly being set to visible false. However I tried adding 5 series which contains histogram as well data. So in all looped 10 times to set the visibility of the series. |I need to consider setting the visibility of the histogram and data object
 Could somebody tell me what the problem is ?
This is how it looks now

This is how it should be

This is how the series is bound to the histogram. If you see below each series would contain histogram object and data object.
@Input() set endingResults(value: Array<EndingSurplus>) {
    let objHistogram;
    let objectData;
    this.results = value;

    this.chartSeries1 = value.map((element, idx) => {

      objHistogram = {
        name: element.strategyName,
        color: element.strategyColor,
        type: 'histogram',
        xAxis: 1,
        yAxis: 1,
        baseSeries: 's' + idx,
        zIndex: -1,
        binWidth: Math.round((Math.max.apply(null, element.data) - Math.min.apply(null, element.data)) / 40)
      };
      objectData = {
        name: 'Data' + idx,
        showInLegend: false,
        data: element.data,
        id: 's' + idx,
      };

     this.chartSeries[2 * idx] = objHistogram;
     this.chartSeries[2 * idx + 1] = objectData;

     if (this.endingHistogramChart) this.endingHistogramChart.redraw();
    });

  }

kindly see the logic in the redraw method
 redraw() {
        if (!this.chart) return;

          let seriesLength = this.chart.series.length;
        for (let i = seriesLength - 1; i > -1; i--) {
            this.chart.series[i].remove();
        }

        this.series.map(s => {
            if (s !== null) {
                this.chart.addSeries(s,false);
            }
        });

        for (let i = 0; i < this.chart.series.length; i++) {
            if (i > 1) {
                this.chart.series[i].setVisible(false, false);
            } else {
                this.chart.series[i].setVisible(true, true);
                this.chart.series[i].showInLegend = true;
            }
        }

       this.chart.redraw();
    }

histogram component
import { Component, Input } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'histogramchart',
    template: '<chart [options]="options" (load)="getInstance($event.context)"></chart>',
    styles: [`
        chart{
              display: block;
              width: 100% !important;
              padding:0;
        }
    `]
})
export class HistogramChartComponent {

    public options: any;
    chart: any;
    @Input() public series: any;

    constructor(private _translate: TranslateService) {

        this.options = {
            credits: {
                enabled: false
            },
            title: {
                text: ''
            },
            chart: {
                type: 'histogram'
            },
            legend: {
                layout: 'horizontal',
                margin: 25,
                itemMarginTop: 0,
                symbolRadius: 0,
                symbolHeight: 20,
                symbolWidth: 20,
                useHTML: true,
                    title: {
                    text: this._translate.instant('CAPTIVES.RESULTS.COMMON.GRAPH_LEGEND_TITLE') + '  ',
                    margin: 50,
                    style: {
                        fontStyle: 'italic',
                        fontWeight: 'normal',
                        margin: 20
                    }
                },
                align: 'right',
                verticalAlign: 'bottom',
            },

            plotOptions: {
                series: {
                    events: {
                        legendItemClick: function() {
                            for (let i = 0; i < this.chart.series.length; i++) {
                                if (this.chart.series[i].index !== this.index) {
                                    this.chart.series[i].setVisible(false, false);
                                } else {
                                    this.chart.series[i].setVisible(true, false);
                                }
                            }
                            this.chart.redraw();
                            return false;
                        }
                    }

                }

            },

            xAxis: [{
                title: { text: '' },
                alignTicks: false
            }, {
                title: { text: this._translate.instant('CAPTIVES.RESULTS.ESA.GRAPH_XAXIS') },
                alignTicks: false,

            }],

            yAxis: [{
                title: { text: '' }
            }, {
                title: { text: this._translate.instant('CAPTIVES.RESULTS.ESA.GRAPH_YAXIS') },

            }],

            series: [{
                showInLegend: false
            }]

        };
    }

    getInstance(chartInstance): void {
        this.chart = chartInstance;
        this.redraw();
    }

    ngOnChanges(data: any) {
        if (!data.series.currentValue || !this.chart) return;

        data.series.currentValue.map(s => {
            this.chart.addSeries(s);
        });
        this.chart.reflow();
    }

    redraw() {
        if (!this.chart) return;

          let seriesLength = this.chart.series.length;
        for (let i = seriesLength - 1; i > -1; i--) {
            this.chart.series[i].remove();
        }

        this.series.map(s => {
            if (s !== null) {
                this.chart.addSeries(s,false);
            }
        });

        for (let i = 0; i < this.chart.series.length; i++) {
            if (i > 1) {
                this.chart.series[i].setVisible(false, false);
            } else {
                this.chart.series[i].setVisible(true, true);
                this.chart.series[i].showInLegend = true;
            }
        }

       this.chart.redraw();
    }
}


text:
Q: Paypal _cart not showing tax and shipping in sandbox I've got a paypal form to request a payment that I'm testing in www.sandbox.paypal.com.
It works as I expect, except for tax and shipping costs, that are ignored and not shown in paypal cart and not computed in cart total amount.
In this case I only have one product, but buyers can add more products to their carts.
I can't understand where I'm going wrong.
<form method="post" name="paypal_form" action="https://www.sandbox.paypal.com/cgi-bin/webscr">

   <input type='hidden' name='cmd' value='_cart'>
   <input type='hidden' name='business' value='myEmail'>
   <input type='hidden' name='charset' value='utf-8'>
   <input type='hidden' name='currency_code' value='EUR'>
   <input type='hidden' name='notify_url' value='http://mysite/shop/ipn_url.php'>
   <input type='hidden' name='custom' value='xxxaasxdfd'>
   <input type='hidden' name='return' value='http://mysite/shop/confirm_url.php'>
   <input type='hidden' name='lc' value='IT'>
   <input type='hidden' name='email' value='buyer@mysite'>
   <input type='hidden' name='first_name' value='Test name'>
   <input type='hidden' name='last_name' value='Test surname'>
   <input type='hidden' name='zip' value='00000'>
   <input type='hidden' name='no_note' value='1'>
   <input type='hidden' name='cbt' value='Return to mysite'>
   <input type='hidden' name='rm' value='2'>
   <input type='hidden' name='cancel_return' value='http://mysite/shop/cancel_url.php'>
   <input type='hidden' name='upload' value='1'><input type='hidden' name='amount_1' value='129.00'>
   <input type='hidden' name='item_name_1' value='23-PROD11'>
   <input type='hidden' name='item_number_1' value='120'>
   <input type='hidden' name='tax' value='39.37'>
   <input type='hidden' name='shipping' id='shipping' value='67.87'>

</form>

A: I found that the VAT and the shipping cost are visible and computed if I pass them for every single item in my cart.
<input type='hidden' name='shipping_1' id='shipping' value='67.87'>
<input type='hidden' name='tax_1' value='39.37'>

I've charged them on the first item as shipping_1 and tax_1 in the cart for all my items, in this way I'm sure that it will work for cart with one or more items.

redpajama_set_name: RedPajamaStackExchange


text:
Q: XML Import with "alternate" form or xml formatting I have successfully imported an XML file parsing elements info table attributes using this xml data formating:
<PN>
    <guid>aaaa</guid>
    <dataInput>0</dataInput>
    <deleted>false</deleted>
    <customField1></customField1>
    <customField2></customField2>
    <customField3></customField3>
    <description></description>
    <name>name1></name>
    <ccid>CC007814</ccid>
    <productIds>bbbb</productIds>
</PN>

but it errors whwen I input an XML in this format:
<PN guid="aaaa"
    deleted="false"
    customField1=""
    customField2=""
    customField3=""
    description=""
    modified="2010-10-20T00:00:00.001"
    created="2010-05-20T18:07:10.416"
    name="name1"
    ccid="CC006035"
    productIds="bbbb"/>

Is this later form usable? Any help would be appreciated. Thanks.

A: It's usable, but you're looking at the difference between using tags (your first example) and attributes (your second example).  Your processing is slightly different.


text:
Q: Can't add a field to a model in Symfony, bin/console crashes I'm working with Sylius framework. I'm following the guide to customize models.
I am trying to add a field notice to a model Taxon which is already overridden in my project. For that, I added the field description to Taxon.orm.yml of the model:
MyProject\Bundle\ShopBundle\Entity\Taxon:
    type: entity
    table: sylius_taxon

    # {Relationships code...}

    fields:
        # {Some existing fields...}

        notice:
            type: text
            nullable: true

I also added a field, a getter and a setter to the overriding Taxon class.
Then I'm trying to run bin/console doctrine:migrations:diff, but when I run bin/console even without any arguments, it crashes with the following exception:
[Doctrine\DBAL\Exception\InvalidFieldNameException]
  An exception occurred while executing 'SELECT s0_.code AS code_0, s0_.tree_left AS tree_left_1, s0_.tree_right AS tree_right_2, s0_.tree_level AS tree_level_3, s0_.position AS position_4, s0_.id AS id_5, s0_
  .created_at AS created_at_6, s0_.updated_at AS updated_at_7, s0_.enabled AS enabled_8, s0_.default_markup AS default_markup_9, s0_.notice AS notice_10, s0_.tree_root AS tree_root_11, s0_.parent_id AS parent_
  id_12 FROM sylius_taxon s0_ WHERE s0_.parent_id IS NULL ORDER BY s0_.tree_left ASC':
  SQLSTATE[42S22]: Column not found: 1054 Unknown column 's0_.notice' in 'field list'`

[Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[42S22]: Column not found: 1054 Unknown column 's0_.notice' in 'field list'`

[PDOException]
  SQLSTATE[42S22]: Column not found: 1054 Unknown column 's0_.notice' in 'field list'

If I remove the changes to Taxon.orm.yml then bin/console works again. What is missing in my changes?

A: One of my bundles' configruation contained that model's repository, that's it. I temporarily deleted the bundle's configuration from config.yml, and bin/console worked.

A: When you add new field you should doctrine:schema:update


text:
Q: Clustering PostgreSQL clusters This will be confusing for some due to poor terminology choices by the PostgreSQL folks, but please bear with me...
We have a need to be able to support multiple PostgreSQL (PG) clusters, and cluster them on multiple servers using, e.g. repmgr.  For example, to support both server availability and also PITR for each PG cluster.  A single PG cluster per server is too expensive in many cases, so we multi-tenant (small) customers on separate PG clusters, for data separation, recovery, etc., but also want to be able to support HA via replication/fail-over.
The closest analogy for a PG cluster is a SQL Server instance - each can host multiple DB's, has its own port, etc.  Like SQL Server, you can run multiple instances (PG clusters) on the same server, and set up replication for each.
Basic repmgr setup is no problem - that seems fairly clear in the single PG cluster model.  But, is there any recommended/supported approach to multiple PG clusters using repmgr?  I can kind of imagine faking repmgr into thinking each PG cluster is in effect a separate repmgr cluster (with separate repmgr.conf, connection info/port).  But, I'm not yet sure that will work.
I'd typically expect to fail-over all PG clusters on the same server - not one at a time.
I recognize this may not be the best idea in all cases, but am mostly exploring what's possible.  I have some alternatives, but this is closest to our current single-node model.
To clarify, I need to support many thousands of customers across many server clusters.  Ideally, each cluster uses the same repmgr DB (in the main PG cluster, e.g.), and essentially stands alone from the other server clusters.
Thanks...

A: Answering my own question, but I hope someone eventually posts a better answer, as I otherwise quite like repmgr.  In the end, it appears repmgr just isn't suitable for multiple PG clusters (instances), as there is an implied relationship between the repmgr cluster connection strings and the PG cluster (port).  Thus, you'd essentially have to create a separate repmgr environment (DB) for every clustered PG cluster/instance, losing a lot of the operational simplicity that repmgr brings to the table.
I will investigate a more generic solution using Corosync/Pacemaker/etc., as at least in that case, the virtual cluster IP handling is built-in to the solution, and doesn't require additional software/resources to pull off.
I'm sure I'm probably over-simplifying things, but it seems like repmgr was tantilizingly close to solving much of the problem, had it allowed the repmgr DB to be fully independent of the PG cluster and allow each repmgr cluster to specify its own connection info, not (only) the connection info for the repmgr DB itself.


text:
Q: Python Deciphering I am trying to decipher the standard "a = 1, b = 2, c = 3..." cipher in Python, but I'm a bit stuck. My message that I want decrypting is "he" -- " 8 5 ", but because of the ordering of my if statements, the output is "eh". Does anybody know how to solve this?
import re
import sys
message = " 8 5 ";
map(int, re.findall(r'\d+', message))
if "++" in message:
    sys.stdout.write(" ")
if "--" in message:
    print()
if " 1 " in message:
    sys.stdout.write("a")
if " 2 " in message:
    sys.stdout.write("b")
if " 3 " in message:
    sys.stdout.write("c")
if " 4 " in message:
    sys.stdout.write("d")
if " 5 " in message:
    sys.stdout.write("e")
if " 6 " in message:
    sys.stdout.write("f")
if " 7 " in message:
    sys.stdout.write("g")
if " 8 " in message:
    sys.stdout.write("h")
if " 9 " in message:
    sys.stdout.write("i")
if " 10 " in message:
    sys.stdout.write("j")
if " 11 " in message:
    sys.stdout.write("k")
if " 12 " in message:
    sys.stdout.write("l")
if " 13 " in message:
    sys.stdout.write("m")
if " 14 " in message:
    sys.stdout.write("n")
if " 15 " in message:
    sys.stdout.write("o")
if " 16 " in message:
    sys.stdout.write("p")
if " 17 " in message:
    sys.stdout.write("q")
if " 18 " in message:
    sys.stdout.write("r")
if " 19 " in message:
    sys.stdout.write("s")
if " 20 " in message:
    sys.stdout.write("t")
if " 21 " in message:
    sys.stdout.write("u")
if " 22 " in message:
    sys.stdout.write("v")
if " 23 " in message:
    sys.stdout.write("w")
if " 24 " in message:
    sys.stdout.write("x")
if " 25 " in message:
    sys.stdout.write("y")
if " 26 " in message:
    sys.stdout.write("z")

A: This becomes a lot easier if you use a mapping rather than a series of if statements:
>>> import string
>>> d = {str(x):y for x,y in enumerate(string.ascii_lowercase,1)}
>>> d['++'] = ' '
>>> d['--'] = '\n'
>>> message = ' 8 5 '
>>> ''.join(d[x] for x in message.split())
'he'

Here, I use all strings as keys to the dictionary since you want to support '++' and '--'.

A: Your solution does not work because you do not look at each number in the input string from its beginning, but for any occurence of it.
Suppose your input is 8 5 8, your output would still be eh.
Instead of using the in operator, you should have a loop among all numbers of the message:
for code in map(int, re.findall("\d+", message)):
    if code == 1:
        sys.stdout.write("a")
    -- ... and so on until 26

You should also use the tipsgiven by others, that consist in using a code dictionary to avoid all those ifstatements.

A: Since it looks like you are more interested in why your approach isn't working that getting a concise solution I'll try to avoid more complicated methods of approaching this problem (ASCII mappings/dictionaries and give you a few pointers on how you could approach this.
Firstly, you have a message that is a String. You want to look at each letter of this string and find the correct letter it encodes, so you will want to parse the string and look at it one letter at a time, from left to right.
You can use a for loop to grab a letter, and then do your comparison on that single letter. Do this one letter at a time and write the output at each stage.
Once you get this working you can look at optimising your code, but it is important to understand the basics first.

A: Instead of doing what you're doing now, you'll want to

*

*Split the message string into each component (8 and 5 (or 11 for that matter, etc))

*Iterate through each component in order...

*... And "decipher" its value into a letter.

(That map(int... line does nothing, by the way.)


text:
Q: Why don't you get electrocuted when you jump and touch an electric fence? I've read that you won't get electrocuted if you jump and touch an electric fence because you aren't closing the circuit with the ground. Which is also why birds don't get electrocuted when they're standing on power lines.
The way I understand voltage is that it's basically "a pressure of electrons" in the wire where electrons would like to escape from each other because they are the same charge, and they would love to reach the ground where there is plenty of space (i.e "low pressure"). When you touch an electric fence, the electrons see an opportunity to reach the ground (to "fill the space") through you and you get electrocuted because your body resists the current which makes heat.
Alright, but I don't understand why don't electrons want to fill up your body even  you're not touching the ground? Especially at high voltages; I mean there is plenty of space in your body. So when you jump and touch a fence, even though you're not touching the ground, why don't electrons see an opportunity and rush to fill up your body and cause you a shock?
To put it another way, let's say a bird lands on the ground and discharges all the excess electrons (becomes neutral with the ground). Now let's say the bird flies off and lands on a power line. Why don't electrons in the wire rush to fill up the bird and electrocute it?
Please help me understand.

A: Electrons do "fill up your body" when you jump up and hit a high voltage wire - there is a property called the capacitance of the body that determines how much the voltage increases when you add a certain amount of charge - mathematically, $C = \frac{Q}{V}$.
But it's not charge that kills you, it is current: charge flowing per unit time. Since it takes relatively few electrons to bring the body up to 30,000 V or so, there is not much charge flowing and nobody gets killed. But you may have noticed a static "shock" when (especially in winter) you walked across a carpet, then touched a metal door and got a shock. As you walked across the carpet you built up static charge (with an associated potential that could reach several 10's of kV); and all that charge "leaks away" when you touch a grounded (conducting) surface. But while you can "feel" the current it's not enough to kill you.
So how much charge is there on your body when you are charged to 30,000 V? It's a bit hard to estimate the capacitance of a human body, so we'll use the physicist's trick of the "spherical cow": we approximate the human body as a sphere with 1 m diameter. The capacitance of a sphere is given by
$$C_{sphere} = 4\pi\epsilon_0 R = 0.11 nF$$
At 30 kV, that gives a charge of 3.3 µA; if that charge comes out of your body in 1 µs*, it would result in a peak current of 3.3 A which is why it feels like quite a jolt; however, the total amount of energy is only $\frac12 C V^2 = 0.05 J$ - and that is not enough to kill you. It's enough to kill sensitive electronic circuits, which is why you have to be careful how you handle "bare" electronics, especially in winter (low humidity = build up of static electricity as conductivity of air is lower).
EDIT

*

*if the current flows in 1 $\mu$s, that suggests that the time constant of body capacitance and skin resistance should be on that order. Since time constant is RC, solving for R gives about 10 kOhm. That's a rather low resistance: skin resistance is higher, so peak current will be lower.


text:
Q: Eclipse or Javac bug; lambda type inference The following code compiles with javac, and with Eclipse 4.6.1/4.6, but produces an error in Eclipse 4.6.2:
package ecbug;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Foo
{
    class A
    {
        public int getStart() { return 0; }
    }

    void someMethod(List<A> toRemove)
    {
        Collections.sort(toRemove, Comparator.comparing(t -> -t.getStart()));
    }
}

Eclipse 4.6.2 complains, under -t.getStart(), that there is a Type mismatch: cannot convert from int to Comparable<? super Comparable<? super U>>.
I would think that the arguments to Comparator.comparing(...) should be a Comparable<T> with T = A, with functional method compareTo which returns int. Eclipse seems to believe that the lambda function should return Comparable<? super Comparable<? super U>>, however.
I strongly suspect an Eclipse bug, but there are certainly cases where Eclipse has correctly implemented the language specification and javac hasn't, so it seems worth asking: is this an Eclipse bug or a javac bug? Can any language-lawyers out there point out the relevant parts of the language spec?
Possibly related questions, which in my eyes are not duplicates:
Java 8 Stream flatMap and group by code compiler error - similar error message, but unclear if it is exactly the same issue; Answer claims that it is an Eclipse bug but provides no bug link nor JLS quotations; refers to old Eclipse version.
Why didn't this java 8 example using type inference compile in Eclipse? - similar to previous
Java Stream collect after flatMap returns List<Object> instead of List<String> - again, may be a different issue; comments claim Eclipse problem but do not justify via reference to JLS nor provide a link to an Eclipse bug report.

A: Your explanation doesn't hit it. The argument to Comparator.comparing(...) (single argument version) should not be a Comparable<T>, but rather a Function<? super T,? extends U>, whereas T := A, but U being U extends Comparable<? super U>.
So when you say

Eclipse seems to believe that the lambda function should return Comparable<? super Comparable<? super U>>

you are right regarding Eclipse's expectation and Eclipse is right in expecting that, too.
But your function returns an int value that is supposed to be compared and when you box that value to Integer, you have a type that fulfills the expected U extends Comparable<? super U> constraint, as Integer implements Comparable<Integer>. In other words, U should be inferred to be Integer, but apparently, this specific Eclipse version fails to do this due to the required boxing of int to Integer.

As a side note, when you want to compare an int property, you might want to use Comparator.comparingInt(...) anyway. With this factory, the returned comparator avoids boxing of int to Integer altogether.
Additionally, you should not reverse an integer ordering by negation. The problem is that
-Integer.MIN_VALUE == Integer.MIN_VALUE, as trying to negate the smallest possible int value causes an overflow evaluating to the smallest int value again, instead of the biggest one. Using negation for reversing the order may work in a lot of situations, in some of them it might be justified as this special value can be precluded, however, it creates a bad habit, that can backfire awfully in a scenario where the situation can occure, of course, only rarely and usually only at the customer…
The correct idiom would be
Collections.sort(toRemove, Comparator.comparingInt(A::getStart).reversed());

which works by swapping the two elements to compare, which is valid in all scenarios and has no performance drawbacks.


text:
Q: How to check condition in one to many relation model filed value in jpa I am using play framework(java) 1.2.4, jpa and hibernate.How can i check relation(oneToMany) model filed value on find error occurred
Contry model:
@Entity
public class Countries extends Model {

    @Required
    public String name;

    public String iso2;

    public String iso3;

    @OneToMany(mappedBy="country", fetch=FetchType.EAGER,  cascade=CascadeType.All)
    public List<States> states;

    public Countries() { }

}

State model:
@Entity
public class States extends Model {

   @Required
   public long country_id;

   @Required
   public String name;

   @Required
   public long product_id;

   @ManyToOne(fetch=FetchType.EAGER)
   @NotFound(action = NotFoundAction.IGNORE)
   @JoinColumn(name="country_id", nullable=false,insertable=false, updatable=false)
   public Countries country;

   public States() { }
}

In Contry controller:
   List<Countries> countries = Countries.find("states.product_id =5").fetch();

When i check states table value (oneToMany) following error occurred:
    IllegalArgumentException occured : org.hibernate.QueryException: illegal attempt to dereference collection

A: I think something like this will work, though it's untested.
List<Countries> countries = Countries.find(
    "select c from Countries c, States s where s.country = c and s.product_id = ?", 5
);

You might need quote around 5, I forget. You can also do it with a join clause, but I don't think that's necessary here.
Also, your model names should be singular, not plural. That should confuse you. It confuses me :-)

A: Method find supports also normal JPQL queries. Following is drop-in replacement for fetching unique list of countries that do have state with product_id 5:
SELECT DISTINCT(s.country) FROM States s WHERE s.product_id = 5


text:
Q: Unable to startup RESTEasy Maven project through Tomcat7 Maven plugin (ExecutionException) I am working on a Maven Java project that uses RESTEasy 3.0.6.Final as its REST provider framework. Because this application will be deployed to AWS Elastic Beanstalk through its Tomcat 7 container, I have set up the project to use the Tomcat Maven Plugin as its local web container. I have the following relevant dependencies and plugins in my pom.xml file:
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>${resteasy.version}</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-guice</artifactId>
    <version>${resteasy.version}</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <version>${resteasy.version}</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-servlet-initializer</artifactId>
    <version>${resteasy.version}</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>
...
<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.2</version>
    <configuration>
        <path>/</path>
    </configuration>
</plugin>

Then, when I build and run the project using mvn clean install tomcat7:run, I get the following errors in my console, which fails the build:
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
    at java.util.concurrent.FutureTask.get(FutureTask.java:111)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 7 more
Caused by: java.lang.ClassCastException: org.jboss.resteasy.plugins.servlet.ResteasyServletInitializer cannot be cast to javax.servlet.ServletContainerInitializer
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializer(ContextConfig.java:1670)
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializers(ContextConfig.java:1652)
    at org.apache.catalina.startup.ContextConfig.processServletContainerInitializers(ContextConfig.java:1562)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1270)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more

Feb 12, 2014 11:49:44 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
    at java.util.concurrent.FutureTask.get(FutureTask.java:111)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:341)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.startContainer(AbstractRunMojo.java:1238)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.execute(AbstractRunMojo.java:592)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:106)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:317)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:152)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:555)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:214)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:158)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more

Does anyone have any idea about what might be the problem? Note that I have tried this with both an empty web.xml file (besides setting a <listener-class> to a child of GuiceResteasyBootstrapServletContextListener in order to customize Guice in RESTEasy) and a web.xml file that uses servlet configuration for standalone servlet containers for Servlet version pre 3.0 (link). Thanks in advance.
NOTE: If I were to instead start-up my application with the Maven Jerry plugin, via mvn clean install org.mortbay.jetty:jetty-maven-plugin::run, then my project will indeed build successfully.

A: SOLVED!
One issue was that I should've been using mvn clean tomcat7:run-war instead of mvn clean tomcat7:run. As well, in contrast to what was said in the RESTEasy documentation, I needed to add a <servlet> tag for org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher in web.xml, despite the fact I was using a Servlet 3.0+ container.

A: Use
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>


text:
Q: Plotting thousands of observations on a single graph I am trying to plot Date on the X axis and Revenue on the Y axis. I have data for about 16000 customers, revenue aggregated on a weekly basis. The data set looks like the example dataset below (except that I have data for about 100 weeks and 16000 customers):
CustNum    Date    Revenue
1    2013-01-07    35
1    2013-01-14    23
1    2013-01-21    42
1    2013-01-28    65
2    2013-01-07    78
2    2013-01-14    48
2    2013-01-21    85
2    2013-01-28    34

I would like to plot this data on a single plot with one line on the plot representing one customer. In other words, the plot will have more than 16000 lines on it showing Revenue for each customer, each week.
Now, I understand that this plot will be really messy with 16000 lines on it, I would like to have suggestions on what could be a better way to plot this data so it is not as cluttered.
I tried the following code which didn't give me the desired result:
p <- ggplot() + geom_line(data=res,aes(x=Date,y=Revenue,color=custnum))

This didn't give me multiple lines for multiple customers.
So I basically have two questions:

*

*What could be a better way to represent this data?

*How can we improve my code to show 16000 lines on a single plot? (I don't care about this question a lot if I can get another way to represent this data)
Any help with this will be much appreciated.

A: Here is a base R outline of the approach in my comment above.  I use a large matrix to hold all the data. The first column is whether the customer got the treatment. The subsequent columns are the weekly revenue for 100 weeks.
First, I will simulate some data, this has a lot of temporal noise.
#First records are a stable pattern
notreat<- matrix(c(rep(0,8000), 100+rnorm(8000*100,0,5)),nrow=8000)
#second set of records get no treatment for 50 weeks
treat<- matrix(c(rep(1,8000), 100+rnorm(8000*50,0,5)),nrow=8000)
#then get the treatment for 50 weeks
treat<-cbind(treat,
             matrix(rnorm(50*8000,100+0.75*(0:50)),nrow=8000,ncol=50,byrow=TRUE))

m <- rbind(notreat, treat)

#use a color palette with transparency to be able to discern the overall pattern.
palette ( c(rgb(.4,0,0,0.01),rgb(0,0,0.4,0.01)))

#This will take several seconds to render 16000 lines
matplot(t(m[,2:101]),col=1+m[,1],type="l")

You can get your data frame into the type of matrix I build here using something like unstack() or the reshape package.

A: May be you are looking at something like this:
CustNum = c("1","1","1","1",
            "2","2","2","2")
Date = c("2013-01-07","2013-01-14","2013-01-21","2013-01-28",
         "2013-01-07","2013-01-14","2013-01-21","2013-01-28")
Revenue = c("35","23","42","65","78","48","85","34")

df = as.data.frame(cbind(CustNum,Date,Revenue))

df$CustNum = as.factor(df$CustNum)
df$Revenue = as.numeric(as.character(df$Revenue))

## create the factor variable
df$Treatment = ifelse(df$CustNum == '1','campaign','no campaign')

ggplot(df) + geom_point(aes(x=Date, y=Revenue, color=Treatment), size=5) + facet_wrap(~Treatment)

Results:
Now you can imagine doing the same with switching geom_point with geom_boxplot or geom_errorbar across all your data points. You could alternatively opt for not faceting and just plot in one graph, but you'd have to specify within the geom call the option 'dodge' to avoid having you boxplot stacked over one another.
Results2:


text:
Q: calculate the given sum (related to Newton's binomial formula) i was given the following question:
given n is a positve integer, calculate the given sum:
$$
{n \choose 1} -2{n \choose 2} +3{n \choose 3}+ \ldots +(-1)^{n-1}\cdot n {n \choose n}
$$
I looked at the expression and it reminds me of Newton's binom.. but i have no idea where to begin.. can someone help me understand how should i approach this?
thank you


text:
Q: How to display "content": in firefox? Everything works fine in Chrome but Microsoft Edge and Firefox display only a small block of the checkbox's border. I tried background-image property but it doesn't work with my code - the image appears before the checkbox. I tried placing "my-icon" with background-image property and "checkbox-body-checkmark" in the div class but the checkbox is then messed up and doesn't work at all.
CSS:
.checkbox-body-checkmark{
    border-radius: 15px;
    border: 4px solid var(--main-color);
    height: 70px;
    width: 100%;
    box-shadow: 1px 1px 5px #000000;
}
.select-body-container input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
}
.select-body-container:hover input ~ .checkbox-body-checkmark{
    background-color: #adadad;
    transition-duration: 0.6s;
}
.select-body-container input:checked ~ .checkbox-body-checkmark{
    background-color:#adadad;
    box-shadow: 1px 1px 1px #000000;
}
.body-type-font{
    position: absolute;
    top: 75%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.my-icon{
        content: url("Imgs/my-icon.svg");
}

HTML:

     <input type="checkbox">

          My icon

A: Use this appeareance only for Firefox Browser:
input[type="checkbox"]{
    appearance: initial; # only this also works others are just for browser support
    -webkit-appearance: initial;
    -moz-appearance: initial;
}


text:
Q: function DATE() type mismatch I can't make this work
Dim StrtD As Long, EndD As Long
Dim StartDate As Date, EndDate As Date
Dim myVar As Variant
Dim stringaAppoggio As String

With ThisWorkbook.Sheets("Settimana")
    StartDate = .TextBox1.Value
    EndDate = .TextBox2.Value
End With

StrtD = Month(StartDate)
EndD = StrtD + DateDiff("m", StartDate, EndDate)
yearData = year(StartDate)
arr4 = Application.Transpose(.Evaluate("TEXT(DATE(yearData,ROW(" & StrtD & ":" & EndD & "),1), ""[$-0410]mmmm yyyy"")"))

For Each myVar In arr4

stringaAppoggio = myVar

StartDate is "01/01/2020"
EndDate is "01/10/2020"
The error is stringaAppoggio = myVar

type mismatch

I think the error is yearData in Application.Transpose because if I put 2020 it works!
Thank you

A: yeardata variable is not evaluated passed correctly to your string formula. You need to concatenate it directly into your formula string like what you did in StrtD and EndD variables. Try:
arr4 = Application.Transpose(.Evaluate("TEXT(DATE(" & yearData & _
       ",ROW(" & StrtD & ":" & EndD & "),1), ""[$-0410]mmmm yyyy"")"))

A: There are some things going wrong for you here:

*

*Your code should not even compile in the first place, because (with the information you have shown) Application.Transpose(.Evaluate holds a unqualified .Evaluate method.

*As I told you yesterday, Debug.Print is a great way of checking if what you intended to write, actually gets written in the .Evaluate. Currently you are using yeardata wrong within the formula. It's a variable holding a string value! Don't get confused with thinking that writing this word within another string automatically picks up you meant to use the variable.

*To TRANSPOSE values from a worksheet into a 1D-array, you can do so directly through your formula.

*I just assume your code sample above isn't complete and includes a Next below stringaAppoggio = myVar
Considering the above, I think your code can be rewritten to something like:
arr4 = Evaluate("TRANSPOSE(TEXT(DATE(" & yearData & ",ROW(" & StrtD & ":" & EndD & "),1), ""[$-0410]mmmm yyyy""))")


text:
Q: Can you decide an ngIf for a singular parameter on a component? Ive been told this may not work out-of-the-box with Angular but I wanted to check if anyone else had an idea. I am attempting the following:
My preferred solution is:
<ds-checkbox *ngIf="maxSelectAll != undefined; then showTooltip else '//STAYHERE'"
     id="data-table-select-all-checkbox"
     [checked]="allClicked"
     (checkedChange)="_handleAllClick()"
     [disabled]="selectCheckBoxesDisabled"
 ></ds-checkbox>

 <ng-template #showTooltip
     [dsTooltip]="'Only the first ' + maxSelectAll + ' ' + nameForTotal + ' will be selected'"
 ></ng-template>

The working solution is:
<ds-checkbox *ngIf="maxSelectAll == undefined; else showTooltip"
     id="data-table-select-all-checkbox"
     [checked]="allClicked"
     (checkedChange)="_handleAllClick()"
     [disabled]="selectCheckBoxesDisabled"
 ></ds-checkbox>
 <ng-template #showTooltip
     id="data-table-select-all-checkbox"
     [dsTooltip]="'Only the first ' + maxSelectAll + ' ' + nameForTotal + ' will be selected'"
     [checked]="allClicked"
     (checkedChange)="_handleAllClick()"
     [disabled]="selectCheckBoxesDisabled"
 ></ng-template>

I would rather not duplicate code if possible, but I am not seeing another option in angular. Is there a way to add only a single parameter to the checkbox without needing to redo all of the parameters that will exist anyways? As of now, my first example will see maxSelectAll as undefined and skip all of the parameters below it (my 'STAYHERE' note for id, checked, checkedChange, disabled).
If this cannot be done, no worries. Thank you for your time!
EDIT: Another attempt?
<ds-checkbox *ngIf="maxSelectAll == undefined; then standards;
              else standards; then showTooltip">
</ds-checkbox>

 <ng-template #standards
     id="data-table-select-all-checkbox"
     [checked]="allClicked"
     (checkedChange)="_handleAllClick()"
     [disabled]="selectCheckBoxesDisabled"
 ></ng-template>

 <ng-template #showTooltip
     [dsTooltip]="'Only the first ' + maxSelectAll + ' ' + nameForTotal + ' will be selected'"
 ></ng-template>

TLDR:
I would like:
<ds-checkbox
     id="data-table-select-all-checkbox"
     [dsTooltip]="'Only the first ' + maxSelectAll + ' ' + nameForTotal + ' will be selected'"
     [checked]="allClicked"
     (checkedChange)="_handleAllClick()"
     [disabled]="selectCheckBoxesDisabled"
 ></ds-checkbox>

Where[dsTooltip] can be added conditionally to the checkbox.


text:
Q: How can I fix "Type org.freedesktop.gstreamer.GStreamer is defined multiple times" error when building an Android APK? I have been working on a project for a couple of months integrating gstreamer to a basic react-native Android app. The starting point was react-native-gstreamer but with a number of modifications to the gstreamer pipeline etc.
My debug builds (created with yarn android or ./gradlew assembleDebug) have been working reliably, on emulated and real devices, but I can't get a release build / signed APK ./gradlew assembleRelease to work. The build scan showing the error (created with ./gradlew assembleRelease --scan, doesn't appear to contain any sensitive information?) is at scans.gradle.com. The error I am stuck on is

C:\Temp\MyApp\app\intermediates\project_dex_archive\release\out\org\freedesktop\gstreamer\GStreamer.dex: D8: Type org.freedesktop.gstreamer.GStreamer is defined multiple times: C:\Temp\MyApp\app\intermediates\project_dex_archive\release\out\org\freedesktop\gstreamer\GStreamer.dex, C:\Temp\MyApp\react-native-gstreamer.transforms\b22258b54d8d354026f3fb18b0251db4\transformed\classes\classes.dex
com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
Learn how to resolve the issue at https://developer.android.com/studio/build/dependencies#duplicate_classes.

I'm new to Android development (experienced C++/Python mainly), so I could be missing something obvious, this seems to be a common issue (see below) but the link in the error doesn't help me and the solutions I have found have not worked.
The most likely cause that I can't pin down is some sort of dependency clash, similar to this issue also, but I don't have lots of dependencies, it seems specifically related to gstreamer, and I don't know where to dig further to find the clash.
./gradlew app:dependencies doesn't show any obviously bad dependencies. react-native-gstreamer has a dependency on com.facebook.react:react-native:+ -> 0.63.4 (*) and doesn't appear in any other context in the dependencies (i.e. the above dependency appears a few times in the output, but react-native-gstreamer isn't a dependency of other packages and doesn't have other dependencies and there are no other occurrences of gstreamer)
Similar errors elsewhere on stackoverflow and solutions which I have unsuccessfully tested:

*

*Delete gradle folder - fault still occurs

*Enable multiDex in build.gradle - fault still occurs (note minSdkVersion is set to 21, so some messages suggest this should not be necessary, but tried anyway)

*Similar to this but I am not aware of any dependency

*./gradlew clean and ./gradlew assembleRelease - fault still occurs

*Various solutions

*

*look at the path given in AS, it should point to \app\build\intermediates\project_dex_archive\debug\out. Go to this path, delete all the *.jar files, leaving the most recent one - fault still occurs (removed file is recreated on next build)

*Delete the build directory (C:/Temp/MyApp above) - fault still occurs

*Multidex changes - it looks like this is now outdated for minSdkVersion >= 21, no upvotes and one comment that it didn't fix the original poster's problem, not tested.

A: The error message mentions two dex sources which contain the org.freedesktop.gstreamer.GStreamer class:

*

*C:\Temp\MyApp\app\intermediates\project_dex_archive\release\out\org\freedesktop\gstreamer\GStreamer.dex

*C:\Temp\MyApp\react-native-gstreamer.transforms\b22258b54d8d354026f3fb18b0251db4\transformed\classes\classes.dex

First source's project_dex_archive folder generally contains output artifacts which were built from project source files. Is it possible that your app module contains GStreamer.java source file?
If yes - then it might be the root cause of the conflict, since you're most likely have similar artifact packaged in a third party dependency (the second dex source: react-native-gstreamer).


text:
Q: Why is Pygame Application Freezing Upon Launch? I'm working on creating a Snake Game from a Udemy course and am having trouble getting the Python Game application to launch.
Every time I run my module, the application will load and then just freeze with the Mac spinning pinwheel in the application window.
I'm still in the process of building it, but my code matches the courses and I still cannot launch the game.  Here is my code:
`import pygame
import sys
import random
import time`

`check_errors = pygame.init()
if check_errors[1] > 0:
    print("(!) Had {0} initializing errors,
exiting...".format(check_errors[1]))
    sys.exit(-1)
else:
    print("(+) PyGame successfully initialized!")`

`# Play surface
playSurface = pygame.display.set_mode((720, 460))
pygame.display.set_caption('Snake game!')`

`# Colors
red = pygame.Color(255, 0, 0) # gameover
green = pygame.Color(0, 255, 0) # snake
blue = pygame.Color(0, 0, 255)
black = pygame.Color(0, 0, 0) #score
white = pygame.Color(255, 255, 255) #background
brown = pygame.Color(165, 42, 42) #food`

`# FPS controller
fpsController = pygame.time.Clock()`

`# Important Variables
snakePos = [100, 50]
snakeBody = [[100, 50], [90, 50], [80, 50]]`

`foodPos = [random.randrange(1,72)*10,random.randrange(1,46)*10]
foodSpawn = True`

`direction = 'RIGHT'
changeto = direction`

`# Game over function
def game0ver():
    myFont = pygame.font.SysFont('monaco', 72)
    GOsurf = myFont.render('Game over!', True, red)
    GOrect = GOsurf.get_rect()
    GOrect.midtop = (360, 15)
    playSurface.blit(GOsurf,GOrect)
    pygame.display.flip()`

`gameOver()
time.sleep(10)`

A: You need to handle events so your operating system doesn't think your application has crashed. Even if your application is still a work in progress you'll something like the following:
done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

Any pygame application needs a game loop that:

*

*Handles events

*Updates game state

*Updates the display


text:
Q: Requisição Ajax em C# atualizar autenticação como eu faço para cada solicitação Ajax, dar update no cookie do forms authentication.
Quero dar update no no forms authentication no meu controller, pois ele é uma tela de agenda que usa o FullCalendar.
Estou tento problemas em uma página, que somente faz solicitações ajax e depois de um tempo se o usuário for para outra tela, pede login e senha.

A: Dois anos atrás eu fazia requisições AJAX sem utilizar ferramentas ou API's de apoio.
O recurso alvo das requisições feitas via AJAX eram "Generic Handlers" (com extensão ASHX).
Depois de muito tempo só fazendo esse tipo de requisição, a Session dava timeout, e meu usuário acabava deslogado.
Eu corrigi, simplesmente acrescentando System.Web.SessionState.IRequiresSessionState à herança da classe.
Declaração da classe antes (dava timeout e deslogava):
public class DisponibilidadeHandler : IHttpHandler

Declaração da classe depois (passou a funcionar OK, sem timeout e sem deslogar):
public class DisponibilidadeHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState


text:
Q: Exporting max values of different csv files in to one I got 3 datasets which contain the flow in m3/s per location. Dataset 1 is a 5 year ARI flood, Dataset 2 is a 20 year ARI flood and Dataset 3 is a 50 year ARI flood.
Per location I found the maximum discharge (5,20 & 50)
Code:
for key in Data_5_ARI_RunID_Flow_New.keys():

    m = key
    y5F_RunID = Data_5_ARI_RunID_Flow_New.loc[:,m]
    y20F_RunID = Data_20_ARI_RunID_Flow_New.loc[:,m]
    y50F_RunID = Data_50_ARI_RunID_Flow_New.loc[:,m]
    max_y5F = max(y5F_RunID)
    max_y20F = max(y20F_RunID)
    max_y50F = max(y50F_RunID)
    Max_DataID = m, max_y5F, max_y20F, max_y50F
    print (Max_DataID)

The output is like this:
('G60_18', 44.0514, 47.625, 56.1275)
('Area5_11', 1028.4065, 1191.5946, 1475.9685)
('Area5_12', 1017.8286, 1139.2628, 1424.4304)
('Area5_13', 994.5626, 1220.0084, 1501.1483)
('Area5_14', 995.9636, 1191.8066, 1517.4541)

Now I want to export this result to a csv file, but I don't know how. I used this line of code, but it didn't work:
Max_DataID.to_csv(r'C:\Users\Max_DataID.csv', sep=',', index = False)

A: Use this file name myexample.csv with specific path where you want to create the file.
Please check that Max_DataID is a iterable value. And as your reference the values are in form of tuple so I use list() to convert tuples into list and that will be supported values for writerow in csv.
import csv
file = open('myexample.csv', 'wb')
filewriter = csv.writer(file,delimiter =',')
for data in Max_DataID:
    filewriter.writerow(list(data))

A: You can do the following.
df.to_csv(file_name, sep='\t')

Also, if you want to split it into chunks, like 10,000 rows, or whatever, you can do this.
import pandas as pd
for i,chunk in enumerate(pd.read_csv('C:/your_path_here/main.csv', chunksize=10000)):
chunk.to_csv('chunk{}.csv'.format(i))


text:
Q: Как открыть окно customtkinter в полноэкранном режиме import tkinter
import customtkinter

customtkinter.set_appearance_mode("Light")
customtkinter.set_default_color_theme("blue")

app = customtkinter.CTk()
app.geometry("400x500")
app.title("Win locker")
# app.attributes("-fullscreen", True)

frame_1 = customtkinter.CTkFrame(master=app)
frame_1.pack(pady=20, padx=60, fill="both", expand=True)

label_1 = customtkinter.CTkLabel(master=frame_1, justify=tkinter.LEFT, text="hello")
label_1.pack(pady=10, padx=10)

app.mainloop()

метод app.attributes("-fullscreen", True) не работает


text:
Q: Why is it typically a switching regulator to 5 V with a further linear to 3.3V instead of both in parallel? I'm looking at some device's schematics of various purpose, and noticed one thing: if there is a need to go down from 12-24 V to 5V and 3.3V it is usually implemented as 24V -> 5V switching converter (alike LM2596) and then linear from 5V to 3.3V (alike AMS1117-3.3.)
Why is it like that? Wouldn't it be better to have 2 separate switching converters from 24V -> 5V and 24V -> 3.3V?
What are the reasons?

A: Switching regulators are noisier but have high efficiency. Linear regulators give cleaner voltage out but terrible efficiency and also generate lots of heat when the Vin/Vout gap is relatively large.
Therefore it is a common design to use a switching regulator for the big leap from 24V down to 5V, then use a linear regulator to obtain a cleaner 3.3V from 5V, in order to power RF parts of similar noise-sensitive circuits.


text:
Q: How to remove Homebridge on Raspberry Pi How can I remove Homebridge from a Raspberry Pi 3.  I have attempted the following without any luck.
pi@Development:~ $ sudo npm uninstall homebridge
npm WARN enoent ENOENT: no such file or directory, open '/home/pi/package.json'
npm WARN pi No description
npm WARN pi No repository field.
npm WARN pi No README data
npm WARN pi No license field.

I have also attempted to remove it not as sudo.  A much longer result but still no luck.
pi@Development:~ $ npm uninstall homebridge
npm WARN enoent ENOENT: no such file or directory, open '/home/pi/package.json'
npm WARN pi No description
npm WARN pi No repository field.
npm WARN pi No README data
npm WARN pi No license field.
npm ERR! Linux 4.4.21-v7+
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "uninstall" "homebridge"
npm ERR! node v7.3.0
npm ERR! npm v4.0.5
npm ERR! path /home/pi/node_modules/.staging
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall mkdir
npm ERR! Error: EACCES: permission denied, mkdir '/home/pi/node_modules/.staging'
npm ERR! { Error: EACCES: permission denied, mkdir '/home/pi/node_modules/.staging'
npm ERR! errno: -13,
npm ERR! code: 'EACCES',
npm ERR! syscall: 'mkdir',
npm ERR! path: '/home/pi/node_modules/.staging' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator
npm ERR! Please include the following file with any support request:
npm ERR! /home/pi/npm-debug.log

A: Try one of these, they seemed to work for me when nothing else did. (Or at least I didn't get error messages, and when I tried to get back into Homebridge, I DID get an error so I think it worked.)
To remove the Homebridge service run this:
sudo hb-service uninstall

To remove Homebridge and Homebridge Config UI X run this:
sudo npm uninstall -g homebridge homebridge-config-ui-x

A: You can do it globally as root:
sudo npm uninstall -g homebridge

Homebridge's configuration files are stored in ~/.homebridge (if you're using default user "pi", the directory is /home/pi/.homebridge)

A: None of these work for me, after uninstalling homebridge, homebridge is still in /usr/local/bin/ along with hb-config. I need to completely remove it so I can try reinstalling it since it's completely b0rked.
     pi@pi4 % sudo npm uninstall -g homebridge homebridge-config-ui
up to date, audited 1 package in 878ms

found 0 vulnerabilities
 pi@pi4 % ls -ls /usr/local/bin/homebridge
0 lrwxrwxrwx 1 root root 45 Oct  2  2019 /usr/local/bin/homebridge -> ../lib/node_modules/homebridge/bin/homebridge
 pi@pi4 %


text:
Q: CM.make cannot find file "smlnj-lib.cm" When I try to use smlnj-lib.cm in a .cm file, I get this error:
I installed SML/NJ using Homebrew on MAC OS X 10.14.2. /usr/local/smlnj/bin is in .bash_profile, .bash_profile is updated.
sources.cm file:
Group is
driver.sml
errormsg.sml
tokens.sig
tokens.sml
tiger.lex
smlnj-lib.cm

I try to run it:
CM.make "sources.cm";

And get this error:
sources.cm:8.1-8.13 Error: Io: openIn failed on "smlnj-lib.cm", No such file or directory

A: If i recall, you are using the old compilation manager format, in the new compilation manager
cm files which should be looked up relative to the standard ML installation directories should be prefixed by $/dir where smlnj-lib.cm exists in the root.
directories without such a prefix will be looked up relative to the current directory.
such as
Group is
driver.sml
...
$/smlnj-lib.cm


text:
Q: Реализация "Жизни" Конвея на JavaScript и DOM(Ошибка) Добрый день, уважаемые господа! Написал тут реализацию "Жизни" Конвея кривую под стать своему навыку, выглядит все работающим, но на деле при нажатии на кнопку браузер повисает и больше не оживает. Сколько не смотрел, не нашел почему так происходит. Заранее Вам благодарен за подсказку и совет! Дай Бог Вам здоровья)

<button id="next">Следующее поколение</button>

A: Если вам еще нужен ответ:
Проблема заключается в функции countNeighboors,а конкретно в циклах for.
Например в первом из них вы используете такое условие:(y <= y + 2), но оно по определению всегда true и программа никак не может выйти из цикла.
То есть вам надо заменить названия счетчиков, чтобы они не совпадали с другими именами и не модифицировались нечаянно.


text:
Q: Understanding an eigenspace visually. I'm trying to make sense of an example in my textbook but I am confused as to what they are presenting to me. I can do the computations but I would like to have a greater understanding of what is actually going on.
My assumption is that the blue vectors are my eigenvectors but when I cross these two vectors it does not produce the same results. The vectors, when multiplied by A lie off of the plane. My next assumption is that the plane is the $Span(\begin{bmatrix}\frac{1}{2}\\1\\0\end{bmatrix},\begin{bmatrix}-3\\0\\1\end{bmatrix})$. This does not appear to work either.
Would anyone have any insight as to what is going on in this example?

A: A linear operator is a transformation of the underlying space. A square matrix is a linear operator. Geometrically, it is a rotation, reflection, or inhomogeneous stretching of the space, or combinations thereof. Eigenvalues are conserved directions - e.g. The axis of a rotation or the principal directions of a stretch. If one subtracts a smoothly increasing linear multiple of the identity operator - which is an isotropic stretch of unit magnitude and can be viewed as a unit sphere - from zero, one may imagine the origin "gobbling up" eigenvectors isotropic ally,  almost like a linear black hole! Each eigenvector head is coincident with the origin for precisely one value of the parameter, and this value is the corresponding eigenvalue.  If two eigenvectors have the same length (they cannot be collinear), then they therefore correspond to the same eigenvalue. Hence, any linear combination of them is still an eigenvector - so in this special case there is a whole plane of eigenvectors, in contrast to the "more usual" case of distinct eigenvectors corresponding to distinct eigenvalues. This is termed degeneracy and is manifested, for example, in circular polarisation of light or vibration of surfaces of revolution. It often corresponds to a rotational symmetry or complex structure.  The correspondence between the geometric description and the algebraic one generalises to higher dimensions, mutatis mutandis.Hope that helps :)

A: The plane shown in figure 3 is the eigenspace corresponding the $A$'s eigenvalue $\lambda = 2$. And, as shown in the calculation, $\Bigg\{\begin{bmatrix} 1 \\ 2 \\ 0 \end{bmatrix}, \begin{bmatrix} -3 \\ 0 \\ 1 \end{bmatrix}\Bigg\} = \{\mathbf{v_1}, \mathbf{v_2}\}$ is the basis for that space. Any linear combinations of $\mathbf{v_1}$ and $\mathbf{v_2}$ is an eigenvector in that eigenspace. And, the matrix $A$ acts as a dilation to any vectors in that space, i.e. $A\mathbf{x} = 2 \mathbf{x}$ for any $\mathbf{x}$ in that eigenspace. For example,
$$A \mathbf{v_1} = \begin{bmatrix} 2 \\ 4 \\ 0 \end{bmatrix} = 2 \mathbf{v_1}$$
$$A (2 \mathbf{v_1} + 3 \mathbf{v_2}) = \begin{bmatrix} -14 \\ 8 \\ 6 \end{bmatrix} = 2 (2 \mathbf{v_1} + 3 \mathbf{v_2})$$
Hope this helps in giving you a visual image of what's going on.


text:
Q: mySQL select í returns results with i I have a table set up where fields are TEXT utf8_general_ci.
The field data is set to Jovíkhan (where the í is actually ALT-161).
I do a search for Jovikhan (regular i, NOT ALT-161), I'm returned all the results as if I had actually used the ALT-161 í.
SELECT * FROM Table WHERE Field = 'Jovikhan';

Driving me a little bonkers here...  I'm getting this issue directly in phpMyAdmin currently...  why would it return those fields, especially if I'm using = 'Jovikhan' vs. LIKE '%Jov%'?

A: The _ci in utf_general_ci means case-insensitive. This causes MySQL to treat i and í as identical. You need to add COLLATE utf8_bin to your query:
SELECT * FROM Table WHERE Field = 'Jovikhan' COLLATE utf8_bin;

For more discussion, see this post.


text:
Q: PHP performance question Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.
//OPTION ONE
if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.

A: Neither. The best option is to check for isLoggedIn once, save the result, and do ifs inside the source to swap in each place.

A: The second option is negligibly more performance heavy, but is your better option as it produces less code duplication.
Also, if you cache the result of isLoggedIn() in a static var, you do not have to perform all your checks with every call of the method. You can check your static var and jump out early.
function isLoggedIn() {
    static $is_logged_in = null;

    if(!is_null($is_logged_in)) {
        return $is_logged_in;
    }

    //... user is known not to have valid credentials

    $is_logged_in = false;

    // ... User has been validated

    $is_logged_in = true;

    //...

}

A: Both.
You don't want to check isLoggedIn() everytime (especially if it's going to hit the database) because that will be slow. But you don't want to have 2 versions of HTML either because it's unmaintainable.
Check it once at the top and set a variable (or use a session variable and check that). Then in the HTML use if statements against the variable to determine what to show. For example:
PHP:
$logged_in = false;
if(isLoggedIn() ) {
     $logged_in = true;
}

HTML:
<?php if($logged_in) { ?>

     Super-secret needs a login stuff

<?php } else { ?>

     Sorry! You have to login to see this cool stuff

<?php } ?>

A: I would say, if you can, keep a cached version for the people who are not logged in, and generate everything when they're logged in.

A: For separation of concerns, it might be viable to let the client browser add functions for logged in users. Meaning you send out one static version of the website, and Javascript checks client-side for the presence of a login cookie. If it's present the few additional GUI elements or permissable links are displayed.
The obvious pitfall being that JS disabled browsers would not see anything. Unless you decorate elements with CSS .optional-func and disable/enable that:
if (!document.cookies.match(/login/)) { $(".user-funcs").hide(); }


text:
Q: $g(x)=c$ solves the ODE $y'=f(y)$ iff $c$ is a critical point of the ODE
Consider the autonomous ODE $y'=f(y)$ where $f$ is continuously
differentiable. $g(x)=c$ (where $c$ is a constant) solves this ODE if
and only if $c$ is a critical point of the ODE. Remember to prove in
both directions.

My attempt at the solution:
First, I need to show that if $g(x)=c$ is a solution of the ODE then $c$ is a critical point of the ODE.
So if $g(x)=c$ is a solution of $y'=f(y)$ then we have
$y'=f(y)=f(c)$ by definition for all $x$.
Since $f(c)$ is a constant, then $y=c$ is also a solution of the ODE.
If we do $\frac{d}{dy} f(y) = f'(y)$ at the point $y=c$, then we have $f'(c)=0$ because the derivative of a constant function is always zero. Thus $c$ is a critical point of the ODE.
Second, I need to show the converse is true. Namely, if $c$ is a critical point of the ODE, then $g(x)=c$ is a solution of the ODE.
So if $c$ is a critical point, that means $f(c)=0$. To show that $g(x)=c$ is a solution of the ODE, we need to show that $y'=f(y)=f(c)$ for all $x$.
Since $f(c)=0$ then $f(y)$ is constant at $y=c$ so when $y=c$, $y'=f(y)=f(c)$ for all $x$.
Is this a correct proof?

A: In proving the first direction ($\implies$), the crucial starting point is not that $y'=f(y)=f(c)$ for all $x$, but that $y'=g'(x)$ and $f(y)=f(c)$ imply that $g'(x)=f(c)$ for all $x$. Since $g(x)=c$ is a constant, we have that $g'(x)=0$ for all $x$ and therefore $f(c)=0$ and $c$ is a critical point.
For the second direction ($\impliedby$), $c$ being a critical point means that $y'=f(c)=0$ by definition. $y'=g'(x)=0$ for all $x$, so $g(x)=c$ is a solution to the ODE.


text:
Q: Is Visual Studio 2017 RC backwards compatible with Visual Studio 2013 solutions? We have several VS2013 solutions all targeting .NET 3.5, with several WinForms projects, an ASP.NET Web Application, and a Windows Service.  Mostly VB.NET with some C#.
These projects all worked fine in VS2013 and VS2015 - we could open, work on, save, compile and run them, in both versions of VS.
We didn't move to VS2015 in the end because it was so buggy - VB.NET Edit & Continue was hopelessly broken, and Intellisense didn't work so well either.
So now we're contemplating skipping 2015 and moving straight from 2013 to 2017, but again we're nervous, wanting to run them in parallel for a while until we feel 2017 is ok.  It's a two person team, and one would be sticking with VS2013 while the other one develops with VS2017.
So: can you use both VS2013 and VS2017 to work on the same codebase in the same way that you could with VS2013 and VS2015?
We aren't yet using features that come with later versions but we do want to move to the newer IDE as a precursor to moving to more recent framework versions and language features.

A: The compatibility between different versions of VS should remain the same - that is, VS2017 and VS2013 should work together as well as VS2015 does with VS2013.  The usual caveats apply: any globally installed packages/frameworks from VS2017 might have unintended impact on VS2013 (for example, if VS2017 installs a newer version of the .NET Framework that has an unintentional behavior change).
In general, VS2017 ought to be very compatible with other versions of VS.  Most of the install payload is now local to that VS installation with lessened impact to the system (no GAC'ed components, no registry keys, etc), so the impact to your box should be less than VS2015.
Obviously, if you add functionality to your solution that's from VS2017 and isn't back-compatible to VS2013, an upgrade will be forced.  But that's also no different than VS2015 was.


text:
Q: How do I display a standard windows error icon for a custom exception handler? As the title suggests, I just want to display a standard windows error icon for a custom exception handler. What the easiest way to achieve this using WPF?
For example, the red cross in this dialog:
alt text http://blogs.sun.com/coreqa/resource/other/report-exception.jpg

A: Have a look in System.Drawing.SystemIcons. All the standard dialog icons are there for your use.


text:
Q: iOS 9 Location Update Background task after 3 minutes I've been digging into this code which is using a basic timer to check for location updates. I then have it sending lat/lng to a server.
http://mobileoop.com/background-location-update-programming-for-ios-7
https://github.com/voyage11/Location
It's working well when plugged in and hooked up through XCode, however when I unplug and take the device mobile, the OS seems to always kill the background thread exactly after 3 minutes. So if I set the timer to run every 30 seconds, I'll get ~6 updates until I bring the app up to the foreground.
I have read that max background execution time is 3 minutes, but as I see it this code is resetting the background task after 1 minute, so I'm not sure why I'm seeing this.
There must be some way around this. Anything I can do here?
EDIT: this helped me: allowsBackgroundLocationUpdates in CLLocationManager in iOS9

A: se:
if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
}

This is needed for background location tracking.

A: In case anyone else runs into this issue, the code at the github repo listed above - https://github.com/voyage11/Location - has recently been updated with a fix for iOS 9, that will allow the GPS to continuously poll in the background without the thread getting terminated after 3 minutes.

A: In case anyone runs into unreliablity problems when running this otherwise excellent library, integrated into other xcode modules in a more sophisticated app, they might look at the initialisation statement for the background task list Id array and consider changing _bgTaskIdList = [NSMutableArray array]; to _bgTaskIdList = [[NSMutableArray alloc]init]; in BackgroundTaskManager.m  Until I did this I got unreliable behavious. Sometimes it worked and sometimes I got a stack dump. I found that this was because bgTaskList had been overwritten with other data causing bad access errors.


text: Q: Get overall grade from Google Classroom using Google Script Using the Classroom API, one can get most of the information for students in a class.  I can't seem to find a way to get a current overall grade for students to then automatically populate a spreadsheet.  I know this can be done manually by exporting grades to a sheet or csv.  I also know that Classroom API allows for getting grades on specific submissions.  Is it possible to get overall grades with the Classroom API?


text:
Q: Java application runs much slower when packaged as a MacOs app I've written a Java application that I want to package for the main OSes so that I can provide it as a self-contained installable image. To do this, I use jpackage, with help from the best-named plugin I've come across, The Badass  Runtime Plugin (https://badass-runtime-plugin.beryx.org)
My problem is that although the packaging works the performance of the packaged application is dreadful when compared to the compiled Java.
When I build my application (I use gradle for this) on MacOS, the build output includes an install directory containing the compiled classes and a launch script, and an installer directory containing a dmg with the app file.
Running the application from the compiled classes via the launch script works great. Running the application from the app (after installing from the dmg) is very much slower - frequently 10x and worse.
The launch script for the compiled classes points at my local JDK instance (openjdk 16), whereas the app file contains the jdk modules needed for the app to run. This is by design of course, but the only difference I can think of between the two.
Thanks for reading this far - I realise this is a fairly niche problem. If anyone has any experience or thoughts that might help I'd love to hear it.
Thanks,
Andy
Edit 10th Sept - thanks for all the interest and comments so far. A couple more notes about my app that might be relevant:
It's a heavy user of RocksDB for off-heap, file-backed data storage. Both the compiled Java and the packaged app use the same
sst files, so the data is identical. The app and data are running/present on the same machine, a MacBook Pro with SSD drive and plenty of capacity.
It launches Javalin instances to fire up https connections for a browser based UI and accepting data requests.

A: I did have the same issue somehow the binary made by jpackage is waaay too slow, did not find any solutions in tweaking the creation of the binary, so I ended up replacing it with a sh that starts the jar and this made the app work normal.
So after creating the app-image in the /Contents/app replaced the binary with
#!/bin/bash
$DIR/../runtime/Contents/Home/bin/java -Xdock:icon=$DIR/../Resources/icon.icns -Djava.library.path=$DIR:$DIR/../MacOS -Djava.launcher.path=$DIR/../MacOS -Dapp.preferences.id=org/springframework/boot/loader -Dstorage.diskCache.bufferSize=200 -Xmx4g -cp $DIR/../app/server.jar org.springframework.boot.loader.JarLauncher


text:
Q: How Do I Go About Transposing/Cutting Columns into Rows in R I am working with a large dataset on country level data that is in country-year format and appears in the following form (abridged for ease):
Country     Variable of Interest  Year
Bolivia     5                     1990
Bolivia     6                     1991
Bolivia     7                     1992
Cambodia    8                     1990
Cambodia    9                     1991
Cambodia    10                    1992
Russia      11                    1990
Russia      12                    1991
Russia      13                    1992

Due to a collaboration with a colleague, how do I get the data into this form?:
Country   1990    1991   1992
Bolivia    5        6     7
Cambodia   8        9     10
Russia     11       12    13

I'm using R version 2.15.2 and using the library WDI to poll the World Bank for the information.  I'm attaching my code as it stands so far that will work for a single country.  I will then paste the code when I try to do it for all countries.  Any help would be greatly appreciated.  Thanks.
library(WDI)
x<-WDI(country="US",indicator="NY.GDP.MKTP.CD",start = 1980, end=2012)
a<-as.matrix(x$country)
b<-x$year
x<-as.data.frame(t(x))
colnames(x)<-b
x<-x[-1:-2,][-2,]
x<-x[,order(ncol(x):1]
a<-a[1,]
rownames(x)<-a
x

The change for when I try to change to all countries is changing the argument "US" to "all" in WDI.
I appreciate any and all help on this!  Thank you in advance!

A: Using reshape2 package:
Assuming your data.frame is df (I changed the second column name to Interest):
require(reshape2)
# use dcast as:
dcast(df, Country ~ Year, value.var="Interest")

#    Country 1990 1991 1992
# 1  Bolivia    5    6    7
# 2 Cambodia    8    9   10
# 3   Russia   11   12   13

A:  reshape(dfrm, timevar="Year", direction="wide", idvar='Country')
#-------------
   Country Variable_of_Interest.1990 Variable_of_Interest.1991 Variable_of_Interest.1992
1  Bolivia                         5                         6                         7
4 Cambodia                         8                         9                        10
7   Russia                        11                        12                        13

If you wanted to fix the names to your liking then setNames could be useful:
setNames( reshape(dfrm, timevar="Year", direction="wide", idvar='Country'),
           c("Country", unique(dfrm$Year) )  )
#--------------
   Country 1990 1991 1992
1  Bolivia    5    6    7
4 Cambodia    8    9   10
7   Russia   11   12   13

Note that column names with leading digits are not really valid unless quoted.


text:
Q: Change form input attribute 'name' to 'data-encrypted-name' in Rails forms Change form input attribute 'name' to 'data-encrypted-name' discusses Django, but this question is about Rails.
I created a form in Rails to handle credit card payments with Braintree. However, the encryption doesn't work because Rails adds name attributes to the forms. As per the Braintree Docs, I want to replace the name attributes with data-encrypted-name attributes. How do I do this?
This (nested) form helper:
<%= cc.text_field :number %>

..creates the following element:
 <input id="credit_card_number" name="credit_card[number]" size="30" type="text">

How do I replace name with data-encrypted-name?

A: Try text_field_tag like
<%= text_field_tag 'credit_card[data-encrypted-name]', size: 30 %>

You may also assign a value, for example
<%= text_field_tag 'credit_card[data-encrypted-name]', cc.number, size: 30 %>

A: Actually Philp's answer works.  Given Braintree's docs, the following in development mode runs as intended:
c.text_field  :number, 'data-encrypted-name' => "number"


text:
Q: Dual of $\mathbb Z^I$ for uncountable $I$
Let $I$ be an infinite set. There is a homomorphism of abelian groups $\mathbb{Z}^{(I)} \to \hom(\mathbb{Z}^I,\mathbb{Z})$ which sends the basis element $e_i$ to the projection $p_i$. If $I$ is countable, it's a famous result of Specker1 that this is actually an isomorphism. But what happens when $I$ is uncountable?

Clearly it is injective. Surjectivity means that $\phi \in \hom(\mathbb{Z}^I,\mathbb{Z})$ is determined by the values $\phi(e_i)$ and that these values vanisch for almost all $i$. I can't copy the proof for the countable case.
1 Ernst Specker, Additive Gruppe von Folgen ganzer Zahlen, Portugaliae Math. 9 (1950), 131-140. MR0039719 (12,587b)

A: With regard to Mariano's answer, I believe some clarification is in order. A closely related question was asked by Michael Barr and answered by user Ralph here. In brief, the homomorphism named in Martin's question is in fact an isomorphism, provided that $I$ has cardinality less than the first measurable cardinal.
Shelah and Strüngmann (accessible here) refer to this result as well, using the same source given by Ralph, just before Definition 2.1:

For generalizations to products of larger cardinalities and the resulting definition of slenderness for abelian groups we refer to [EM] or [F1]

where [EM] is the text by Eklof and Mekler. It seems that Shelah and Strüngmann are talking about something slightly different: homomorphisms out of free complete products (but using a notation which could unfortunately suggest direct products).


text:
Q: Gridsearch CV outputs NAN score for specific split I'm having no problem running the code without GridsearchCV, however I keep getting the same error:
UserWarning: One or more of the test scores are non-finite: [nan]

when I do use it.
I am using a Pipeline that looks as follows:
transform = ColumnTransformer(

    transformers=[
        ("cont", StandardScaler(), cont),
        ("cat", OneHotEncoder(drop='first'), cat),
    ]
)

clf = Pipeline(
    steps=[("preprocessor", transform), ("classifier", LogisticRegression())]
)

And I am running the following:
param_grid_lr = {
    'classifier__solver': ['saga'],
    'classifier__class_weight': ['balanced']
}
cv = RepeatedStratifiedKFold(n_splits=6, n_repeats=1, random_state=1)
grid_search = GridSearchCV(estimator=clf, param_grid=param_grid_lr, n_jobs=6, cv=cv)

Without RepeatedStratifiedKfold does not change anything.
The full error looks as follows :
{'mean_fit_time': array([6.5918897]),
 'std_fit_time': array([0.05099964]),
 'mean_score_time': array([0.03199418]),
 'std_score_time': array([0.00810072]),
 'param_classifier__class_weight': masked_array(data=['balanced'],
              mask=[False],
        fill_value='?',
             dtype=object),
 'param_classifier__solver': masked_array(data=['saga'],
              mask=[False],
        fill_value='?',
             dtype=object),
 'params': [{'classifier__class_weight': 'balanced',
   'classifier__solver': 'saga'}],
 'split0_test_score': array([0.80664902]),
 'split1_test_score': array([0.80201786]),
 'split2_test_score': array([nan]),
 'split3_test_score': array([0.79902961]),
 'split4_test_score': array([0.80355075]),
 'split5_test_score': array([0.8017864]),
 'mean_test_score': array([nan]),
 'std_test_score': array([nan]),
 'rank_test_score': array([1])}

What I would like ideally is to have a grid search searching through parameters that I would give as
solvers = ['saga']
penalty = ['elasticnet']
C_value = [0.1]
grid = dict(solver=solvers,penalty=penalty,C=C_value)

How could I solve the error and would the easier above solution be feasible? I also tried to run the code with error_score = "raise", but then the program never ends.


text:
Q: Css transform 3d I'm trying to create a CSS opening book, but the transitions doesn't seem to work.
https://jsfiddle.net/g722fq84/
@-webkit-keyframes spincube {
from,to  {                                                    }
10%      { transform: rotateY(-90deg) translatex(60px) translatez(75px)
 }

}
the final position of the cover is fine, but the cover goes right at the beginning, how do I fix it?

A: Instead of translating the div on the x and z axis you can specify a transform origin.
.front {
    -webkit-animation-name: spincube;
    -webkit-animation-timing-function: ease-in-out;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-duration: 2s;
    transform-origin: left;
}

Updated jsfiddle:
https://jsfiddle.net/g722fq84/2/


text:
Q: find ALL signs(characters, whitespaces, digits etc.) before regex I want to find(to remove this with perl, but this is not the question) all characters, digits, whitespaces before a special regex.
Example:
this is my test
foo ... == < foo
something else

myregex
 all other

So I want to find
this is my test
foo ... == < foo
something else

its ok when
myregex

is also "highlighted".
I found some other post regex to remove all text before a character, but this does not realy match my problem...

A: The question is worded very badly. As I understand it, you want to remove everything before the part that matches your regular expression.
If that's the case, this might help: s/.*(<REGEX>)/\1/g
This matches all the characters before your regex (.*) and then matches your regex and creates a group. Once the matching is complete, it replaces all the matched section with the contents of the group alone (\1).


text:
Q: How do I execute a function on-close or on dismiss of  for Polymer 1.0? Question:

How do I automatically execute a function whenever my <paper-dialog> element is closed?

Version: Polymer 1.0
Code:
<paper-dialog id="paper-id"
              entry-animation="scale-up-animation"
              exit-animation="scale-down-animation">
    <sample-element></sample-element>
</paper-dialog>

A: Even this is old topic, there is still 1 thing that people should know and be aware of:
I highly recommend you to also check event.target inside your listener function. For example, if you have another element using iron-overlay inside paper-dialog, closing that elements will trigger listener on paper-dialog. (you can try this with vaadin-date-picker).
So:
<paper-dialog on-iron-overlay-closed="_myClosedFunction"></paper-dialog>

and then _myClosedFunction:
_myClosedFunction(e) {
  if(e.target.nodeName == "PAPER-DIALOG") {
    //...toDo stuff...
  }
}

Now you are guaranteed that whenever only paper-dialog is closed, your code will be executed

A: paper-dialog inherits the Polymer.IronOverlayBehavior, which has the iron-overlay-opened and iron-overlay-closed events.
<paper-dialog
  on-iron-overlay-opened="_myOpenFunction"
  on-iron-overlay-closed="_myClosedFunction"></paper-dialog>

*

*https://www.webcomponents.org/element/@polymer/iron-overlay-behavior

*code: https://github.com/PolymerElements/iron-overlay-behavior/blob/master/test/iron-overlay-behavior.html (for example: take a look at line 147 for the iron-overload-opened event)


text:
Q: Rectifying the image I have problem in remaping the image, I used my own millimeter sheet which contains coplanar set of points, I applied the method of direct radial alignment still the image is warped not rectified, can someone help me to find where my error is. Xw, Yw, Zw are the real world coordinates, Xf, Yf are the corresponding pixel coordinates. Cx, Cy are the coordinates of the center of distortion.
import cv2
import numpy as np
from scipy.optimize import minimize

Xd = dx*(Xf-Cx)/Sx
Yd = dy*(Yf-Cy)
n1=6
A=np.zeros((N, n1))
for i in range(N):
   for j in range(n1):
      A[:, 0] = Yd*Xw
      A[:, 1] = Yd*Yw
      A[:, 2] = Yd
      A[:, 3] = -Xd*Xw
      A[:, 4] = -Xd*Yw
      A[:, 5] = -Xd
X = solution(A)
Sr = r1_prime**2 + r2_prime**2 + r4_prime**2 + r5_prime**2
Ty = np.sqrt(Sr-np.sqrt(Sr**2-4*(r1_prime*r5_prime-r2_prime*r4_prime)**2))/(2*(r1_prime*r5_prime-r2_prime*r4_prime)**2)
 #compute the rotation matrix components:
 r1 = (X[0]/X[5])*Ty
 r2 = (X[1]/X[5])*Ty
 r4 = (X[3]/X[5])*Ty
 r5 = (X[5]/X[5])*Ty
 Tx = (X[2]/X[5])*Ty
 s = -np.sign(r1*r4+r2*r5)
 r3 = np.sqrt(1-r1**2-r2**2)
 r6 = s*np.sqrt(1-r4**2-r5**2)
 r7 = np.sqrt(1-(r1**2+r4**2))
 r8 = np.sqrt(1-(r2**2+r5**2))
 r9 = np.sqrt(-1+Sr*Ty**2)
 n11 = 2
 A1=np.zeros((N, n11))
 for i in range(N):
    for j in range(n11):
       A1[:, 0] = r4*Xw + r5*Yw +Ty
       A1[:, 1] = -Yd
 b1 = (r7*Xw + r8*Yw)*Yd
 U1, S1, VT1 = np.linalg.svd(A1)
 Sigma = np.zeros((A1.shape[0], A1.shape[1]))
 Sigma[:A1.shape[1], :A1.shape[1]] = np.diag(S1)
 J1 = np.zeros((A1.shape[0], A1.shape[1]))
 J1[:A1.shape[1], :A1.shape[1]] = np.linalg.inv(np.diag(S1))
 H1 = np.zeros((A1.shape[0], A1.shape[1]))
 H1[:A1.shape[0], :A1.shape[0]] = np.linalg.multi_dot([U1, J1, VT1])
 H1 = H1.T
 x1 = np.dot(H1, b1)
 f  = x1[0]
 Tz = x1[1]
 R = np.array([[r1, r2, r3], [r4, r5, r6], [r7, r8, r9]])
 def func(guess):
    k1 = guess[0]
    k2 = guess[1]
    f = guess[2]
    tz = guess[3]
    sx = guess[4]
    r = np.sqrt((dx*(Xf-Cx)/sx)**2 + (Yd)**2)
    return np.sum((Yd*(1+k1*r**2 + k2*r**4)*(r7*Xw + r8*Yw + r9*Zw + tz)-f*(r4*Xw + r5*Yw + r6*Zw + Ty))**2)
x0 = np.array([0, 0, f, Tz, 1])
i = minimize(func, x0, method='COBYLA', options={'disp': True})
K1 = i.x[0]
K2 = i.x[1]
F = i.x[2]
Pz = i.x[3]
Sx = i.x[4]
dx_new = dx*Sx
nx, ny = img.shape[1], img.shape[0]
X, Y = np.meshgrid(np.arange(0, nx, 1), np.arange(0, ny, 1))
x = X.astype(np.float32)
y = Y.astype(np.float32)
rd = np.sqrt((y-Cy)**2 + (x-Cx)**2)
map_x = y*(1+K11*np.power(rd, 2)+K22*np.power(rd, 4))
map_y = x*(1+K11*np.power(rd, 2)+K22*np.power(rd, 4))
imgg = cv2.remap(img, map_x, map_y, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)

enter image description here


text:
Q: Displaying high dimensional box plots If several box plots are to be displayed on a graphic where the X-axis represents a unique level, but one which is continuous (like per-year over a very long study) is there a well known way to condense a large number of boxplots aside from the obvious of aggregating up by large subsets of the X?

A: Illustrating @gung's suggestion, here are boxplots (made in R)--one for each of 10 'years'.
Each boxplot shows 12 (simulated) 'monthly' values of a variable x, which is gamma
distributed. Gamma shapes increase gradually from 2 to 8 during
the 120 months, and rates from about .32 to about .45.
Red line segments connect the averages for the 10 years. Such a graph is still clearly readable with 30 years instead of 10 (second figure).

# R code for first figure
set.seed(329)                      # for reproducibility
Month = 1:120
shape = seq(2, 8, len=120); rate = seq(.1,.2,len=120)^.5
x = rgamma(120, shape, rate)
Year = rep(1:10, each=12)
MAT = matrix(x, byrow=T, nrow=10)  # a row for each year
a = rowMeans(MAT)                  # 10 averages
boxplot(x ~ Year, col="skyblue2", pch=19)
 lines(1:10, a, type="l", lwd=2, col="red")


text: Q: How to open chrome standalone window in extension? I am developing a chrome browser action extension. I want to be able to open chrome standalone window when i click a button in default action. How can I do that? And how can I stablish a communication between default action and the window?


text:
Q: How to replace dmenu with fzf as application launcher in suckless dwm I am using dwm with dmenu but am trying to replace dmenu for fzf as an application launcher. I have looked at examples in fzf wiki but did not find information about a particular problem.
The problem is that I can not start PhpStorm with the setup shown in the example. So I came up with partial and incomplete solution probably due to lack of knowledge of Linux.
Here is my menu script:
#!/usr/bin/env bash

st -c phpstorm -n phpstorm -e sh -c "storm" & disown
sleep 5; kill $!;

This is my helper script called storm:
#!/bin/bash

result=$(find ~/www -type d | fzf )

[ -z $result ] && exit
nohup phpstorm $result >/dev/null 2>&1

I have to kill the suckless terminal session after phpstorm started otherwise the window with terminal after fzf selection remains open and I have to close it manually.
PhpStorm, on the other hand, operates differently than vscode or sublime as it starts with jvm. And even if I do phpstorm dir & it keeps throwing java output into the log. I can't make it start in a background properly, does any one know how this should be done in a better way?

A: I have managed to achieve results with the following two scripts
fzfmenu script:
#!/usr/bin/env bash

st -c fzfmenu -n fzfmenu -g "100x12" -e sh -c "storm" & disown

storm script:
#!/bin/bash

result=$(find ~/www -type d | fzf)

[ -z $result ] && exit

(nohup phpstorm $result >/dev/null 2>&1 &)

pkill -f fzfmenu


text:
Q: Recommended filesize range for html/js/css/jpg/png for http transfer When optimizing websites I've used concatenating and spriting to group related, reusable bits together but I'm often wondering how much or how little to package assets for delivery to the browser (sometimes automated tools aren't always part of my build process, though I prefer them).
I'm curious if there are some sensible guidelines just in the area of filesize when combining assets for delivery to the browser. Assuming no compression, or caching, just straightforward http transfer from a server to a browser with or without AJAX.

*

*What is the largest smallest filesize recommended?
I've heard that because of packet size (right? apologies if that was inept) that 1kb and 2kb of data will transfer at basically the same speed — is there a general threshold in kb where additional bytes start impacting transfer rate.

*Does transfer speed change linearly with filesize, or does it stair-stepper?
Extending the first question, does each kilobyte increase transfer speed in a fairly linear fashion? Or does it stair-stepper at packet-sized intervals (again, possibly inept word choice)?

*Is there a maximum size
Again, I know there are lot's contextual reasonings that influence this, but is there are filesize that is inadvisably large given current networks, browsers, or is it heavily dependent on the server and networks? If there is a good generalization, that's all I'm curious about.
It probably goes without saying, but I'm not a server/networking expert, just a front-end dev looking for some sensible defaults to guide quick decisions in asset optimization.

A: It really depends on the server, network, and client.
Use common sense, is the basic answer: Don't try to send several-megabyte bitmaps, or the page will take as long to load as if the person is trying to download any other several-megabyte file. A bunch of PNGs right there on a single page, on the other hand, will not really be noticeable to most modern users. In a more computational realm than you've asked, don't abuse iframes to redirect people to several steps of other web pages.
If you want more information about actual transmission, the maximum size of a single TCP packet is technically 64kB, but you're not really going to be sending more than 1.5kB in a single packet. However, TCP is stream-based, so the packet size is mostly irrelevant. You should be more concerned with bandwidth of modern machines, and considering how efficient we have video asset streaming nowadays, I really don't think you should be overly worried about delivering uncompressed assets to your users.
Because of the relative infrequency of actual delivery errors (which have to be corrected over TCP), along with the miniscule packet size relative to the size of most modern web pages, it's going to increase in delivery time pretty much linearly with total size (again, like one giant file). There are some details about multi-stage web page delivery that I'm leaving out, but they're mostly ignored when you're delivering high-asset-count web pages.
Edit: To address your concern (in the title) about transferring actual html/js files, they're just text in transfer. The browser does all of that rendering and code-running for you. If you have a single jpg, it's going to mostly overshadow any html/js you have on the page.
Transfer size: maximum packet size for a TCP connection
http flow (a rough view): http://www.http.header.free.fr/http.html
Basically, as you get the primary html document representing the page as a whole (which is from your initial request to access the page), you parse for other URLs specified as images or scripts, and request those from the server for delivery to your session. The linked page is old but still relevant, and (I hope) easy to understand.
If you want actual bandwidth statistics for modern users, that's probably too much for me to track down. But if you want more technical info, wikipedia's pages on HTTP and TCP are pretty great.


text:
Q: How to save the structure of my list of matrices from lapply-attack? I want to convert a list of integer matrices to numeric. I know that lapply is not friendly to internal structures, but is there a lapply-solution?
mtList = list(matrix(sample(1:10),nrow=5),
              matrix(sample(1:21),nrow=7))
str(mtList)

# This works, and I could wrap it in a for loop
mtList[[1]][] = as.numeric(mtList[[1]])
mtList[[2]][] = as.numeric(mtList[[2]])
str(mtList)

# But how to use lapply here? Note that the internal
# matrix structure is flattened
mtList1 = lapply(mtList,function(x)x[] = as.numeric(x))
str(mtList1)

A: You have to return the value in your lapply workhorse function:
mtList1 = lapply(mtList,function(x) {
  x[] = as.numeric(x)
  x
})

str(mtList1)
# List of 2
#  $ : num [1:5, 1:2] 1 7 6 3 9 10 5 2 8 4
#  $ : num [1:7, 1:3] 21 3 15 14 6 4 18 17 9 8 ...

A: A marginally simpler alternative could be to coerce by multiplying by 1.0 (or arguably, more robustly, raising to the power of 1.0)...
mtList1 <- lapply( mtList , "*" , 1.0 )
str(mtList1)
#List of 2
# $ x: num [1:5, 1:2] 2 8 1 5 7 9 3 10 4 6
# $ x: num [1:7, 1:3] 17 20 9 11 2 18 1 4 12 10 ...