text:
Q: How to get the next object in a list of objects? I'm using a Map in my application to store each location within a fictional game map. The current implementation allows me to get the start node, ie Tiberius.
But I'm not sure how I can get to the next location on the map relative to the current location the player is at. For example when I create the map I am at "Tiberius" by default, so I'm wondering how I can create a method that will iterate to the next location, which would be "Desert" while a subsequent call to move() would bring the player to "Jerusalem".
The graph is wired up as shown below with each location having a child location.
From a quick search I see that a list can be iterated through by a field in the ID, like this get element by ID  but in this implementation I need to get the next location relative to the current location.
Does anyone know how this method could be implemented?
This is how I've set up the map at the moment in my main class:
public class Main implements Commands{

    public static void main(String[] args)  {

        //Boolean to signify game state
        boolean gameNotOver = true;

        //main game loop
        while (gameNotOver) {

            GameMap playerMap = new GameMap();
            playerMap.getStartNode();

            Main mainObj = new Main();

            //Take in user commands here
            //and parse commands
            String input = Input.getInput();
            if (input.equals("description")) {
                System.out.println("Description: " );
            } else if (input.equals("move")) {
                System.out.println("Moving to the next location in map.. " );
                mainObj.move();
        }

        //Game over
        System.out.println("Game Over!");
        System.exit(0);
    }

    //Game player commands inherited from GameCharacterInterface:

    public String move() {
         //want to create a method here that will call the next
         //location based on the current location that the player is in.
        // TODO Auto-generated method stub
        return null;
    }

}

This is the Location class used to model the locations:
public class Location {

    private Location[] location;

    private int id;

    private String description;

    private String weight;

    private String name;

    private Item item;

    private Exit[] exit;

    private boolean visited = false;
    private boolean goalLocation;
    private int approximateDistanceFromGoal = 0;
    private Location parent;

    private Map<Location, Integer> children = new HashMap<Location, Integer>();

    public Location() {
        super();
    }

    public Location(String name){
        this.name = name;
    }

    public Location(String name, int goalDistance){
        this.name = name;
        this.approximateDistanceFromGoal = goalDistance;
    }

    public Location[] children(){
        return (Location[]) children.keySet().toArray(new Location[children.size()]);
    }

    public int getDistance(Location loc){
        if(children.get(loc) == null) System.out.println(this.name + ": " + loc.getName());
        return children.get(loc);
    }

    public int getChildLocationCount(){
        return children.size();
    }

    public void addChildLocation(Location child, int distance){
        children.put(child, distance);
    }

    public boolean isLeaf(){
        if (children.size() > 0){
            return false;
        }else{
            return true;
        }
    }

    public void removeChild(Location child){
        children.remove(child);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDescription ()
    {
        return description;
    }

    public void setDescription (String description)
    {
        this.description = description;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public Exit[] getExit() {
        return exit;
    }

    public void setExit(Exit[] exit) {
        this.exit = exit;
    }

    public Location[] getLocation() {
        return location;
    }

    public void setLocation(Location[] location) {
        this.location = location;
    }

    public boolean isVisited() {
        return visited;
    }

    public void setVisited(boolean visited) {
        this.visited = visited;
    }

    public boolean isGoalLocation() {
        return goalLocation;
    }

    public void setGoalLocation(boolean goalLocation) {
        this.goalLocation = goalLocation;
    }

    public int getApproximateDistanceFromGoal() {
        return approximateDistanceFromGoal;
    }

    public void setApproximateDistanceFromGoal(int approximateDistanceFromGoal) {
        this.approximateDistanceFromGoal = approximateDistanceFromGoal;
    }

    public Location getParent() {
        return parent;
    }

    public void setParent(Location parent) {
        this.parent = parent;
    }

    public Item getItem() {
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }

    @Override
    public String toString() {
        return "Location [location=" + Arrays.toString(location) + ", id=" + id
                + ", description=" + description + ", name=" + name + ", item="
                + item + ", exit=" + Arrays.toString(exit) + "]";
    }

}

And this is the GameMap showing each of the locations and the getStartNode():
public class GameMap {

private Location tiberius;

    public GameMap() {

        //Creating Locations
        tiberius = new Location("Tiberius", 200);
        tiberius.setDescription("You are in the city of Tiberius. There is a sword on the ground in front of you. You see a long street with high buildings and a castle.You see an exit to the south.");

        Location desert = new Location("Desert", 170);
        desert.setDescription("You are in hot dreary desert, surrounded by sand dunes and nothingness, you see an exit to the south.");
        Location jerusalem = new Location("Jerusalem", 270);
        jerusalem.setDescription("You are at battlefield of Jerusalem. You are in awe of your surroundings, you see an exit to the west.");
        Location hattin = new Location("Hattin", 120);
        hattin.setDescription("You are at battlefield of Hattin. You see the ruination of the battle and fallen comrades...You see an exit to the north.");
        Location damascus = new Location("Damascus", 130);
        damascus.setDescription("You are in Damascus. You see the some shady characters...you see an exit to the west.");
        Location tripoli = new Location("Tripoli", 80);
        tripoli.setDescription("You are in Tripoli. You see the some more shady characters...you see an exit to the north.");
        Location antioch = new Location("Antioch", 60);
        antioch.setDescription("You are in the city of Antioch. You see a long street with high buildings and a castle.. You see the some more shady characters...you see an exit to the north.");
        Location sis = new Location("Sis", 100);
        sis.setDescription("You are in the city of Sis....exit ahead in the west.");
        Location tarsus = new Location("Tarsus", 20);
        tarsus.setDescription("You are in the city of Tarsus. ...you see an exit to the south.");
        Location cyprus = new Location("Cyprus", 0);
        cyprus.setDescription("You have reached the Byzantine Empire, your quest has finished!");
        cyprus.setGoalLocation(true);

        //Adding child locations
        tiberius.addChildLocation(desert, 105);
        desert.addChildLocation(jerusalem, 105);
        jerusalem.addChildLocation(hattin, 323);
        hattin.addChildLocation(damascus, 121);
        damascus.addChildLocation(tripoli, 121);
        tripoli.addChildLocation(antioch, 220);
        antioch.addChildLocation(sis, 126);
        sis.addChildLocation(tarsus, 121);
        tarsus.addChildLocation(cyprus, 126);

    }

    public Location getStartNode(){
        System.out.println(tiberius.toString());
        return tiberius;

    }

}

A: Brian, get rid of this field from Location:
Map<Location,Integer> children;

Replace it with two fields.
Location next;
int goalDistance;

Then, in your game controller, keep a reference to the current location of the character.
For example:

Location currentLoc = tiberius;

Then, each time move() is called, just say

currentLoc = currentLoc.next;

A: I think you're saying you want a method on the Location class called next() that will return the next location. So why not just do this?
public Location next() {
    Location nextLocation = null;
    for (Location child : children.keySet()) {
        nextLocation = child;
        break;
    }
    return nextLocation;
}

This is based on your assertion that there will only ever be one entry in the children Map, of course. If this ever changes in future, you could add a test (of unknown design at this point) that the child is the one you want:
public Location next() {
    Location nextLocation = null;
    for (Location child : children.keySet()) {
        if (isCorrectChild(child)) {
            nextLocation = child;
            break;
        }
    }
    return nextLocation;
}


text:
Q: How do I set up bash completion for command arguments? When I open up the command line and type in git, I get a bunch of completions for arguments of git, like add, commit, merge, and so on.
How do I add this kind of completion to my own apps?
So far, I've been able to specify the first level of completion like this:
$ complete -W "asd asdf" ./test.py

$ ./test.py asd
asd asdf

But it tries to keep going after that:
$ ./test.py asdf asd
asd asdf

I've tried setting a completion for the second level by running complete -W "lol" "./test.py asd", but that doesn't work.
What's the proper way to set these up? And once I've figured out all of the commands, where do I have to put them? Running a big list of these commands in .bashrc, every time a terminal is opened, doesn't seem too efficient (plus I don't want to mess with users' files if I don't have to).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Determining Earth's circumference using shadows The problem is:
Assuming the Sun is far away from Earth and that light rays are arriving parallel to each other, determine Earth's circumference, assuming that it
is spherical.
Does anyone know how to solve this? Any hints or advice? I've been working some of the geometry but haven't gotten anything solid yet.

A: Draw two right triangles, initially with corresponding legs parallel to one another.  One triangle has legs of 10 m and 0.113 cm, corresponding to one pole and its shadow.  The other has legs of 10 m and 1.36 m, for the other pole.
This is not correct because the hypoteneuses which correspond to the Sun's rays are not parallel.  You must rotate one triangle through the difference between corresponding acute angles of the pair, to render the hypoteneuses parallel.  The angle of rotation is then the amount of arc between the poles on the round Earth.
Render that arc in radians and divide into the 10 km distance between the ploes.  This gives the radius of the Earth, which multiplied by $2\pi$ gives the circumference.

A:
The diagram shows the system you have. You can work out $\theta$ and $\phi$ with standard trigonometric methods. Then $\phi-\theta$ gives you an angle, and you have the arclength of 790km. This allows you to compute the radius of the earth, and thus the circumference using $2\pi r$.


text:
Q: Is it possible to define a block with default arguments in Ruby? This question deals with optional arguments passed to a Ruby block. I'm wondering if it's also possible to define arguments with default values, and what the syntax for that would be.
At first glance, it appears that the answer is "no":
def call_it &block
  block.call
end

call_it do |x = "foo"|
  p "Called the block with value #{x}"
end

...results in:
my_test.rb:5: syntax error, unexpected '=', expecting '|'
    call_it do |x = "foo"|
                   ^
my_test.rb:6: syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '('
      p "Called the block with value #{x}"
         ^
my_test.rb:7: syntax error, unexpected kEND, expecting $end
    end
       ^

A: ruby 1.9 allows this:
{|a,b=1| ... }

A: Poor-man's default block arguments:
def call_it &block
  block.call
end

call_it do |*args|
  x = args[0] || "foo"
  p "Called the block with value #{x}"
end


text:
Q: Categorizing Sales by Team The question is: "In one record for each squad, show the team, its US (area = '-US') sales for 2018 and its UK (area = 'UK') sales for 2018. "
Would this not work?
SELECT squad, SUM(CASE WHEN area = "US" THEN sales_2018 ELSE 0 END) AS "US", SUM(CASE WHEN area = "UK" then sales_2018 ELSE 0 END) AS "UK"
FROM squad A
Inner join Sales b on a.account = b.account
GROUP BY squad

Tables involved:

A: From what i understand you can use pivot to achieve your result.
select squad,[US],[UK] from(
select sq.squad,sq.Area,sa.sales_2018 from Sales sa inner join Squad sq on sa.account=sq.account
) tbl
pivot(
sum(sales_2018) for Area in ([US],[UK])
) pvtTable

The result of inner query returns

squad
Area
sales_2018

IT
US
1300.00

IT
UK
3300.00

Finance
US
3400.00

Finance
UK
2500.00

After applying Pivot

squad
US
UK

IT
3400.00
2500.00

Finance
1300.00
3300.00


text:
Q: How to customize the custom options in magento? For example
In magento have added two custom options as Size(S,L,XL) and Color(RED,BLUE).
But in frontend i have to show the size as

And color as

Ideas welcome.

A: There are lots of extension in magento store(magento-conect), search by color swatch you may get some modules what you need,
eg,
some freemodules:
http://www.magentocommerce.com/magento-connect/gala-color-swatches-free-1.html
http://www.magentocommerce.com/magento-connect/color-swatch-1.html
http://www.magentocommerce.com/magento-connect/configurable-colors.html
some paid modules:
http://www.magentocommerce.com/magento-connect/product-color-swatch.html
http://www.magentocommerce.com/magento-connect/color-swatch-with-zoom.html
use what you like

A: I suggest you create classes using the color names and modify the filter labels to add that class (given the option name) and have a nice CSS behind that to display some nice squares.
As far as sizes are concerned, you could either do the same, or use custom font-icons.

A: I have developed new module Option swatches that allow to display option swatches on product details page and product list page by replacing drop-down custom options or configurable product's options.
Check here http://hkpatel201.blogspot.in/2015/01/product-custom-option-pro-with-optionswatch.html
For Magento2: Product Custom Option Swatches For Magento 2


text:
Q: How to remove file associations with IDEA? OS - Windows 7 32-bit. Command assoc .java= does not help. I have deleted IDEA. Now I need to delete ALL file associations with IDEA.

A: *

*Launch regedit or any other registry edit application

*Go to HKEY_CLASSES_ROOT in the registry

*Search ".java" under this key.

*Click on this key and delete the (Default) value


text:
Q: bar chart with multiple bars and 1 label Sample grouped stacked bar chart
Above is a sample chart.  The colored parts of the bars are tickets opened.  The diamond part of the bars are tickets closed.  I only want 1 label for tickets closed.
var ctxMonthly = document.getElementById('monthlyTkts').getContext('2d');
            var chartMonthly = new Chart(ctxMonthly, {
                // The type of chart we want to create
                type: "bar",
                    // The data for our dataset
                data: {
                    labels: ["Week 1", "Week 2", "Week 3", "Week 4"],
                    datasets: [
                    {
//                      label: "Critical-Opened",
                        stack: "Critical",
                        backgroundColor: ["red", "red", "red", "red"],
                        borderColor: ["black", "black", "black", "black"],
                        data:
                            <?php echo json_encode($monthlyOpenedData[0]); ?>
                    },
                    {
//                      label: "Critical-Closed",
                        stack: "Critical",
                        backgroundColor: ["purple", "purple", "purple", "purple"],
                        borderColor: ["black", "black", "black", "black"],
                        data:
                            <?php echo json_encode($monthlyClosedData[0]); ?>
                    },
                    {
//                      label: "Urgent-Opened",
                        stack: "Urgent",
                        backgroundColor: ["orange", "orange", "orange", "orange"],
                        borderColor: ["black", "black", "black", "black"],
                        data:
                            <?php echo json_encode($monthlyOpenedData[1]); ?>
                    },
                    {
//                      label: "Urgent-Closed",
                        stack: "Urgent",
                        backgroundColor: ["purple", "purple", "purple", "purple"],
                        borderColor: ["black", "black", "black", "black"],
                        data:
                            <?php echo json_encode($monthlyClosedData[1]); ?>
                    },
                    {
//                      label: "Elevated-Opened",
                        stack: "Elevated",
                        backgroundColor: ["green", "green", "green", "green"],
                        borderColor: ["black", "black", "black", "black"],
                        data:
                            <?php echo json_encode($monthlyOpenedData[2]); ?>
                    },
                    {
//                      label: "Elevated-Closed",
                        stack: "Elevated",
                        backgroundColor: ["purple", "purple", "purple", "purple"],
                        borderColor: ["black", "black", "black", "black"],
                        data:
                            <?php echo json_encode($monthlyClosedData[2]); ?>
                    },
                    {
//                      label: "General-Opened",
                        stack: "General",
                        backgroundColor: ["blue", "blue", "blue", "blue"],
                        borderColor: ["black", "black", "black", "black"],
                        data:
                            <?php echo json_encode($monthlyOpenedData[3]); ?>
                    },
                    {
//                      label: "General-Closed",
                        stack: "General",
                        backgroundColor: ["purple", "purple", "purple", "purple"],
                        borderColor: ["black", "black", "black", "black"],
                        data:
                            <?php echo json_encode($monthlyClosedData[3]); ?>
                    }]
                },
                    // Configuration options go here
                options: {
                    responsive: true,
                    legendCallback: function(chartMonthly) {
                        var text = [];
                        text.push('
');
                        var bgColorsMonthly = ["red", "orange", "green", "blue", "purple"];
                        var chartLabelsMonthly = ["Critical", "Urgent", "Elevated", "General", "Closed"];

                        for(var i = 0;i < 5; i++) {
                            text.push('
');
                            text.push(chartLabelsMonthly[i]);
                            text.push('
');
                        }

                        text.push('
');
                        return text.join("");
                    },
                    scales: {
                        xAxes: [{
                            stacked: true,
                        }],
                        yAxes: [{
                            stacked: true,
                            ticks : {
                                min : 0
                            }
                        }]
                    },
                    legend: {
                        display: false,
                        labels: {
                            boxWidth: 15,
    //                      usePointStyle: true,
                        }
                    }
                }
            });
            document.getElementById('monthlyLabels').innerHTML = chartMonthly.generateLegend();

OK, so I figured out that I needed to use generateLegend to achieve what I wanted with the labels.  Is there anyway for format the legend to look like the auto generated legend and still achieve what I want?


text:
Q: Jmeter regular expression extractor for capturing dynamic value within code Here I am using Jmeter 2.6 to test a .net application.
While extracting dynamic value through regular expression Extractor, I am unable to proceed and getting the match count=0.
My expression is:
window.open('ConsumptionBatchSerial.aspx?Quantity='+ReturnQty+'&ItemCode='+ItemCode+'&Batch='+Batch+'&Serial='+Serial+'&StDetailsId='+StDetailsId+'','','width=810,height=350,left=100,top=150,resizable=1')

From this I want to extract Itemcode,Quantity,Serial,Batch,StDetailsId.
Can anybody have any idea on this concept?
Please post if you are aware of such scenario.
Thanks in advance.

A: If you are wanting to capture the parsed data, which is what would show up in the browser, something like this should work.
(??)Quantity=([^&]*)&ItemCode=([^&]+)&Batch=([^&]+)&Serial=([^&]+)&StDetailsID=([^,]+)
If that string is the exact string you want to match, then something like this should work.
(??)Quantity='\+([^\+]*)\+&ItemCode='\+([^\+]*)\+&Batch='\+([^\+]*)\+&Serial='\+([^\+]*)\+&StDetailsID=\+([^\+]+)
(can't yet comment anywhere to ask for clarification, sorry)

A: Regular Expression Formats to get the following values
1. Quantity
2. Itemcode
3. Batch
4. Serial
5. StDetailsId

Regular Expression
Quantity=(.+)&ItemCode=(.+)&Batch=(.+)&Serial=(.+)&StDetailsId=(.+)','',


text:
Q: Computing dimension of subspaces of cubics Let $L,M,N \in \mathbb{P}^5$ $3$ general subspaces of codimension $3$, and let $l_i$ (resp $m_i,n_i)$, $i=1,2,3$ be three general points on $L_i$ (resp. $M_i,N_i)$.
I can't understand why $I_{L\cup M\cup N}(3)$, (i.e. the space of all cubics through these subspaces with all first partial derivatives vanishing at this $9$ points), has dimension $26$.
I really can't figure out how to attack the problem, so any hint would be appreciate!

A: The dimension of the space of cubics passing through $L$, $M$, and $N$ without extra first derivative conditions at $l_i$, $m_i$, and $n_i$ is 26. And if you impose these extra conditions, the dimension will drop to 17.
To see this note that for a general triple $L,M,N$ there is a unique $\mathbb{P}^2 \times \mathbb{P}^1 \subset \mathbb{P}^5$ such that
$$
L = \mathbb{P}^2 \times \{0\},
\quad
M = \mathbb{P}^2 \times \{1\},
\quad
N = \mathbb{P}^2 \times \{\infty\}.
$$
Cubics in $\mathbb{P}^5$ cut out a complete linear system $\mathcal{O}(3,3)$ and the space of cubics containing $\mathbb{P}^2 \times \mathbb{P}^1$ has dimension 16.
The ideal of $L \cup M \cup N$ in $\mathbb{P}^2 \times \mathbb{P}^1$ is $\mathcal{O}(0,-3)$, so the space of sections of $\mathcal{O}(3,3)$ vanishing on $L \cup M \cup N$ coincides with $H^0(\mathbb{P}^2 \times \mathbb{P}^1,\mathcal{O}(3,0))$, hence has dimension 10. Altogether, this gives
$$
16 + 10 = 26
$$
cubics through $L$, $M$, $N$.
If you want to impose the first derivative conditions at nine points $l_i$, $m_i$, $n_i$, this means that the above section of $\mathcal{O}(3,0)$ vanishes at the corresponding nine points of $\mathbb{P}^2$, and such section is unique. This gives
$$
16 + 1 = 17
$$
as the answer to this question.


text:
Q: How to set a max width for html div for mobile devices using css On Desktop screens everything is responsive and okay. But on mobile devices content doesn't fit the screen, I have to swipe to the left to see all the content, is there anyway to fix that using CSS?

Quote...

......

........

              ...............

This just an example to work with.
And btw I'm using Md-bootstrap as font end framework.

A: This div element has a width of 500px, and margin set to auto.

div.container {
  width:500px;
  margin: auto;

}


text:
Q: Can I directly substitute a specific complex number into a formal power series equation? Suppose there is a formal power series equation, such as
$$\sum_{i=0}^\infty a_i x^i=\sum_{i=0}^\infty b_i\left(\sum_{j=1}^\infty c_j x^j\right)^i.$$
If there is a complex number $r$ which makes $\sum c_jr^j$ and $\sum a_i r^i$ convergent, also, the convergent point of $\sum c_jr^j$, $s$, makes $\sum b_i s^i$ convergent, then, does the equation above still hold when I substitute $r$ into $x$?
Thanks for your discussion.

A: The operation involves re-arranging the power series.  Hence this can only be done if the respective sums converge absolutely.  This is satisfied if the power series is evaluated at a value from inside the respective radius of convergence.
If a power series just converges conditionally, then re-arranging might change its value.  This can only happen if the value where the series is evaluated is on the boundary of the radius of convergence.
See also Riemann's rearrangement theorem.
There are also some posts on mathoverflow that deal with value-preserving permutations of conditionally convergent series, like The stabilizer of the conditionally convergent series.

ad comment: Just that a function is analytic at some point doesn't tell you anything about it's power series expansion.  Take $u(z) = \sum_0 z^n$ for example, with radius of convergence $r_u=1$. $u$ is analytic everywhere except $z=1$, but the series does not converge for any $|z|>1$.  And it does not converge for, say, $z=-1$ or $z=\sqrt{-1}$, either.
Also, if a power series expansion of $f$ around 0 converges for $z$ with $|z|=r_f$, then $f$ is countinuous at $z$.  Again, the opposite is not true in general, and continuiuty of $f$ doesn't tell you anything about $r_f$ or about the becaviour of a power series expansion.
However, your requirement that $f$ is analytic in$^1$ $0\leqslant |z|\leqslant r_f$ for $f\in\{F,G,H\}$ means that the radius of convergence of $f$ is greater than $r_f$ and $r_f$ does not denote the radius of convergence of $f$.  The reason is that, when a power series has a finite radius of convergence $r_f\neq0$, then $f$ has a singularity of some sort for at least one $|z|=r_f$.  Example is polylog $\operatorname{Li}_2(z) = \sum_1 z^n/n^2$ that converges for all $|z|=1$ but it has still a singularity: a branch point at $z=1$.
The conclusion is that you are inside$^1$ the radius of convergence of the functions, thus their power series converge absolutely.
Notice that $z$ above denotes a complex number, and if you replace it by a real number, then what's said above is no more true.  For example, $\arctan z =\sum_0 z^{2n+1}/(2n+1)$ is analytic over $\Bbb R$, yet the power series has finite radius of convergence $r_{\arctan} = 1$.  The reason is that $\arctan$ has branch points at $z=\pm\sqrt{-1}$, so you only see whan't going on over $\Bbb C$.

$^1$Assuming with $D(z,r)$ you denote the closed disk of radius $r$ around $z$.
If, however, $D$ denotes the open disk and $r_f$ stands actually for the respective radius of convergence, then analyticity of $f$ in the open disk $0\leqslant |z| < r_f$ does not tell about whether the power series converges (absolutely) for some $|z|=r_f$.


text:
Q: Multple Criteria in a Single Case inside a Switch Statement Hi all I searched and found old answers like in 2008, im creating firefox addon for new browsers so i can use ecma 5+.
I was trying to do a a switch that had one block meet multiple criteria like if >=0 && <= 3 like below:
switch (blah) {
     case 0, 1, 2, 3: //<<<<<<<< this here please
          //do this;
          break;
     default:
          ///do this
}

This is just a basic example.
I would like multiple values to trigger the same case. How do I do this?

A: This might be what you are looking for. If it is please more clearly define your problem/question.
switch (x) {
   case 0:
   case 1:
   case 2:
   case 3:
   // do this
   break;
   default:
   // do this
}

See also Multiple Cases in Switch:

A: There is one hacky switch style that allows you to specify ranges:
switch (true) {
    case blah >= 0 && blah <= 3:
        //do this
        break
    default:
        //do that
}

It sometimes useful in cases like this.
Maybe it'll do what you want.


text:
Q: Parallel instances each running parallelized code? Using rstan, I am running a code that uses 4 cores in parallel. I have access to a computer with 32 cores and I need to run 3 instances of the same code on different datasets, and another 3 instances of a slightly different code on the same datasets, for a total of 6 models. I'm having a hard time figuring what is the best way to accomplish this. Ideally, the computer would be running 4 cores on each model for a total of 24 cores running at a time.
I've used the parallel package many times before but I don't think it can handle this kind of "parallel in parallel". I am also aware of the Jobs feature in RStudio but one of the good things about rstan is that it interactively shows you how the chains progress, so ideally I would like to be able to see these updates. Can this be accomplished by having 6 different RStudio sessions open at once? I tried running two at a time but I'm not sure if they run in parallel to each other as well, so any clarification would be great.

A: I would suggest using batch jobs instead. In principle, since you don't have that many models, you could simply try writing 9 different R scripts and store them as, e.g., model1.R, model2.R, ..., model6.R. With that, you could then try submitting the jobs in the command line like this:
R CMD BATCH --vanilla model1.R model1.Rout &

This will run the first script in batch mode and output the stdout to a log file, model1.Rout. That way, you can inspect the state of the jobs by just opening that file. Of course, you will need to run the above command for each model.


text:
Q: how to modify array_count_values output i have an array
$array=(1,1,2,3,3,3,4);

i need to find each element how many times each element is exist in array .
So that i use
$occurences = array_count_values($array);

output is
Array
(
    [1] => 2
    [2] => 1
    [3] => 3
    [4] => 1
)

But  i need to arrage the out put in following format
1 : 2
2 : 1
3 : 3
4 : 1

how can i do that ?
is there an other solution rater than using array_count_values
please help ;

A: Use foreach to iterate over every occurance and echo them out.
// If they are in wrong order, sort your array
ksort($occurences);

// Print output
if(count($occurences)>0){
  foreach ($occurences as $key => $value) {
    echo $key.' : '.$value.'
';
  }
}

EDIT
To sort by no of occurances, use arsort.
arsort($occurences);

Of course, before printing it.
If 2:1 must come before 4:1 in your case, use:
asort($occurences);
arsort($occurences);

A: Just use this loop to have output like you need
foreach ($occurences as $k => $v) {
    echo "$k : $v
";
}

A: You can use json_encode or array_keys and array_values
<?php

$array= array(1,1,2,3,3,3,4);
$occurences = array_count_values($array);

$array_keys = array_keys($occurences);
$array_values = array_values($occurences);

for($i=0; $i<count($array_keys); $i++) {
    echo $array_keys[$i].':'.$array_values[$i].'\n';//add \n or \br tag
}

//you can echo json_encode
echo json_encode($occurences);


text:
Q: Gulp browserify/browser-sync unexpected token when compiling SASS I have created a gulpfile.js which works fine so far but as soon I try to add  browser-sync and I change my .scss-file I get this error ParseError: unexpected token and I have no clue why this happens. Another thing is, that even though in my server.js I have set app.listen(3000) it opens a window with localhost:3001???
Here is my gulpfile.js:
var gulp = require('gulp'),
   connect = require('gulp-connect'),
   uglify = require('gulp-uglify'),
   sass = require('gulp-ruby-sass'),
   webserver = require('gulp-webserver'),
   browserify = require('gulp-browserify'),
   browserSync = require("browser-sync").create();

  gulp.task('browser-sync', function(){
     browserSync.init({
        server: {
           baseDir: "./public"
        }
     });
  })

 gulp.task('styles', function() {
    return sass('public/scss/*.scss')
    .pipe(browserify())
    .pipe(uglify())
    .pipe(gulp.dest('public/css'));
 });

 gulp.task('watch', function(){
   gulp.watch('public/scss/*.scss', ['styles'])
 })

gulp.task('webserver', function() {
  gulp.src('root')
  .pipe(webserver({
    livereload: true,
    directoryListing: true,
    port: 3000
  }));
});

gulp.task('default', ['webserver', 'watch', 'browser-sync'])

So, does anyone know what I'm doing wrong??


text:
Q: SQLite: Using a table as a base for other tables I am building a database for a small organisation with around 100 to 200 members. Those members have to pay a small fee to be a member.
I have created a table where all the details of the members are listed:
------------------------------------------
| First name | Last Name | Address  | ...
------------------------------------------
| John       | Smith     | Street 1 | ...
| Jane       | Smith     | Street 2 | ...
| ...        | ...       | ...      | ...

Now I want to create a table where the names of the members are displayed and if they have paid there fee:
----------------------
| Name       | Paid? |
----------------------
| John Smith | yes   |
| Jane Smith | no    |
| ...        | ...   |

Here comes the problem: if a new member is added to the first table, this should be reflected in the second. If a member is no longer a member, the same has to happen.
I searched the internet for solutions, but could only find ones where the table was dropped and recreated, but this isn't really viable as the data in the second table is really important. We don't want a member that already has paid his fee to have to pay it again.
I want to know:

*

*Is this even possible with the use of SQLite?

*If there is a solution, is it guaranteed to keep the data in the second table in the right place?

P.S.: After writing this question, I thought of creating a temporary table, copying the data of the second table, repopulating the original and then copying back the data out of the temporary table. This seems very devious and very difficult to do with a tool like SQLiteStudio. Is there a better way?

A: You should think more in terms of operations on the data, than how you store it.
This is a typical normalization problem. There are as many tuples in members as in paid; both have the same primary key. So you should combine both tables.
Add the field paid to your table members, and make it by default "no".
For instance:
create table members(
  firstname text,
  lastname text,
  paid   bool default false,
   -- any other fields
  primary key (firstname, lastname)

);
and if you insert:
insert into members(firstname, lastname) values ('john', 'smith');

you will get:
| firstname | lastname | paid  |
|-----------+----------+-------|
| john      | smith    | false |

Alternatively you can keep a paid table, declare a foreign key constraint from that table to members (so any tuple in paid has a tuple in members) and then assume that if a member is not in paid, then it has not paid.
Otherwise use the value of the field.

A: You can use triggers that are supported by SQLite.
The link bellow show how create a trigger on insert data:

*

*How to duplicate INSERTS into a separate table?
And the next link show how create a trigger on delete data:

*

*SQLite Trigger Expression For Deleting Rows


text:
Q: How to resolve Invalid argument supplied for foreach() in Laravel I have this code in Laravel-5.8 controller:
$goaltypes = GoalType::where('company_id', $userCompany)->get();
foreach($goaltypes as $goaltype){
     $goaltypedetails = Goal::whereIn('goal_type_id', [$goaltype->id])->where('employee_id', $userEmployee)->get();
}

I got this error:

Invalid argument supplied for foreach()

and it points at:

foreach($goaltypes as $goaltype){

dd($goaltypes); gives me:
  #original: array:14 [▼
    "id" => 8
    "name" => "Employee Targets"
    "updated_by" => 2
    "created_at" => "2020-01-22 13:23:26"
    "updated_at" => "2020-02-25 14:12:30"
    "is_active" => 1
  ]

How do I get this resolved?
Thanks

A: First I think that is bad practice in performance side to make model query inside the foreach loop
It will be good practice if you make one to many relationship between GoalType model and GoalTypeDetail then you can get goaltypedetails at any time you need.
The "invalid argument supplied for foreach()" error occurs when PHP's built-in foreach() tries to iterate over a data structure that is not recognized as an array or object.

A: laravel get() method return Collection  object , this collection has able iterator ,itterator object can  convert to array,already Colllection  has toArray()  method

iterable object to array

$array=iterator_to_array($object);

or

$array=$object->toArray();

Also, the iterable object can be  iterate with foreach loop

 foreach($object as $obj)
 {
    print $obj->foo;
 }

Note
this code not logical, this code has n+1 problem, and possibly cause a slowdown in provinces

$goaltypes = GoalType::where('company_id', $userCompany)->get();
foreach($goaltypes as $goaltype){
     $goaltypedetails = Goal::whereIn('goal_type_id', [$goaltype->id])->where('employee_id', $userEmployee)->get();
}


text:
Q: What is the purpose of this rail on an intel X540-T2 NIC? I recently picked up a pair of Intel X540-T2s for various reasons. They're generally meant for (older) servers and workstations but I'm installing them in relatively modern desktop machines.
I noticed that there's a 'rail' at the bottom of the card that I've never seen on any other card I've used. Its not tied into the (rather beefy?) heatsink, or from what I can tell, the ground and runs a significant length of the card. I'm wondering what this rail is for

It also dosen't seem to be grounded, though its soldered (not fixed by plastic tabs like the heatsink or jacks)

I mean, I guess it could be structural reinforcement, but does the rail provide any purpose, and would I need to connect it to something in a server or workstation application?


text:
Q: where in the db is the "Automatic alias" setting stored for drupal's pathauto I created a bunch of nodes using node_save(). Unfortunately, I forgot to turn on the Automatic alias setting on them. Anyone know how I can do that now? I can't figure out where in the db that setting is stored. (Other non-db approaches are fine, too.)

A: Got the answer on drupal.org: http://drupal.org/node/763874
The short version: that checkbox isn't stored in the db, it's calculated for the form. The reason my nodes didn't create aliases is that there's a limit on the number that can be created at a time (50 by default).

A: In the path auto admin screen you can make a bulk alias creation operation. You can set the maximum alias' Per time created this way aswell.
I believe path alias also can be created in cron jobs, but I'm not quite sure.


text:
Q: How to fix a css navigation flashing issue I have a react app using reactstrap(bootstrap4). I created a simple layout using react-router for the navigation. I cannot figure out why the navbar items flash when you click on one. I am using a built-in NavLink from react-router-dom that keeps the selected NavItem highlighted.
Here is link to the website
Website
Header Component
import {
  Collapse,
  Navbar,
  NavbarToggler,
  Nav,
  NavItem,
  NavbarBrand,
  NavLink } from 'reactstrap'
import { NavLink as RRNavLink } from 'react-router-dom'

const Item = ({link, label}) => (
  <NavItem>
    <NavLink exact activeClassName='active-tab' to={link} tag={RRNavLink}>{label}</NavLink>
  </NavItem>
)

const ROUTES = []

export default class extends React.Component {
  render () {
    return (
      <div className='header-bkg'>
        <Navbar color='faded' light expand='md'>
          <NavbarBrand className='text-white'>Star Designs</NavbarBrand>
          <NavbarToggler onClick={this._onToggle} />
          <Collapse isOpen={this.state.isOpen} navbar>
            <Nav className='ml-auto' navbar>
              {ROUTES.map((x, i) => (
                <Item key={i} {...x} />
              ))}
            </Nav>
          </Collapse>
        </Navbar>
      </div>
    )
  }
}

CSS
   .header-bkg {
    box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.6), inset 0 -1px 1px rgba(0, 0, 0, 0.6), 0 0 5px rgba(0, 0, 0, 0.6);
    border-top: 0 solid rgba(47, 46, 46, 1);
    border-bottom: 0 solid rgba(47, 46, 46, 1);
    background-color: #d7a29e;
}

.nav-link:hover,
.nav-link:active {
    background-color: #ede9e2;
}

.nav-link {
    text-transform: uppercase;
}

.active-tab {
    background-color: #ede9e2;
}

:focus {
    outline: -webkit-focus-ring-color auto 0;
}

@media (max-width: 575px) {
}

@media (max-width: 767px) {
}

@media (max-width: 991px) {

}

@media (max-width: 1199px) {
}

A: On click of menu item, some js code is adding height : 0px on the collapse navbar-collapse element (for the closing dropdown animation effect in mobile view) and then removing it after a few miliseconds. Add the following style, it will not allow the height 0 to get applied in desktop views because of higher specificity and important attribute. Hence, the flickering will not occur.
@media (min-width: 768px) {
    .navbar-expand-md .navbar-collapse {
        height: auto !important;
    }
}

A: Try using:

.yourMenuButtonClass {
    -webkit-transition: none;
  -moz-transition: none;
  -ms-transition: none;
  -o-transition: none;
  transition: none;
      -webkit-transition-duration: 0s;
  -moz-transition-duration: 0s;
  -ms-transition-duration: 0s;
  -o-transition-duration: 0s;
  transition-duration: 0s;
      -webkit-animation: none;
  -o-animation: none;
  animation: none;
}

.yourSubmenuThatAppearsAfterClickClass {
     -webkit-transition: none;
  -moz-transition: none;
  -ms-transition: none;
  -o-transition: none;
  transition: none;
     -webkit-transition-duration: 0s;
  -moz-transition-duration: 0s;
  -ms-transition-duration: 0s;
  -o-transition-duration: 0s;
  transition-duration: 0s;
     -webkit-animation: none;
  -o-animation: none;
  animation: none;
}

Replace the Classes above in CSS accordingly.


text:
Q:  вставдяет не туда куда нужно, как исправить? Пытаюсь использовать <link rel="import" href="..."> и

Для вставки части другого документа.
Вставка происходит. Но не туда куда нужно, а в конец.
Вот пример
Помогите поставить на нужное место. Если можно, пример готового кода scripts. Спасибо.

A: appendChild() всегда вставляет элементы в конец.
function insertAfter(newElem, refElem) {
  return refElem.parentNode.insertBefore(elem, refElem.nextSibling);
}

let link = document.querySelector('link[rel=import]'),
    content = link.import.querySelector('#product-card-7'),
    referenceElement = document.querySelector('#product-card-6');

insertAfter(content, referenceElement);

Стоит заметить, что расположение тега


text:
Q: Child object rotation relative to parent I've been trying to rotate my player's gun target along with the player. My player keeps shooting to right side even though he's facing left.
I've created a target called Firepoint, it's set to as a child Object of the player. I want it to change as the character changes it's direction.
Any help is appreciated.

Here's the code of the player.
 public void Move()
{
    float controlThrow = CrossPlatformInputManager.GetAxis("Horizontal");
    Vector2 playerVelocity = new Vector2(controlThrow * runSpeed, myRigidBody.velocity.y);
    myRigidBody.velocity = playerVelocity;

    bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;

    myAnimator.SetBool("Walking", playerHasHorizontalSpeed);
}

 public void Flipsprite()
{

    bool playerhashorizontalspeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;

    if (playerhashorizontalspeed)
    {
        transform.localScale = new Vector2(Mathf.Sign(myRigidBody.velocity.x), 1f);
        transform.rotation = new Vector2(Mathf.Sign(firePoint.transform.localScale.x), 1f);

    }

}

A: The problem here is that the rotation is not effected by scaling. Only the relative scales and positions.
Also why are you using > Mathf.Epsilon and not simply > 0. As far as I understand you only need to check if it is not 0 ... using Mathf.Epsilon is such a small difference that it actually doesn't matter.
public void Move()
{
    float controlThrow = CrossPlatformInputManager.GetAxis("Horizontal");
    Vector2 playerVelocity = new Vector2(controlThrow * runSpeed, myRigidBody.velocity.y);
    myRigidBody.velocity = playerVelocity;

    bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > 0;

    myAnimator.SetBool("Walking", playerHasHorizontalSpeed);
}

// store the last direction
int direction;

public void Flipsprite()
{
    bool playerhashorizontalspeed = Mathf.Abs(myRigidBody.velocity.x) > 0;

    if (playerhashorizontalspeed)
    {
        // update the direction
        direction = Mathf.Sign(myRigidBody.velocity.x);
        transform.localScale = new Vector2(direction, 1f);
    }
}

Then when you are shooting multiply the direction also with direction
private IEnumerator FireContinuously()
{
    while (true)
    {
        GameObject laser = Instantiate(bullet, firePoint.position, firePoint.rotation);
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(projectileSpeed * direction, 0);
        yield return new WaitForSeconds(projectileFiringPeriod);
    }
}

a small hint:
If you make the type of
public RigidBody2D bullet

and drag in the according prefab again than you don't need to use GetComponent but could directly use
var laser = Instantiate(bullet, firePoint.position, firePoint.rotation);
laser.velocity = ...


text:
Q: Read with python and django an array of input fields i'm tring to read from request.POST an array of fields
<input type="text" name="arrayfield[]" />

<input type="text" name="arrayfield[]" />

<input type="text" name="arrayfield[]" />

<input type="text" name="arrayfield[]" />

<input type="text" name="arrayfield[]" />

<input type="text" name="arrayfield[]" />

<input type="text" name="arrayfield[]" />

if i use print(request.POST) i get that output
<QueryDict: {'csrfmiddlewaretoken': ['p0GWUzgXEEYOTI1710vTsUAPrjUUv5NpqlVCGU7Oq1zw4LWA20d222q1aE8QvlIg'], 'username': ['Oscurodrago'],  'birthday': ['1988-04-16'], 'arrayfield[]': ['try', 'tyey', 'egr', '', 'tyr', '', ''], 'edit': ['Modifica']}>

but when i try get it with request.POST.get('arrayfield[]','') dosen't work
what i have to do?

A: i found that solution
arraylist = request.POST.getlist('arrayfield[]')

A: To use the Post method, you have to make sure your form has {% csrf_token %} if not it won't work.

     <form method="POST">
        {% csrf_token %}
        <input />
    </form>


text:
Q: Compilar programa Visual Studio com banco de dados e passar para outro PC Só uma pergunta básica, ao fazer um form com banco de dados no visual studio e depois de compilado é necessário o computador onde passarei os arquivos para execução ter o sql instalado ou consigo rodar o programa de boa sem nenhum erro?
Pergunto pois ao fazer um teste em outro PC passando os arquivos de compilação para rodar em outro PC aparece um erro de rede a instancia ao estabelecer conexão com o SQL Server. Porém ao continuar o programa roda e grava no banco de dados de boa pois nos arquivos de compilação tem 2 arquivos do banco um com extensão mdf e ldf, não sei se futuramente possa acontecer algo ou como posso fazer para executar e ignorar este erro para que não aparece mais?

A: Bom dia, o banco de dados não compila junto com o seu programa.
Caso você queira usar o software localmente você terá que instalar o sql client na máquina do cliente, segue um link que irá te ajudar: http://www.andrealveslima.com.br/blog/index.php/2015/10/15/instalando-o-sql-server-junto-com-a-aplicacao/


text:
Q: How to find minimum value of function from smoof package? I am using genetic algorithm for finding maximum of Ackley function
lbound <- c(-10, -10)
ubound <- c(10, 10)

m <- makeAckleyFunction(2)
GA <- ga(type = "real-valued", fitness = m, lower = lbound, upper = ubound, maxiter = 1000)

GA@fitnessValue

GA@fitnessValue returns maximum value but I need to find minimum. The solution would be to multiply function by (-1) and then find maximum and multiply by (-1) once more and then I would have the minimum value. But R is not letting me do that:
m <- -(makeAckleyFunction(2))

Error in -(makeAckleyFunction(2)) : invalid argument to unary operator

How to fix that?


text:
Q: How to display multiple annotations in Seaborn Heatmap cells? I want seaborn heatmap to display multiple values in each cell of the heatmap. Here is a manual example of what I want to see, just to be clear:
data = np.array([[0.000000,0.000000],[-0.231049,0.000000],[-0.231049,0.000000]])
labels =  np.array([['A\nExtra Stuff','B'],['C','D'],['E','F']])
fig, ax = plt.subplots()
ax = sns.heatmap(data, annot = labels, fmt = '')

Here as an example to get seaborn.heat to display flightsRoundUp values in the cells.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

def RoundUp(x):
    return int(np.ceil(x/10)*10)

# Load the example flights dataset and conver to long-form
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")
flightsRoundUp =  flights.applymap(RoundUp)

# Draw a heatmap with the numeric values in each cell
f, ax = plt.subplots(figsize=(9, 6))
sns.heatmap(flights, annot=flightsRoundUp, fmt="", linewidths=.5, ax=ax)

What is the best way to display both flightsRoundUp and flights in all cells? Something like the first manual example above, but for all the cells in a vectorized-like way...

A: Rotail's answer didn't work for me, I got an error when applying that lambda function.
However, I found a solution that exploits the fact that seaborn plots sequential figures on top of each other. All you have to do is use one call to heatmap to establish the figure, and then a subsequent call for each of the annotations. Use the annot_kws arg to make sure the text aren't written over eachother.
X = pd.DataFrame({'a':[1, 2, 3], 'b':[4, 5, 6]})
Y = pd.DataFrame({'A':['A', 'B', 'C'], 'B':['E', 'F', 'G']})
Z = pd.DataFrame({'A':['(Extra Stuff)', '(Extra Stuff)', '(Extra Stuff)'], 'B':['(Extra Stuff)', '(Extra Stuff)', '(Extra Stuff)']})

sns.heatmap(X, annot=False)
sns.heatmap(X, annot=Y, annot_kws={'va':'bottom'}, fmt="", cbar=False)
sns.heatmap(X, annot=Z, annot_kws={'va':'top'}, fmt="", cbar=False)

A: Following works for me too:
X = pd.DataFrame({'a':[1, 2, np.nan], 'b':[10, 20, 30]})
Y = pd.DataFrame({'A':[11, 222, np.nan], 'B':[110, np.nan, 330]})

# convert to string
X_value_ann = (X).astype('|S5').reset_index()
Y_value_ann = (Y).astype('|S5').reset_index()

# define () and new line to glue on later
br = np.char.array(pd.DataFrame('\n(', index=X_value_ann.index, columns=X_value_ann.columns))
cl = np.char.array(pd.DataFrame(')', index=X_value_ann.index, columns=X_value_ann.columns))

# convert to chararray
X_value_ann = np.char.array(X_value_ann)
Y_value_ann = np.char.array(Y_value_ann)

# glue and reshape
my_annotation = pd.DataFrame(X_value_ann+br+Y_value_ann+cl)
my_annotation = my_annotation.applymap(lambda x: x.decode('utf-8'))
my_annotation = my_annotation.drop(columns=[0])
my_annotation

A: you should be able to set fmt="" and format you labels with appropriate "\n" to have multiple lines of annotations.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

np.random.seed(0)
sns.set_theme()
uniform_data = np.random.rand(4, 4)
fig,ax = plt.subplots(figsize=(50,20))

uniform_data_labels = \[\]
for i in uniform_data:
    tmp_arr=\[\]
    for j in i:
        tmp_arr.append('Example\nExample')
    uniform_data_labels.append(tmp_arr)

sns.heatmap(uniform_data, vmin=0, vmax=1, annot=uniform_data_labels ,ax=ax,fmt="",annot_kws={"fontsize":30})
plt.show()

1


text:
Q: Xcode, create two the same MyMoviePlayerController in two ViewController I have a ViewController:
ReadViewController.h
ReadViewController.m

And I have a MPMoviePlayerController inside ReadViewController:
ReadViewController.h
@interface ReadViewController : UIViewController
@property (nonatomic, strong) MyMoviePlayerController   *myPlayView;
@end

ReadViewController.m

- (void)viewDidLoad
{
   .....
   .....
   .....
   [self.view addSubview:self.myPlayView.view];
}

I created two objects of ReadViewController which one is small size used for "preview" and another is Screen Size.
I put the two ViewControllers in two place:
ReadViewController *bigSizeReadViewController = [[ReadViewController alloc] init];
//put bigSizeReadViewController inside an UITabBarController

.....
ReadViewController *smallSizeReadViewController = [[ReadViewController alloc] init];
smallSizeReadViewController.view.frame = CGRectMake(200, 300, 400, 600);
[......  addSubView:smallSizeReadViewController.view];

I put the two ViewControllers in two place.
When I run this on IPAD Simulator,  self.myPlayView inside small size's ReadViewController can be played normally.
But self.myPlayView inside big size's ReadViewController can not be played normally and show black screen.
Could anyone help me with this issue?
Sorry for my bad English.

A: You have to initialize and setup each of the myPlayView properties separately, and start playing them each individually.
There will be no guarantees that they will be synchronized as they are independent AVPLayer objects.  You;ll have to write the extra code to keep them in sync.


text:
Q: Type '(s: string) => string' is not assignable to type '(t: T) => T' I declared a Typescript interface like so:
interface ProductFieldMapping {
  name: string,
  mapping: (p: Product) => string | number,
  formatting: <T>(t: T) => T,
}

And a function that returns a list of such fields like so:
export const mappingFunctions = (host: string): ProductFieldMapping[] => {
  const mappings = defaultFunctions(host)

  return [
    {
      name: 'title',
      mapping: mappings.productName,
      formatting: (s: string) => s,
    },
  ]
}

But I get this error when I want to assign to formatting this simple function (s: string) => s
Type '(s: string) => string' is not assignable to type '<T>(t: T) =>
T'.

What am I missing?
Possible fix:
type MappingResult = | string | number

interface ProductFieldMapping<T> {
  name: string,
  mapping: (p: Product) => T,
  formatting: (t: T) => T,
}

export const mappingFunctions = (host: string): ProductFieldMapping<MappingResult>[] => {
  const mappings = defaultFunctions(host)

  return [
    {
      name: 'title',
      mapping: mappings.productName,
      formatting: compose([limitSize(255), replaceNewLine(' ')]),
    }]
}

A: You need to give the type when you invoke the function.
In your case, you should replace string with T.
Because you just assign the function, not invoke it.
formatting: <T>(s: T) => s,

Then while you are invoking the function, then you give a type to your function.
formatting<string>("1") // it doesn't throw error
formatting<number>(1) // it doesn't throw error

EDIT
I saw documentation has a chapter about Generic Classes.
There is same way which VLAZ did, but documentation used classes.
class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

let myGenericString = new GenericNumber<string>();
myGenericString.zeroValue = "0";
myGenericString.add = function(x, y) {
    return x + y.toLocaleLowerCase(); // it works
};

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) {
    return Math.round(y) // it works
};

A: You can tighten up your types by using a discriminated union (also see here) for your possible ProductFieldMappings.
A discriminated union is where you have a union over multiple types but can use a property on them to narrow down the type.
interface ProductFieldMapping<T> {
  name: keyof Product,
  mapping: (p: Product) => T,
  formatting: (t: T) => T,
}

interface StringFieldMapping extends ProductFieldMapping<string> {
    type: "string";
}

interface NumberFieldMapping extends ProductFieldMapping<number> {
    type: "number";
}

type Mapping = StringFieldMapping | NumberFieldMapping;

This makes the ProductFieldMapping a generic interface where the result of mapping and formatting are tied together and must use the same format. Since we only have two formats, we make one type for each - StringFieldMapping and NumberFieldMapping. Each of these has a distinct type and thus Mapping is now a discriminated union.
From here you can produce an array of Mappings and you'll know they work with the correct data:
const numFormat = (n: number) => Math.round(n);
const strFormat = (s: string) => s.toLowerCase();

export const mappingFunctions = (host: string): Mapping[] => {
  const mappings = defaultFunctions(host);

  return [
    {                                   // OK
      name: 'title',
      type: "string",                   // it's a string
      mapping: mappings.productName,    // produces string ✔
      formatting: strFormat,            // consumes string ✔
    },
    {                                   // OK
      name: 'price',
      type: "number",                   // it's a number
      mapping: mappings.price,          // produces number ✔
      formatting: numFormat,            // consumes number ✔
    },
    {                                   // ERROR
      name: 'a',
      type: "string",                   // it's a string
      mapping: mappings.productName,    // produces string ✔
      formatting: numFormat,            // consumes number ❌
    },
    {                                   // ERROR
      name: 'b',
      type: "number",                   // it's a number
      mapping: mappings.price,          // produces number ✔
      formatting: strFormat,            // consumes string ❌
    },
    {                                   // ERROR
      name: 'c',
      type: "string",                   // it's a string
      mapping: (p: Product) => 42,      // produces number ❌
      formatting: strFormat,            // consumes string ✔
    },
    {                                   // ERROR
      name: 'd',
      type: "number",                   // it's a number
      mapping: (p: Product) => "hello", // produces string ❌
      formatting: numFormat,            // consumes number ✔
    },
  ]
}

Playground Link


text:
Q: Python script sorted csv files exported empty My current csv file
Client.csv:
RecNo,AdultNo,NoChild,ClientName,CAT
1,1,5,Fred Flintstone,0
2,10,2,Georia OKeefe,5
3,2,4,Joe BLow,6
4,2,5,Cher,0

Output desired is group by NoChild, then sort ascending by ClientName then export groups to separate csv files.
Thus for the Client.csv file I would have
1.csv - empty
2.csv
2,10,2,Georia OKeefe,5
3.csv - empty
4.csv
3,2,4,Joe BLow,6
5.csv
4,2,5,Cher,0
1,1,5,Fred Flintstone,0
I get all 5 csv files, but their empty. What am I missing?
Below is my Python 2.7 code:
import csv

counter = ("1","2","3","4","5")
for variablefile  in counter:
    inputCSVFile = "C:\\Test\\Client.csv"
    variable_CSV = "C:\\Test\\" + variablefile + ".csv"

    with open(variable_CSV , 'wb') as f:
        with open(inputCSVFile) as test:
            reader = csv.DictReader(test)
            for row in reader:
                mylist = tuple([row["NoChild"] for row in reader])
                print mylist
                if mylist == variablefile:
                    print mylist
                    f.write((sorted("ClientName")) + '\n')
                else:
                    exit

I've been hacking away at various syntax's but get the same results. What am I missing here? Please provide code suggestions if you have solution. I'm stumped.

A: I doubt that mylist == variablefile ever returns True since mylist is a tuple and variablefile is a string as far as I can tell.
This also explains why you don't get a TypeError when you try add a list to a string:
(sorted("ClientName")) + '\n'

And, sorted("ClientName") will return
['C', 'N', 'a', 'e', 'e', 'i', 'l', 'm', 'n', 't']

which probably isn't what you meant either ...


text:
Q: many controller for state in ui-router how to add many controller for state in ui-router ?
I have searched long and hard but found nothing that helped yet. Where I wrong? I really do not know what to do. I wrote all the details below. I've tried and did not succeed.
angular.module('uiRouterApp.typeNews', [
        'uiRouterApp.typeNews.Service',
        'ui.router'
    ])
    .config(
        [
            '$stateProvider', '$urlRouterProvider',
            function($stateProvider, $urlRouterProvider) {
                $stateProvider
                    .state('detail', {
                        url: '/typeNews/detail/typeNewsId=:typeNewsId',
                        templateUrl: '/Scripts/ui-route/typeNews/typeNews.detail.html',
                        controller: [
                            '$scope', '$stateParams', '$state', 'typeNewsService',
                            function($scope, $stateParams, $state, typeNewsService) {
                                typeNewsService.readTypeNews($stateParams.typeNewsId)
                                    .success(function(data, status, headers, config) {
                                        $scope.typeNews = data;
                                    });
                            }
                        ]
                    })
                    .state('typeNews', {
                        url: '/typeNews/PageSize=:PageSize/PageIndex=:PageIndex',
                        templateUrl: '/Scripts/ui-route/typeNews/typeNews.html',
                        controller: 'pagerCtrl'// need two many controller like controller: 'pagerCtrl' , 'gridCtrl'
                    });
            }
        ]
    );

A: Every state in your state provider maps to a single controller.
Having multiple (many) controllers handling one state is not possible and goes against the basic concept of the framework.
I don't understand what you want to achieve with multiple controllers in one state.
What is your idea and how should this function? Can you explain?
You can have parent and child states and they can have their own controllers. Maybe that is what could help you out.

A: Based on your comment:

controller: 'pagerCtrl'// need two many controller like controller: 'pagerCtrl' , 'gridCtrl'

I think you want controllers for ui elements.  You probably want to use or create a Directive.  Have a look at ngTable and ng-Grid for example.

A: Yes u will need this if u reference some other controllers info....just add one controller to the state and the other one u can nest it as a ng-controller in the html.
JS snippet
angular.module('xTimeApp').config(function ($stateProvider, $httpProvider) {
$stateProvider.state('editpayhistory', {
      url: '/payhistory/:id/edit',
      templateUrl: '../PayHist/PayHist-edit.html',
      controller: 'PayHistEditController'  //<-Controller 1
  });

HTML snippet:

    Attendance

        <select ng-init="payhist._attend = {AC_CODEID: payhist.AC_CODEID}"
                ng-change="payhist.AC_CODEID = payhist._attend.AC_CODEID"
                ng-model="payhist._attend"
                ng-options="attend.AC_CODEID as attend.AC_NAME for attend in attends track by attend.AC_CODEID"></select>

A: .state('app.somestate', {
    url : '/someurl',
    views:{
        'menuContent': {
            templateUrl: 'part1.html',
            controller: 'ACtrl'
        },
        'otherContent': {
            templateUrl: 'part2.html',
            controller: 'BCtrl'
        },
        'someotherContent': {
            templateUrl: 'part3.html',
            controller: 'CCtrl'
        }
    }
})


text:
Q: jQuery mobile loading script after submitting form to self I am writing a processing script that allows users to enter data in compartments on a form and save each section rather then complete the whole page in one go. It is essentially a sequence of forms within expandable elements within the page. However, Upon submitting any form to itself, the page cannot reload any javascript, In the documentation for jquery mobile it does say this can be problematic but I cant make any of the solutions offered there work.
I've stripped my code down to a very basic skeleton for troubleshooting:

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

<body onload = myFunction("<?php echo $_GET['p']?>")>

Click me - I'm collapsible!

            <form action = "<?php echo $_SERVER['PHP_SELF'] . "?p=1"?>" method="GET">

<input type="submit" id="Button1" name="" value="Save">

            </form>

Click me - I'm collapsible!

I'm the expanded content.

Click me - I'm collapsible!

I'm the expanded content.

Click me - I'm collapsible!

I'm the expanded content.

Click me - I'm collapsible!

I'm the expanded content.

The code is trying to accomplish a simple task. When a form is submitted, send it to itself, where some php script will process the results and the page will then load the updates into the form fields. This all works perfectly, the section that isn't doing what it is supposed to is the myFunction process that should set the active expandable content to the value of content_(what ever number is in $_GET['p']).
I thought having it in body would force its update on page load but jquery mobile acts differently.
I've also tried having the js in a separate .js file loaded in the header to no avail.
I've even tried including all the java script inside a div element  and using that wrapper around all the expandable content elements as the jQuery documentation says (i think) that only div elements are loaded.
when a form is submitted it is processed but no content is auto-expanded. If you manually refresh the page it expands as it should but you shouldn't need to manually refresh the page after clicking save.
ive also tried using

This above will echo the correct value of p, but wont assign an expand to anything. I tried including it before and after the div elements that are expandable.
I'm running out of ideas to try and make it load, am i missing something simple or is there an alternative that I've just not come across yet?

A: Try putting it in your pagecontanershow event and then putting a switch to run script based on the page that is loaded.  Remember that when using AJAX navigation that JQM only loads the body of the second and subsequent pages, JS loaded from the header is only loaded on the first page load so you need to make it all available then.
$(document).on("pagecontainershow", function(event, ui) {

console.log('pagecontainershow::navigating to page ' + ui.toPage.attr('id'));

page_id = ui.toPage.attr('id');

switch (page_id) {
case 'page-id1':
    //some page specific code here
    break;
case 'page-id2':
    //some more here
    break;
}
});

A: Im not sure how technically correct this is, but it works and includes very little alteration.

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

<body onload = myFunction("<?php echo $_POST['p']?>")>

Click me - I'm collapsible!

        <form data-ajax="false" action = "<?php echo $_SERVER['PHP_SELF']?>" method="POST">
            <input type = "hidden" name = "p" value = "1">

<input type="submit" id="Button1" name="" value="Save">

        </form>

Click me - I'm collapsible!

        <form data-ajax="false" action = "<?php echo $_SERVER['PHP_SELF']?>" method="POST">
            <input type = "hidden" name = "p" value = "2">

<input type="submit" id="Button1" name="" value="Save">

        </form>

Click me - I'm collapsible!

        <form data-ajax="false" action = "<?php echo $_SERVER['PHP_SELF']?>" method="POST">
            <input type = "hidden" name = "p" value = "3">

<input type="submit" id="Button1" name="" value="Save">

        </form>

Click me - I'm collapsible!

        <form data-ajax="false" action = "<?php echo $_SERVER['PHP_SELF']?>" method="POST">
            <input type = "hidden" name = "p" value = "4">

<input type="submit" id="Button1" name="" value="Save">

        </form>

Click me - I'm collapsible!

        <form data-ajax="false" action = "<?php echo $_SERVER['PHP_SELF']?>" method="POST">
            <input type = "hidden" name = "p" value = "5">

<input type="submit" id="Button1" name="" value="Save">

        </form>

essentialy I needed to add data-ajax="false" to each form, which from what I gather makes it load the page in full. It will only work with method="POST", but as the code shows, its a minor change.
The code here creates 5 expandable boxes ready for form elements, when the save button is clicked, the form is submitted to itself and the expandable box that sent it is triggered to become expanded and active.
If this will present issues in future please comment about it but otherwise i'm overjoyed it goes round.


text:
Q: How do I know the difference of days, months, and years from a date, can I use subtraction? I'm writing an algorithm where I'm going to get a whole number and with that I want to determine a date to expire a certain content. I'm already getting the date that the content was published.
Example:
publication date: 01/05/2019
days to expire: 30
result of the program: 01/06/2019 // date of expiry of the content
NOTE: The value of "Days to expire" is entered by the user.
How can I solve this? Do you have any documentation or function to help me?

A: There are a handful of ways to accomplish what you're trying to do -- Here are a few possibilities.
Using Time (my recommendation so you have more flexibility later depending on how your needs change and how you end up expiring content):
You can convert the "days to expire" to seconds and then add that to your time object.  For example:
require "time"

t = Time.parse("01/05/2019")
days_to_expire = 30
expiration = t + (60 * 60 * 24 * days_to_expire)

Using Date:
require "date"

d = Date.parse("01/05/2019")
days_to_expire = 30
expiration = d + days_to_expire

Using built-in helpers from Rails Active::Support:
t = Time.parse("01/05/2019")
days_to_expire = 30
expiration = t + days_to_expire.days

You can learn more about Ruby Time here and you can learn about the helpers built-in to Time and Numeric by Rails here and here.

A: I'll answer this assuming the project is in Rails since this question is tagged as a Rails one. You could do something like this:
t = Date.parse("01/05/2019")
days_to_expire = 30   # Obtained from user input in your case
result = t + days_to_expire.days   # Similar to result = t + 30.days

You could check out more about Date in the API docs here


text:
Q: Does the color band on a thermal fuse indicate temperature? I have a thermal fuse that is blown (open circuit.) Any textual markings it might have had are worn away, but I'm wondering if the yellow color on the one end is significant. In looking for possible replacements, I've seen yellow, black, tan, etc., but I have yet to find anything that says anything about what the color means, if anything.
Would this color possibly indicate the temperature at which the fuse blows? More specifically, can I replace a yellow ended one with another yellow ended one and have it work as expected?
The circuit board is from a lighted fiber-optic Christmas tree that uses a 12V halogen bulb, so I would think just about any volt/amp ratings on a thermal fuse would be within tolerance. Just trying to figure out the temperature it was designed for.

A: There does not appear to be a standardized color code. Maybe within individual manufacturers. For example, Cantherm's datasheet for similar products shows multicolored epoxy sealants but does not disclose their coding.
I can easily find clear photos of thermal cutoff with different marked Tf temperatures from 90°C to 100°C with yellow coding.
That said, if it was me, I'd feel fairly confident (given fire extinguisher and insurance situation) in replacing it with a 90°C unit, but not much more- the PCB appears to be FR1 or FR2 paper-based phenolic good for around 100°C depending on grade.
Your choice is up to you- this is a safety-related device so the only 'official' answer can be to replace it with the exact OEM type, and if that is not possible to dispose of the unit properly.


text:
Q: Android: Physical Back button returning to restricted activity I have an admin activity in an app which will allow him or her make changes to certain things. How do I prevent a normal user from pressing the "back" button from entering this activity?

A: You can launch the Activity with the FLAG_ACTIVITY_NO_HISTORY flag and that should keep it out of the backstack.

A: I would recommend putting some kind of user validation in the admin activity, which will disable the normal layout and display some kind of message that tells the user they are not allowed to make changes.


text:
Q: Tensorflow 1.14 can't detect GPU with python 3.6 but see it in Python 2.7 I am trying to work with Mask R-CNN samples to practice detection and segmentation models. I am using python 3.6.8 with Tensorflow and Keras but program model starts training only with CPU and can't detect any GPU. At the same time Python 2.7 can see my GPU as it shown in code below.
I have installed NVidia driver 410, CUDA 10.0, cudnn 7.4.2, tensorflow-gpu==1.14.0 installed with pip and pip3.
To check is GPU available i used small python script:
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

import tensorflow as tf
tf.test.is_gpu_available()

Output for python:
2019-09-16 12:17:21.621640: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-09-16 12:17:21.635692: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcuda.so.1
2019-09-16 12:17:21.720910: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1005] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-09-16 12:17:21.721429: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x558027aed070 executing computations on platform CUDA. Devices:
2019-09-16 12:17:21.721444: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): GeForce GTX 1060 3GB, Compute Capability 6.1
2019-09-16 12:17:21.741624: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3408000000 Hz
2019-09-16 12:17:21.742628: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x558027ba37a0 executing computations on platform Host. Devices:
2019-09-16 12:17:21.742663: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): <undefined>, <undefined>
2019-09-16 12:17:21.742937: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1005] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-09-16 12:17:21.743542: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1640] Found device 0 with properties:
name: GeForce GTX 1060 3GB major: 6 minor: 1 memoryClockRate(GHz): 1.7845
pciBusID: 0000:01:00.0
2019-09-16 12:17:21.743884: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcudart.so.10.0
2019-09-16 12:17:21.745776: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcublas.so.10.0
2019-09-16 12:17:21.747601: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcufft.so.10.0
2019-09-16 12:17:21.748031: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcurand.so.10.0
2019-09-16 12:17:21.750885: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcusolver.so.10.0
2019-09-16 12:17:21.752588: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcusparse.so.10.0
2019-09-16 12:17:21.757589: I tensorflow/stream_executor/platform/default/dso_loader.cc:42]     Successfully opened dynamic library libcudnn.so.7
2019-09-16 12:17:21.757765: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1005] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-09-16 12:17:21.758440: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1005] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-09-16 12:17:21.759102: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1763] Adding visible gpu devices: 0
2019-09-16 12:17:21.759173: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcudart.so.10.0
2019-09-16 12:17:21.760528: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1181] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-09-16 12:17:21.760553: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1187]      0
2019-09-16 12:17:21.760564: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1200] 0:   N
2019-09-16 12:17:21.760807: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1005] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-09-16 12:17:21.761483: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1005] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-09-16 12:17:21.762083: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1326] Created TensorFlow device (/device:GPU:0 with 2287 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1060 3GB, pci bus id: 0000:01:00.0, compute capability: 6.1)
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 13231116977719504797
, name: "/device:XLA_GPU:0"
device_type: "XLA_GPU"
memory_limit: 17179869184
locality {
}
incarnation: 2220022223072533235
physical_device_desc: "device: XLA_GPU device"
, name: "/device:XLA_CPU:0"
device_type: "XLA_CPU"
memory_limit: 17179869184
locality {
}
incarnation: 579036656168733531
physical_device_desc: "device: XLA_CPU device"
, name: "/device:GPU:0"
device_type: "GPU"
memory_limit: 2398158848
locality {
  bus_id: 1
  links {
  }
}
incarnation: 14902085726432239020
physical_device_desc: "device: 0, name: GeForce GTX 1060 3GB, pci bus id: 0000:01:00.0, compute capability: 6.1"
]

Output for python3:
WARNING: Logging before flag parsing goes to stderr.
W0916 12:10:46.067314 140410557671232 __init__.py:308] Limited tf.compat.v2.summary API due to missing TensorBoard installation.
2019-09-16 12:10:46.084425: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-09-16 12:10:46.113540: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3408000000 Hz
2019-09-16 12:10:46.114038: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x495fd00 executing computations on platform Host. Devices:
2019-09-16 12:10:46.114054: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): <undefined>, <undefined>
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 5355211451834126024
, name: "/device:XLA_CPU:0"
device_type: "XLA_CPU"
memory_limit: 17179869184
locality {
}
incarnation: 8307771055363446310
physical_device_desc: "device: XLA_CPU device"
]

Where did I make mistake and how to fix this issue and detect GPU for Python3?


text:
Q: knockout update observable collection from property on viewmodel I'm using knockout to create a basic AJAX shopping cart for a project and the cost of the individual products that are contained in an observable collection inside the view model need to update when a property on the view model is updated. I've been trying various solutions for many hours and I hope somebody can point me in the right direction. I've included a jsfiddle.
http://jsfiddle.net/g8BLj/3/
var product = function (title, operationName, description, parent) {
  this.title = title;
  this.operationName = operationName;
  this.description = description;
  this.cost = 9;
  this.count = ko.observable(parent.recordCount);
  this.subtotal = ko.computed(function () {
    return this.count * this.cost;
  }).bind(this);
};

order = function () {
 var listName = ko.observable("not defined"),
     listId = ko.observable("not defined"),
     recordCount = ko.observable("not defined"),
     products = [
     new product('Product1', 'EMAIL_VER_DELIVERABLE', 'Description.', this),
     new product('Product2', 'EMAIL_BASIC_NO_SUPRESSION_W_VERIFICATION', 'Description.', this),
     new product('Product3', 'PHONE_PREM', 'Description.', this)],
     total = function () {
        var total = 0;
        $.each(this.products(), function () {
            total += this.subtotal();
        });
        return total;
     };

 // anything in the return block is considered public, anything above is private
 return {
    listName: listName,
    listId: listId,
    recordCount: recordCount,
    products: products,
    total: total
 };
}();

ko.applyBindings(order);

// when this value changes the product Cost needs to be updated
order.listName('test list')
order.listId(1)
order.recordCount(100)

Thanks,
Chris

A: I think, the most important thing to solve this problem, is to use subscription to order.recordCount changes instead of sending order as parameter to product.
You can write something like this:
recordCount.subscribe(function (newValue) {
    ko.utils.arrayForEach(products, function (product) {
        product.count(newValue);
    })
});

Also, you should change product.subtotal calculation:
this.subtotal = ko.computed(function () {
    return this.count() * this.cost;
}, this);

A: There are a couple of issues with the "this" scope which are causing problems.
this.subtotal = ko.computed(function () {
  return this.count * this.cost;
}).bind(this);

The correct way to get the ambient this scope correct is to pass "this" into the ko.computed as a second argument.  Also, count is an observable to you need to evaluate it.
this.subtotal = ko.computed(function () {
  return this.count() * this.cost;
}, this);

The products variable is passing "this" into the constructor of product.  The ambient this at this point is window, as are you are using anonymous function/revealing module pattern.
So when
 this.count = ko.observable(parent.recordCount);

evaluates, parent is window, so recordCount == undefined.
If you want to continue to use the revealing module pattern you need to tweek the order function to declare your return object ("obj") and then create the products.
You should also declare the total property as a ko.computed.  I have used map/reduce instead of $.each but that is personal preference.
When this is done, it reveals a further issues with the count property on the product class.  The parent.recordCount is an observable, so you are creating an observable where its value is an observable, not the value of the observable.  Just assign the observable to a count property.

var product = function (title, operationName, description, parent) {
    this.title = title;
    this.operationName = operationName;
    this.description = description;
    this.cost = 9;
    this.count = parent.recordCount;
    this.subtotal = ko.computed(function () {
        return this.count() * this.cost;
    }, this);
};

order = function () {
    var
    listName = ko.observable("not defined"),
        listId = ko.observable("not defined"),
        recordCount = ko.observable("not defined"),
        products = [];

    var obj = {
        listName: listName,
        listId: listId,
        recordCount: recordCount,
        products: products
    }

    // now we have an object to push into the product class
    products.push(
        new product('Product1', 'EMAIL_VER_DELIVERABLE', 'Description.', obj),
        new product('Product2', 'EMAIL_BASIC_NO_SUPRESSION_W_VERIFICATION', 'Description.', obj),
        new product('Product3', 'PHONE_PREM', 'Description.', obj)
        );

    obj.total = ko.computed( function() {
        return this.products
            .map(function(item) { return item.subtotal(); })
            .reduce( function(runningTotal, subtotal) { return runningTotal + subtotal;
        }, 0);
    }, obj);

    // anything in the return block is considered public, anything above is private
    return obj;
}();

ko.applyBindings(order);

// when this value changes the product Cost needs to be updated
order.listId(1);
order.listName('test list');
order.recordCount(100);


text:
Q: How to represent the linear transformation $T:X \to AX$ as a matrix? Let $A$ and $X$ be $n \times n$ real matrices. How do you express the linear transformation $T:X \to AX$ as a linear transformation over the $n^2$ bases vectors of $\mathbb{R}^{n \times n}$? Specifically, how does one compute the matrix representation of $T$?

A: I started writing this before I realized how long it would be (lol).
The standard basis for the space of matrices consists of $E_{ij}$ where the entry in the $i$-th row and $j$-th column is $1$ and all other entries are $0$. Now its easy to verify that $AE_{ij}$ is the matrix whose $j$-th column is is the $i$-th column of $A$. Thus, if we write the entries of $A$ as $a_{pq}$,
$$AE_{i,j}=a_{1,i}E_{1,j}+a_{2,i}E_{2,j}+\cdots+a_{n,i}E_{n,j}=\sum_{p=1}^na_{pi}E_{p,j}$$.
Now if we order the basis according to the entries starting at $1,1$ and going top-down and left-right, we get $E_{1,1},E_{2,1},\ldots,E_{n,1},E_{1,2},\ldots,E_{n,2},\ldots, E_{1,n},\ldots,E_{n,n}$. Then the first column (representing $AE_{1,1}$) will contain the first column of $A$ in the first $n$ positions. The second column (representing $AE_{2,1}$ will have the second column of $A$ in the first $n$ positions, etc. Continuing in this fashion, we see that the matrix will be a block diagonal $n^2\times n^2$ matrix whose $n\times n$ blocks are simply $A$.

As a check, let
$$A=\begin{pmatrix}1&2\\3&4\end{pmatrix}.$$
Our basis is then
$$E_{11}=\begin{pmatrix}1&0\\0&0\end{pmatrix},\quad E_{21}=\begin{pmatrix}0&0\\1&0\end{pmatrix},\quad E_{12}=\begin{pmatrix}0&1\\0&0\end{pmatrix},\quad E_{22}=\begin{pmatrix}0&0\\0&1\end{pmatrix}.$$
We compute
$$AE_{11}=\begin{pmatrix}1&0\\3&0\end{pmatrix},\quad AE_{21}=\begin{pmatrix}2&0\\4&0\end{pmatrix},\quad AE_{12}=\begin{pmatrix}0&1\\0&3\end{pmatrix},\quad AE_{22}=\begin{pmatrix}0&2\\0&4\end{pmatrix}$$
and writing these as row vectors in our ordered basis
\begin{align}
AE_{11}&=E_{11}+3E_{21}=(1,3,0,0)\\
AE_{21}&=2E_{11}+4E_{21}=(2,4,0,0)\\
AE_{12}&=E_{12}+3E_{22}=(0,0,1,3)\\
AE_{22}&=2E_{12}+4E_{22}=(0,0,2,4).
\end{align}
The matrix for multiplication by $A$ is then
$$\begin{pmatrix}
1 & 2 & 0 & 0\\
3 & 4 & 0 & 0\\
0 & 0 & 1 & 2\\
0 & 0 & 3 & 4
\end{pmatrix}.$$

A: This is a nasty thing to do, but in the end, the matrices $X$ and $AX$ are simply vectors from $T$'s point of view. How you arrange the $n^2$ entries as a vector is up to you. It might be easier to list the action of $T$ on the basis matrices $(e_{ij})$ with a $1$ at position $(i,j)$ and $0$ elswhere.

A: It's not too difficult to write out the matrix for $T$, once you choose some nice notation. Let $E^{ij}$ denote the matrix with a 1 in the $(i, j)$ position and zeros elsewhere, which multiply like $E^{ij} E^{kl} = \delta_{jk} E^{il}$. These form a basis for the vector space $\operatorname{Mat}_n (\mathbb{R})$, so we should be able to write any linear operator $T \colon \operatorname{Mat}_n (\mathbb{R}) \to \operatorname{Mat}_n (\mathbb{R})$ down using this basis in the usual way: the matrix components $T_{ij, kl}$ are defined by the equation
$$ T(E^{kl}) = \sum_{i, j} T_{ij, kl} E^{ij}. $$
Now, for any matrix $A$ in $\operatorname{Mat}_n (\mathbb{R})$, let $[A]_{(i, j)} \in \mathbb{R}$ be the scalar in the $(i, j)$ place of the matrix. (I've used this weird notation to distinguish between the two different "levels" of matrices going on here). The defining equation above is saying that
$$ \left[ T(E^{kl}) \right]_{(i, j)} = T_{ij, kl},$$
or in other words, the "meta-matrix" entry $T_{ij, kl}$ is whatever is in the $(i, j)$ spot of the matrix $T(E^{kl}) \in \operatorname{Mat}_n(\mathbb{R})$. Understanding the distinction between these two levels of matrix is essentially the whole problem.
Now fix a matrix $A \in \operatorname{Mat}_n(\mathbb{R})$ and define $T(X) = AX$. We can now write out what $T_{ij, kl}$ is using the definition of matrix multiplication:
$$ \begin{aligned}
T_{ij, kl}
  &= \left[T(E^{kl})\right]_{(i, j)} && \text{by discussion above} \\
  &= \left[A E^{kl}\right]_{(i, j)} && \text{by definition of } T\\
  &= \sum_{m} [A]_{(i, m)} \left[E^{kl}\right]_{(m, j)} && \text{by definition of matrix multiplication} \\
  &= [A]_{(i, k)} \delta_{lj} && \text{since } [E^{kl}]_{(m, j)} \text{ is 1 when } k = m \text{ and } l = j \text{, else } 0.
\end{aligned} $$
Therefore we can see that the matrix of $T$ is
$$T_{ix, ky} = \begin{cases} [A]_{(i, k)} & \text{if } x = y, \\ 0  & \text{otherwise.} \end{cases} $$

Can we get this result more quickly and less formally? Notice that $A E^{kl}$ is a matrix with a single nonzero column $l$, and that column is equal to the $k$th column of $A$. Written in equations this is
$$ T(E^{kl}) = A E^{kl} = \sum_i [A]_{(i, k)} E^{il}, $$
Showing that $T_{il, kl} = [A]_{(i, k)}$, and that $T_{ij, kl} = 0$ when $j \neq l$, the same result as before.


text:
Q: Configuring a program to run as a service I have just purchased a HP Color LaserJet CM2320fxi MRP combined printer/scanner/fax. I have installed the software on a Windows Server 2003 machine. However when I log out of the server and try to scan using the machine I get a connection error, as far as I can see this is due to the requirement for HP Toolbox FX to be running when the scanner is being used.
Does anyone know of a way to get HP Toolbox FX to run all the time, like making it run as a service. I want users to just press a few buttons on the machine and their scans appear on the network shares, not have to log on to a computer and access special software.
Anyone able to help or give me any ideas on this?
Thanks

A: Have you had a look at FireDaemon?
You can also have a go at doing this yourself with Srvany.exe and Instsrv.exe as per How To Run Automation Manager as a Windows NT Service - KB193238 - I think this still appiles to W2K3.

A: You can add it to the startup folder


text:
Q: Ajax is not sending POST data I'm making a registration form where the script is executed in a seperate file that is used thru AJAX.
I have tried using the script directly by doing <form action="assets/php/action.php?action=register method="post" id="registration-form"> And it works that way however I would like to use AJAX to do this.
The problem with that is that if I use AJAX the POST data is not sent to the action.php file.
I have tried debugging my code but I cannot find what is causing the issue.
My registration form:
<form action="#" method="POST" class="user" id="register-form">

                                        <input type="text" name="name" id="name" class="form-control form-control-user"
                                            placeholder="Name" required>

                                    <input type="email" class="form-control form-control-user" id="remail" name="email"
                                        placeholder="Email Address" required>

                                        <input type="password" class="form-control form-control-user"
                                            id="rpassword" name="password" placeholder="Password" required minlength="8">

                                        <input type="password" class="form-control form-control-user"
                                            id="cpassword" name="cpassword" placeholder="Repeat Password" required minlength="8">

                                <input type="submit" value="Register Account" id="register-btn" name="register" class="btn btn-primary btn-user btn-block">

                            </form>

My AJAX script: (Sorry about the comments that are not in English)

My action.php file:
<?php

session_start();
require_once 'auth.php';
$user = new Auth();

if(isset($_POST['action'])) {
        if($_POST['action'] == 'register') {
        $name = $user->test_input($_POST['name']);
        $email = $user->test_input($_POST['email']);
        $pass = $user->test_input($_POST['password']);

        $hpass = password_hash($pass, PASSWORD_DEFAULT);

        echo $name;
        echo $email;
        echo $pass;
        if($user->user_exist($email)) { //Kontrollib kas selle meiliaadressiga on konto juba registreeritud, kui on siis
            echo $user->showMessage('warning', 'This email is already registered'); //Saadab inimesele kirja, et selle emailiga on konto juba registeeritud, 'warning' tähendab teate tüüpi, teine tekst on kiri, mida saadab
        } else { //Kui selle meiliaadressiga pole kasutajat veel registeeritud, siis
            if($user->register($name, $email, $hpass)) {
                echo 'register';
                $_SESSION['user'] = $email;
            } else {
                echo $user->showMessage('danger', 'Something went wrong! Please try again later or contact support.');
            }
        }
        print_r($_POST); //This only outputs that the action is register, no POST values are outputted
        die();
    }
}
?>

Thanks,
Nimetu.

A: Don't use AJAX. Use fetch instead, you don't need external libraries like jQuery and more efficient. This is an example:
fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

More information here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


text:
Q: Can we use PWM on the cheap RX{n}[letter]-TX{n}[letter] Integrated Circuits The market has been inundated with cheap RC toys. Most of them use the RX/TX Integrated Circuits that have 5 to 9 functions:

*

*PT0090 Series Datasheet

*RX2/TX2 Datasheet
All of them operate on an ON/OFF state.
Has anyone tried to feed a PWM signal to these and see if they have enough frequency output on the Receiving end?

A: The second of those datasheets talks about using a 1khz PWM signal internally for communicating, so I suspect transmitting PWM through them will not work.


text:
Q: Do I need to release CFError? In Core Foundation, when I call a function with a CFError pointer, am I responsible to release that error afterwards? For example:
CFErrorRef error = NULL;
BOOL success = ABRecordSetValue(record, property, value, &error);
if (!success) {
    // handle error
    CFRelease(error);
}

I think I remember reading somewhere that this just magically works without the release, but can't find anything to verify that.

A: In CoreFoundation, if you get stuff back using a pointer, that's likely to have been allocated using one of the ...Create() functions (doesn't the documentation say anything about this?), so you do have to release it.
In Foundation, the "returned" values are autoreleased, so there you don't need to (and in fact should not) do this.


text:
Q: Which signal (like SIGINT or SIGTERM) can a process get when system is going to reboot? My application needs to do something before exit, I have already handled the ctrl-c case by handling signal of SIGINT, but I'd also like to handle the case when the system is going to reboot.
I researched a bit but found that SIGTERM is by administrative operation and system will not send SIGTERM before reboot, is it correct?
Any other signal that I can handle?
Edit:
If my application is run by systemd, does it make it more complicated or easier to handle?

A: The signals sent are customizable and that is documented in man systemd.kill.  The most interesting parts are:
       KillSignal=
           Specifies which signal to use when stopping a service. This
           controls the signal that is sent as first step of shutting down a
           unit (see above), and is usually followed by SIGKILL (see above
           and below). For a list of valid signals, see signal(7). Defaults
           to SIGTERM.

           Note that, right after sending the signal specified in this
           setting, systemd will always send SIGCONT, to ensure that even
           suspended tasks can be terminated cleanly.

       FinalKillSignal=
           Specifies which signal to send to remaining processes after a
           timeout if SendSIGKILL= is enabled. The signal configured here
           should be one that is not typically caught and processed by
           services (SIGTERM is not suitable). Developers can find it useful
           to use this to generate a coredump to troubleshoot why a service
           did not terminate upon receiving the initial SIGTERM signal. This
           can be achieved by configuring LimitCORE= and setting
           FinalKillSignal= to either SIGQUIT or SIGABRT. Defaults to
           SIGKILL.

So when you systemctl stop *.service,  systemd will send a SIGTERM by default to the main process in the service.  If the process doesn't exit within TimeoutStopSec (default 90s), then systemd will follow up with a SIGKILL.
When you are developing your application, you don't need to be too considerate about the init system.  If you don't want to code a response to SIGTERM, and want to simply keep SIGINT, you can.  You just need to ensure any systemd service files you ship contain KillSignal=SIGINT.
I have not read anything to suggest systemd skips KillSignal= upon a reboot. If you ever see "Waiting for ..." when shutting down, that's systemd waiting for things to respond to KillSignal.

A: To my knowledge, all init systems implement more or less the same behavior. Which is, they send SIGTERM and wait for some amount of time and if the process does not terminate gracefully, they send a SIGKILL. I believe systemd works the same way. I could be wrong tho. The best way to know for sure is to test it.
I would recommend reading the description of the various signals and what do they mean and make your application react to them accordingly.
If your application is supposed to run as a long-lasting process, you should consider creating a systemd unit for it. This way, you will be able to control exactly what systemd should do with it when the system is shutting down.