text:
Q: Python: Printing figures from file is getting slower and slower I have a large file (~10 GB) which contains t = 1000 (n x n)-matrices where n = 1000. The data file contains float numbers. I wrote a program which prints every matrix as a .png image. The problem is, that it gets slower and slower. The first image needs less than a second to print. Image 350 needs more than 2 minutes! The plot below shows the problem for t = 27 matrices / images.

Here is my code I use. Does someone see why it is getting slower and slower?
import itertools as it
import matplotlib.pyplot as plt
import time

def printImage(M, k):
    fig = plt.imshow(M, interpolation='nearest')
    fig.set_cmap('hot')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(str(k) + '.png', bbox_inches='tight', pad_inches=0, dpi=300)

    plt.ioff()

n = 1000
t = 1000

with open('data', 'r') as f:
    for i in range(t):
        t0 = time.clock()
        try:
            items = [list(map(float, i.split())) for i in it.islice(f, n)]
        except:
            raise
        else:
            printImage(items,i)
        t1 = time.clock()
        print(str(i) + '/' + str(t) + ' ' + str(t1-t0))

A: The issue is probably because you're not closing your figures, which consumes more and more memory.
Modify your plotting to read
import itertools as it
import matplotlib.pyplot as plt
import time

def printImage(M, k):
    figobj = plt.figure()
    fig = plt.imshow(M, interpolation='nearest')
    fig.set_cmap('hot')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(str(k) + '.png', bbox_inches='tight', pad_inches=0, dpi=300)
    plt.close(figobj)

You probably don't need the call to plt.ioff either.


text:
Q: Vlookup in Pandas I just started leaning python... I have two dataframes the df1 consists of "article number" and "current tier". The df2 consists of "article number" and "updated tier". The rows in both dataframes is not same. I want to the output that shows the "article numbers" where the updated tier is 'different' than current tire
I am trying to use join or merge, could not figure out.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I use a DVI-D dual link cable in place of a USB-C cable? TLDR: Can I solder a DVI-D Dual Link cable to a USB-C receptacle and will it work well?
According to the USB-C cable spec:

Figure 3-21 illustrates an example of USB Full-Featured Type-C cable cross-section, using
micro-coaxial wires for TX/RX pairs. There are four groups of wires: USB D+/D− (typically
unshielded twisted pairs (UTP)), TX/RX signal pairs (coaxial wires, twin-axial or shielded
twisted pairs), sideband signal wires, and power and ground wires .

Also according to the spec, there are 4 pairs of TX/RX signal pairs and 1 pair of UTP wires.
Although I couldn't find the specifications for DVI-D, I could see by looking at the pinout and cutting into one such cable that there are 7 groups of wires wrapped in aluminum foil. Each group contains 3 wires, two twisted signal wires and one drain wire (does this mean shielded twisted pairs?). This, along with the information above, would make me assume that the two cables are compatible, ignoring wire gauge since I couldn't find any such info for DVI.
Assuming I don't plan on using power delivery, can I use a DVI-D cable to transmit USB-C 3.1 data?
Long story:
I have been tasked with building a sort of a kiosk computer whose motherboard is physically separated from the peripherals. One requirement is that it must have a USB-C port, so I need to route a long (~2 meters) cable from the motherboard to the kiosk.
Ideally, I would use something like this USB C header cable from amazon.
Unfortunately, the panel where I have to mount it is so small that I can only fit a USB C female PCB connector soldered to a breakout board. I chose to use an Attend 217B-AG01, since this is what was readily available to me, which I soldered to a small breakout of my making.
The final problem I have is that the panel needs to be removable for maintenance purposes. As such, I can't just solder a cable to the breakout board and call it a day since that would mean I would have to either cut the cable to remove the panel, or to use a longer cable so that I can pull the panel off and have it hanging from the cable.
A better option would be to solder a small cable to the breakout board, which would have another connector on the other end of it. I could just use a simple USB C extension cable and chop off the male end to have it soldered to the breakout board, but I would like the free end to have a more secure connection, such a locking cable with a screw. I know there are USB-C cables with single screw locking plugs, but I just wasn't able to find a matching female receptacle cable. I suspect this is because the expectation is that the plug screws directly into the case/chassis of whatever you are connecting it to.
Alternatively, I could use molex or other kind of connectors with clips. The automotive industry is full of them. Problem is, even though the actual connectors and pins are cheap, the crimp tools I find are extortionately expensive.
This leads me to my question. There is one cable/plug which has enough wires/pins, is still somewhat common, can be found in both female and male variants and has locking screws: the DVI cable.

A: No, as USB and DVI don't use the same characteristic impedance for the cable.


text:
Q: find a file and truncate it I'm simply trying to find a single log file and truncate it. Why won't this work?
find ${listener}/tracefiles/${listener}.log -exec cp /dev/null '{}'\;

This returns an error: find: missing argument to-exec'`

A: It's very simple:
find ${listener}/tracefiles -name ${listener}.log -exec truncate -s0 {} \;

A: That's not working because you need a space before the \;. Try this:
find ${listener}/tracefiles/${listener}.log -exec cp /dev/null '{}' \;

However, that's a needlessly complex way of truncating the file. First of all, since you apparently know the exact path of the file, all you need to do is:
> ${listener}/tracefiles/${listener}.log

If you're using find to avoid creating the file if it doesn't exist, you can try:
[ -e ${listener}/tracefiles/${listener}.log ] && > ${listener}/tracefiles/${listener}.log

If you really need find (if you have more than one file to work on), you can use
find ${listener}/tracefiles/${listener}.log -exec sh -c '> {}' \;

Or even:
find ${listener}/tracefiles/${listener}.log -exec printf '' {} \;

A: There must be whitespace in front of the ;:
find "${listener}/tracefiles/${listener}.log" -exec cp /dev/null {} \;

But it doesn't make any sense to call find -exec for a single file. Why don't you use
test -f "${listener}/tracefiles/${listener}.log" &&
    cp /dev/null "${listener}/tracefiles/${listener}.log"


text:
Q: Powercli Script to measure the count of Host and its Vm's in a each clusters I am trying create a on-liner script which gives an outputs of Hosts and vm's counts in a vcenter cluster like as below.
Cluster:                                                      VMHost                         VM's
Cluster01                                                     04                                  15
cluster02                                                      02                                  35

Just using a sample onliner
Get-VMHost | Select @{N="Cl";E={Get-Cluster -VMHost $_}} Name, @{N="NumVM";E={($_ | Get-VM).Count}} | Sort Cluster, Name

any Ideas?? Thanks in advance
Regards,
Subash.

A: A bit long for a one-liner, but here you go (again?)
get-cluster | select @{n="cluster";e={$_.name}}, @{n="hosts";e={($_ | get-vmhost).count}}, @{n="vms";e={($_ | get-vm).count}} | sort cluster | ft -auto


text:
Q: Algorithm to tell when we've processed a complex variable path expression while parsing? I am working on a compiler for a homemade programming language and I am stuck on how to convert the lexical token stream into a tree of commands for constructing a DOM-like tree. The "tree of commands" will still be a list, essentially emmitting events in a way that describes how to create a tree, from partial information provided by the lexer. (This language is like CoffeeScript in a way, indentation based, or like XML with indentation focus).
I am stuck on how to tell when a variable path has been discovered. A variable path can be simple, or complex, as these examples demonstrate:
foo
foo.bar
foo.bar[baz].hello[and][goodday].there
this[is[even[more.complicated].wouldnt.you[say]]]

They could get more complicated still, if we handled dynamic interpolation of strings, such as:
foo[`bar${x}abc`].baz

But in my simple lang, there are two relevant things, "paths", and "terms". Terms are anything /a-z/ for now, and paths are chaining together and nesting, like the first examples.
For demonstration purposes, everything else is a simple "term" of 1 word, so you might have this:
abc foo.bar[baz].hello[and][goodday].there, one foo.bar

It forms a simple tree.
Right now I have a lexer which spits out the tokens, so basically:
abc
[SPACE]
foo
.
bar
[
baz
]
.
hello
[
and
]
[
goodday
]
.
there
,
[SPACE]
one
[SPACE]
foo
.
bar

That is at least how I broke it up initially.
So given that sequence of strings, how can you generate messages to tell the parser how to build a tree?
term
nest-down
term
period
term
open-square
and
close-square
...

That is the stream of tokens with a name now, but it is not a tree yet. I would like this:
term-start
  term # value: abc
term-end
nest-down
term-path-start
  term-start
    term # value: foo
  term-end
  period
  term-start
    term # value: bar
  term-end
  term-nest-start
    term-start
      term # value: and
    term-and
  term-nest-end
...

I have been struggling with this example for several days now (boiled down from a complex real-world scenario). I cant seem to figure out how to keep track of all the information you need to make a decision on when to say "this structure is done now, close it out" sort of thing. Wondering if you know how to get past this.
Note, I don't need the last tree to actually be a tree structure visually, I just need it to generate those messages which can be interpreted on the other end and used to construct a tree at runtime.

A: There is no way to construct a tree from a list without having the description of the tree in some form. Often, in relation to parsing, the description of this tree is given by a context-free grammar (CFG).
Then you create a parser on the basis of this given CFG. The lexical token stream is given as an input to the parser. The parser organizes the lexical tokens into a tree by using some parsing algorithm.
The parser emits commands for syntax tree construction based on the rules it uses during parsing. On entering into a rule a command "rule X enter" is emitted, on exiting a rule a command "exit X rule" is emitted. When you accept a lexical token then a "token forward" is emitted with its lexeme characters. Some grammars, namely these in ABNF format, support repetitions of elements. Depending from these repetitions the syntax tree might be represented as lists or arrays.
Then a builder module receives this commands and builds a tree, or uses the commands for the specific task with the listener pattern.
I have co-authored (2021) a paper describing a list of commands for building a concrete/abstract syntax trees, depending on CFG's structure, that are used in the parsers generated by parser generator Tunnel Grammar Studio.
The paper is named "Тhe Expressive Power of the Statically Typed Concrete Syntax Trees". It is in an open-access journal (intentionally). The commands are in section "4.3 Syntax Structure Construction Commands". The article is bit "compressed", due to space limitations, and it is not really intended to be a software development guide, but to note the taken approach. It might give you some ideas.
Another co-authored paper of mine, from 2021 named "A Parsing Machine Architecture Encapsulating Different Parsing Approaches" (also in open-access journal) describes a general form of parsing machine and its modules. There Fig.1, p.33, will give you a quick description.
Disclaimer: I have made the parser generator.


text:
Q: How to create centeralized auth server for multiple micro services in docker I am running single django project as a micro service in docker, so i am running mutiple django projects for multiple micro services in docker,  and I am able to setting up auth server (oauth or jwt), user management to each micro service individually.
is this possible to create single auth server(user management, permissions) for multiple micro services in a docker.
If it is possible to create single auth server, then how API's get permissions from the auth server.

A: There are more ways you can do that depending on what you need and how big is the load on your apps. You can create an auth server that your client will call for authentication and your microservices will call it for authorization when a request for a resource is made.
Read this article for a more detailed view in order to see what suits you best.
https://medium.com/tech-tajawal/microservice-authentication-and-authorization-solutions-e0e5e74b248a


text:
Q: Matrix ring $M_2(\mathbb{C})$, $\mathbb{C}^2$ with $M_2(\mathbb{C})$-module structure. Let $R$ be the matrix ring $M_2(\mathbb{C})$. Let $M = \mathbb{C}^2$ with its natural $R$-module structure (just given by the usual action of $2 \times 2$ matrices on $2$-dimensional vectors).
My questions are: is $M$ a projective $R$-module? An injective $R$-module? Is it free?

A: $M_2(\mathbb{C})$ is a semisimple ring, so every module over this ring is projective and injective. Moreover, $\mathbb C^2$ is a simple $M_2(\mathbb{C})$-module, and if it is free it must be isomorphic to $M_2(\mathbb{C})$. In fact, $M_2(\mathbb{C})\simeq \mathbb C^2\oplus\mathbb C^2$, and therefore by taking the ranks we get a contradiction.

A: If $R$ is any ring and $n \geq 1$, then the evident map $M_n(R) \to \bigoplus_{i=1}^{n} R^n$ which decomposes a matrix into its columns is an isomorphism of left $M_n(R)$-modules. Hence, $R^n$ is a projective left $M_n(R)$-module. It is usually not free. If $R$ is commutative and non-zero (more generally, when $R$ has IBN), then free $M_n(R)$-modules of rank $k$ have underlying free $R$-modules of rank $n^2 \cdot k$, but $R^n$ is a free $R$-module of rank $n$, and $n^2 \cdot k = n$ is only solvable in the trivial case $n=1$.
If $R$ is a field, then $R^n$ is an injective left $M_n(R)$-module. One reason for this is that the category of left $M_n(R)$-modules is equivalent to the category of left $R$-modules (i.e. $R$ and $M_n(R)$ are Morita equivalent) and since every left $R$-module is injective, which is a purely categorical notion, the same follows for every left $M_n(R)$-module. Of course, this also shows that every left $M_n(R)$-module is projective.


text:
Q: Disappearing Linked Table I have a problem that arose last week and seems to be spreading. I installed a MS Access database front end on several pcs at a company, that link by ip address to SQL Server backend. This was done over a year ago and has been working perfectly until last week. The frontend accesses the user table in the back end to enable the user to login. It came up on one pc that the user table was not a valid name. When I looked at the database, the linked user table was missing from the linked tables in the front end. I put a fresh copy of the front end on the pc and when you try to login you get the same error and you can actually see the user table disappear from the frontend. If I go to the LTM, to add the table back again, it is not showing in the available tables from the backend. I have tried several times to put a fresh copy on the pc but the same thing happens every time.
Today, 5 computers in the same office have the same problem.
If anyone has any ideas, I would be most grateful.


text:
Q: How can i remove the watches one by one when i fire watch on element for multiple times? I will fire watch multiple times on input field by clicking on start watch.
And now I want to remove the watches one by one on that are present on the input field. How can I do it?

(function(angular) {
  'use strict';
  angular.module('docsBindExample', [])
    .controller('Controller', ['$scope', function($scope) {
      $scope.name = 'Max Karl Ernst Ludwig Planck (April 23, 1858 – October 4, 1947)';

      $scope.test = "";
      $scope.cntr = 0;    /* jsCode igonore other methods*/
      $scope.initWatch = function() {
        $scope.$watch('test', function(newValue, oldValue) {
          if (newValue !== oldValue)
            $scope.cntr++;
        });
      };

    }]);
})(window.angular);
<!doctype html>

  <meta charset="UTF-8">
  <title>Example - example-directive-bind-production</title>

    <input type="text" ng-model="test" />

    <input type="button" value="start watch" ng-click="initWatch()" />

 Watch Counter: {{cntr}}

Content relevant to Named Framework versions 2.0 and greater.

A: Instead of using a watcher, use the ng-change directive:
<input type="text" ng-model="test" ng-change="watch()"/>
<input type="button" value="enable watch" ng-click="enableWatch()" />

Instead of adding and removing a watcher, use an enable flag:
  $scope.enableWatch = function() {
      $scope.enable = ! $scope.enable;
  };
  $scope.watch = function() {
      if ($scope.enable) {
        $scope.cntr++;
      };
  };

The technique of adding and removing watchers creates an implicit state that is difficult to see and difficult to debug. That technique should be avoided. Instead adding a flag creates a state that is readily visible and easily debugged. This follows the design principle of Separation of Concerns where the model is separated from the view and its watchers.
The DEMO

angular.module('docsBindExample', [])
  .controller('Controller', ['$scope', function($scope) {
      $scope.name = 'Max Karl Ernst Ludwig Planck (April 23, 1858 – October 4, 1947)';

      $scope.test = "";
      $scope.cntr = 0;    /* jsCode igonore other methods*/
      $scope.enableWatch = function() {
          $scope.enable = ! $scope.enable;
      };
      $scope.watch = function() {
          if ($scope.enable) {
            $scope.cntr++;
          };
      };

}]);

    <input type="text" ng-model="test" ng-change="watch()"/>

    <input type="button" value="enable watch" ng-click="enableWatch()" />

Watch enabled

    Watch Counter: {{cntr}}

A: I think you can deregister the $watch since it return a deregister function
var listener = $scope.initWatch = function() {
    $scope.$watch('test', function(newValue, oldValue) {
        if (newValue !== oldValue)
            $scope.cntr++;
    });
};

listener(); // clear the watch


text:
Q: Best Way to Select Multiple Records GridView Asp.Net Private Sub GetSelectedBasketRecord()
Dim j As Integer = 0

ViewState("SelectedBasket") = Nothing
For i As Integer = 0 To gvSapBaskets.Rows.Count - 1

    Dim rb As CheckBox = DirectCast(gvSapBaskets.Rows(i).Cells(0).FindControl("CHKButton1"), CheckBox)
    If rb IsNot Nothing Then
        If rb.Checked Then

            Dim hf As HiddenField = DirectCast(gvSapBaskets.Rows(i).Cells(0).FindControl("HiddenFieldBasketID"), HiddenField)
            If hf IsNot Nothing Then
                j = j + 1
                If j = 1 Then
                    ViewState("SelectedBasket") = "PositionID = " & hf.Value & " "
                Else
                    ViewState("SelectedBasket") = ViewState("SelectedBasket") & "AND PositionID = " & hf.Value & " "
                End If
                BasketIDLBL.Text = ViewState("SelectedBasket")
            End If

            If i = gvSapBaskets.Rows.Count - 1 Then
                Exit For
            End If
        End If
    End If

Next
End Sub

I have checkboxes in a gridview,

*

*a user can select multiple check boxes

*Each checkbox has an ID assigned to it

Currently What i was planning to do was create an SQL query to bring back rows depending on what the user selects in the gridview, the viewstate would generate part of the SQL query

*

*if the user selects 1 row: ViewState("SelectedBasket") is PositionID = 1234

*if 2 rows are selected ViewState("SelectedBasket") is PositionID = 1234 AND PositionID = 5678
Then i was going to generate SQL like
"SELECT * FROM TABLE WHERE " & ViewState("SelectedBasket") & "
ViewState("SelectedBasket") would be something like PositionID = 1234 AND PositionID = 5678
I have a feeling there is probably a better way around this, just cannot think of it
Any help is much appreciated!

A: You probably mean OR instead of AND.
But a somewhat briefer approach would be to use IN:
SELECT * FROM TABLE WHERE PositionID IN (1234, 5678)

A: I think this might be what you are looking for:
Private Sub GetSelectedBasketRecord()
  ViewState("SelectedBasket") = ""
  For Each gvRow in gvSapBaskets.Rows
      Dim rb As CheckBox = DirectCast(gvRow.FindControl("CHKButton1"), CheckBox)
      If rb IsNot Nothing Then
          If rb.Checked Then
              Dim hf As HiddenField = DirectCast(gvRow.FindControl("HiddenFieldBasketID"), HiddenField)
              If hf IsNot Nothing Then
                  ViewState("SelectedBasket") &= ViewState("SelectedBasket") & ", "
              End If
          End If
      End If
  Next

  If ViewState("SelectedBasket") <> "" Then
     ViewState("SelectedBasket") = Left(ViewState("SelectedBasket"), LEN(ViewState("SelectedBasket"))-2)
     ViewState("SelectedBasket") = "In (" & ViewState("SelectedBasket") & ")"
  End If
End Sub


text:
Q: Keep selected Annotations with proguard Is it even possible to keep selected Annotations with Proguard?
For instance I would like to remove all annotations from
javax.xml.bind.annotation.*

But keep all from from
org.mycompany.annotations.MyAnnotation

I was trying to tell to Proguard to keep annotetion like below but does not work at all.
-keep @interface org.mycompany.annotations.MyAnnotation

Or should I keepattributes Annotation and then remove somehow rest of not needed annotations?

A: Not sure if I understood completely, generally we retain all annotations by using
-keepattributes *Annotation*,
If you remove this from -keepAttributes list you will lose other annotation too, and code might not work.
Ideally I will play with classes on which annotation is applied , not the annotation itself, for instance if you have annotation MyModelClass which is applied on MyService class
 @ MyModelClass
    public class MyService {
    }

and I want nothing to happen to MyService class, then I will use
-keep @MyModelClass class * {
    <methods>;
    <fields>;
}

As you mentioned you don't need some jaxb annotation, I assume they are compile time annotation.

In case you want to remove all compile time Annnotations and retain runtime annotation probably you should use -keepattributes RuntimeVisibleAnnotations


text:
Q: How to unreverse this method in java? I wrote some code:
public class digitShow {

    public static void main(String[] args) {
        System.out.println(digitShow(98198187));
    }

    public static int digitShow(int num) {
        if (num != 0) {
            System.out.print(num % 10);
            return digitShow(num / 10);
        } else
            return num;
    }
}

The code works perfectly fine, but I am trying to make it so instead of printing the numbers in reverse order one by one, the output rather would display each digit one by one in the order that they are entered in the parameter.
So in this case:
1
2
3
4

I've been trying to un-reverse it, but I've had no luck.

A: Ok, some people on comments are suggesting using arrays or similar. This is correct, however this seems like a question made by someone who is learning recursion (and, as a teacher, I can smell a homework question here).
I will not post the answer because I'd be doing your homework for you and we need good programmers in this world. If I (or anyone else) do your homework you'll never understand the basic concepts of programming, and never becoming a good programmer.
Now, building on top of smac89's comment:
Your code to reverse has an issue: it prints 0 after it reverses the digits. Why? because you are returning an integer and then printing it in your main function but you are not really using the return value anywhere else.
Try calling your method without the System.out.println in main and see what happens.
So, basically, evaluate if you really need to return an integer and, if you don't, you can now evaluate how you are calling the recursion (again, read smac89's comment).
I wish you the best in your studies!

A: You need to reduce the number by successive divisions first.  Then process the values as they are unwound from the stack.  This will print the most significant to least significant digit.  Then return the starting number.
public static int digitShow(int num) {
    if (num > 10) {
        digitShow(num/10);
    }
    System.out.println(num%10);
    return num; // returns the starting number.
}

prints
9
8
1
9
8
1
8
7
98198187


text:
Q: What is the ninja performance gap, why is it so large, and how can we overcome it? According to this abstract:

The "Ninja gap" [...] is the
  performance gap between naively written C/C++ code that is parallelism
  unaware (often serial) and best-optimized code on modern
  multi-/many-core processors.

It appears that they are saying that a programmer who can skilfully handle concurrency can write much more efficient code than a programmer who cannot.  As I am beginning to write multithreaded programs, I am starting to gain an intuition for this myself.
After a reread of the abstract, they appear to argue that applying well known
algorithms can close the gap. I find the question intriguing.
So, in the interest of having this question asked here on Programmers:

*

*What is the "ninja performance gap?" (and were these words chosen well? I think perhaps not.)

*Why is it so large? (Or do we question the size of it? )

*How can it be overcome? (How do we learn to overcome it? Should we learn skillful concurrency or learn algorithms?)

A: What is the "ninja performance gap?"
A naive approach finishing many tasks might be to start one task, wait for it to finish, and only then to start the next task. Suppose one wanted to retrieve many networked resources. The naive approach would be to send a request for the first resource, wait for the request to complete, then send the next.
If a good programmer is skilled at concurrency, such a programmer could write a program that executes many actions at a single time using all the resources of the computer on which it runs (processors, system memory, etc.). Using the network resource example above, the optimal approach would be to attempt to get many resources at the same time.
The gap between the naive approach and the most optimal approach is what these authors (and apparently others) are calling the "ninja performance gap."
Were these words chosen well?
They were likely chosen for promotional and novelty value. As the phenomenon appears to be a very real problem, I would have preferred a term that focused on the problem as opposed to the actors on one side of the gap.
Perhaps "optimized concurrency gap" would have been a better choice in words.
Why is it so large?
The naive approach to solving many problems with computers can be quite inefficient relative to known improvements.
My own experience with Project Euler demonstrated this to me, with some solutions not completing in any reasonable amount of time (minutes, hours), but other solutions to the same problem finishing blazingly fast (within a few seconds).
Bubble sort is known to be quite inefficient relative to other sorting algorithms.
Do we question the size of it?
Based on the above knowledge, I do not question the size as stated.
How can it be overcome?
The naive solution would be for the programmer to study threading and all of the relevant skills to close this gap. Closing the gap in this manner would take a lot of time and effort, both to gain the skills and to write the programs.
How do we learn to overcome it? Should we learn skillful concurrency or learn algorithms?
The paper's abstract states that using better algorithms combined with better compilers can relatively minimize the gap with much less effort required. I am inclined, without direct knowledge, to believe them.

A: Note that the difference is between "naïvely written and parallelism unaware code" and optimised code. Your conclusion that there is a difference in quality between the developers responsible is completely unjustified. Naïvely written and parallelism unaware code is much easier and cheaper to write, and it is much easier and cheaper to make reliable.
At some point (and before we start optimising) a decision has to be made whether optimisation is worthwhile. The code may run 10 times faster, but does this actually result in value that is equal or higher than the cost of the optimisation? Not to everyone, but to the ones paying for the optimisation? That decision will often be that optimisation isn't paying off. In many places, the cost of running unoptimised software is much less than the cost of optimising it.
At home, I often go into "Ninja mode" because it is fun. Improving the speed of code that I've written myself by a factor 10 is usually not a big problem. It has happened that I took handwritten SIMD assembler code and improved it by a factor 10 with C code. However, I haven't encountered a situation in commercial programming in the last years where there was any need for this. (There was an occassional need to replace stupid code with naïve code, which made it ten times faster or more).
For most situations, there is no need for optimisation. There is definitely no need for everyone to be able to write optimised code.

A: If you put the title of the paper into Google Scholar you'll get a link to where IBM hosts the paper: https://software.intel.com/sites/default/files/article/386514/isca-2012-paper.pdf
Or you can use Google directly and get a link to where one of the author's host institution's has a full version of the paper: http://web.eecs.umich.edu/~msmelyan/papers/isca-2012-paper.pdf
The short answer is you'll need to read up on algorithms designed for parallelism (the paper lists a number of them and related techniques), but there is in a nutshell no silver bullet presently available. Techniques that are most commonly used in programming today - default sort methods, access patterns, etc - are not able to take advantage of most performance improvements possible with parallel computation. To take advantage of multiple processors requires learning new techniques, adapting existing tools, and using bench marking to see if what you are doing is working as you expect.

A: The paper refers to maximizing performance from both SIMD and multicore parallelism, along with other techniques such as loop-unrolling and cache performance. So it is not just parallelism alone.
"Ninja" refers to expert programmers. In other words, the "Ninja gap" is the performance difference between a masterpiece and an apprentice's work.
The paper goes on to explain how to incrementally transform (rewrite) an apprentice's work into a masterpiece.
Quoted from the abstract (emphasis mine):

We show how a set of well-known algorithmic changes coupled with advancements in modern compiler technology can bring down the Ninja gap to an average of just 1.3X.

In other words, it is not about using well-known algorithms; it is about applying well-known algorithm refactoring techniques for performance gains.
Some of the algorithm refactoring techniques mentioned in the paper are:
(The paper only mentions the terms without explanation; my explanations might be wrong.)

*

*Cache blocking (when an algorithm iterates through one or more dimensions, introduce intermediate loops into the iteration in order to maximize cache locality (spatial and temporal locality) and therefore cache hit rates)

*Changing memory layouts of data to improve bandwidth and SIMD performance. In particular, switching between AOS and SOA (array-of-structs and structs-of-arrays), alignment of data to cachelines and/or SIMD alignment requirements, etc.

*Switching to alternative algorithms which give equivalent results but are more SIMD friendly.

Note that the paper does not attribute all of the performance gains to the use of these techniques. The authors also experimented with many compiler features such as auto-vectorization (into SIMD code generation), auto-parallelization (over multiple cores), and loop-unrolling.


text:
Q: How to separate out command with its arguments coming in format of string using ruby I have to pass a command with its arguments in a scheduled task, while separating the arguments from the command. I used:
split(/(?=\s-)/)

to do this, but it won't work when the argument is not passed as -arg format.
Example of commands can be passed in format:
"ping http://www.google.com" here url is argument
"abc-abc -V"
"abc-abc -L c:\\folder name\\test.log"
'"C:\\Program Files\\example\\program.exe" -arg1 -arg2'
"C:\\Program Files\\example\\program.exe"

To make this more clear these commands are not passed as command line argument which can get in ARGV
The command gets set in command property which accepts input in string format
command '"C:\\Program Files\\example\\program.exe" -arg1 -arg2'

A: Use Shellwords.split, from the standard library:
Shellwords.split("ping http:\\www.google.com here url is argument")
  #=> ["ping", "http:www.google.com", "here", "url", "is", "argument"]
Shellwords.split("abc-abc -V")
  #=> ["abc-abc", "-V"]
Shellwords.split("abc-abc -L c:\\folder name\\test.log")
  #=> ["abc-abc", "-L", "c:folder", "nametest.log"]
Shellwords.split('"C:\\Program Files\\example\\program.exe" -arg1 -arg2')
  #=> ["C:\\Program Files\\example\\program.exe", "-arg1", "-arg2"]
Shellwords.split('"C:\\Program Files\\example\\program.exe"')
  #=> ["C:\\Program Files\\example\\program.exe"]

No need to reinvent the wheel with a custom regex/splitter, or an external system call.

A: Tom Lord's answer is far better than this one.

You probably want to look at OptionParser or GetOptLong if you need parsing of command line arguments provided to a ruby program.

If you are interested in parsing some strings that may or may not be commands with arguments, here's a quick-and-dirty:
I'd use scan instead of split with the following regex: /(".*"|[\w\:\:\.\-\\]+)/.
Best results come from: 'some string'.scan(/(".*"|[\w\:\:\.\-\\]+)/).flatten:
["ping", "http:\\www.google.com"]
["abc-abc", "-V"]
["abc-abc", "-L", "c:\\folder\\", "name\\test.log"]
# Technically, this is wrong, but so is the non-escaped whitespace.
["\"C:\\Program Files\\example\\program.exe\"", "-arg1", "-arg2"]
["\"C:\\Program Files\\example\\program.exe\""]

A: It seems to me that if there's no consistent pattern to your command syntax, then any regex based approach will inevitably fail. It seems better instead to solve this problem the way a human would, i.e. with some knowledge of context.
In a *nix terminal, you can use the compgen command to list available commands. This Ruby script invokes that command to print the first 5 options from that list:
list = `cd ~ && compgen -c`
list_arr = list.split("\n")
list_arr[0,6].each{|x| puts x }

(The cd in the first line seems to be needed because of the context in which my Ruby is running with rvm.) For Windows, you may find this thread a useful starting point.
I'd match against the elements of this list to identify my commands, and take it from there.


text:
Q: Input.GetKeyDown() не работает Столкнулся с проблемой. Я создавал оружие для персонажа, и решил назначить для этого клавишу, однако свойства, которые я ей задал не работали. Тогда я убрал почти всё и оставил только Debug.Log(), но всё равно ничего не происходит при нажатии на клавишу. Проблема возникает здесь:
private void Update()
{
    if (Input.GetKeyDown(KeyCode.X))
    {
        Debug.Log("x");
    }
}

С чем это может быть связано, и как это решить?

A: Я применил его не к оружию, а к игроку, связав его с оружием через метод.


text:
Q: Reactstrap - collapse Navbar on NavLink click only on mobile I have a Navbar that is open on desktop and collapsed on mobile. I can click a NavbarToggler on mobile to open the Navbar. When I click a NavLink on mobile I want the Navbar to collapse again. I added a onclick() toggle function for the NavLink which works fine on mobile, but now the Navbar on Desktop will collapse and immediately after open again whenever I click a Navlink. Is there a way to always have the Navbar open on Desktop and have it collapse on clicking a NavLink on mobile?
const [isOpen, setIsOpen] = useState(false);
const toggle = () => setIsOpen(!isOpen);

<Navbar color="light" light expand="md">
  <NavbarToggler onClick={toggle} />
  <Collapse isOpen={isOpen} navbar>
    <Nav className="mr-auto" navbar>
      <NavItem>
        <NavLink data-toggle="collapse" onClick={() => {history.push("/"); toggle()}}>Home</NavLink>
      </NavItem>
    </Nav>
  </Collapse>
</Navbar>

A: There are a few ways that this can be accomplished in javascript. You can evaluate the userAgent to check what device the user is using or you can use the viewport / document dimensions as a condition for whether the toggle will fire.
For example:

const [isOpen, setIsOpen] = useState(false);
const toggle = () => setIsOpen(!isOpen);

const mobileToggle = () => {
  if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
   setIsOpen(!isOpen);
  };
};

<Navbar color="light" light expand="md">
  <NavbarToggler onClick={toggle} />
  <Collapse isOpen={isOpen} navbar>
    <Nav className="mr-auto" navbar>
      <NavItem>
        <NavLink data-toggle="collapse" onClick={() => {history.push("/"); mobileToggle()}}>Home</NavLink>            {/* <---- change this to mobileToggle too*/}
      </NavItem>
    </Nav>
  </Collapse>
</Navbar>


text:
Q: Data Mismatch Error in VB.net SQL statement I have this code:
Protected Sub unlikebtn_Click(sender As Object, e As EventArgs) Handles unlikebtn.Click
    Dim strSQL As String
    Dim MemberDataConn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & Server.MapPath("database/Database.mdb"))
    Dim MemberCommand As New OleDbCommand(strSQL, MemberDataConn)
    MemberDataConn.Open()

    MemberCommand.Connection = MemberDataConn
    MemberCommand.CommandText = "DELETE FROM LIKES WHERE  user_id ='" & Session("user_id") & "' AND post_id = '" & Session("post_id") & "'"
    MemberCommand.ExecuteNonQuery()
    MemberDataConn.Close()

    likebtn.Visible = True
    unlikebtn.Visible = False
End Sub

When I run it, I get an error on the .ExecuteNonQuery():

System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.

I don't think the problem is the data-types in the database...

A: It is (almost) always a bad idea to concatenate values into an SQL command. Instead, you should use SQL parameters to pass the values.
Also, instances of some classes, such as an OleDbConnection, use unmanaged resources and you have to tell the .NET Framework to dispose of those resources when you've finished using them. You can either call the .Dispose() method yourself or use the Using construct. The latter is tidier as it will take care of the disposal even if there was a problem.
So your code could look like:
Dim strSQL As String = "DELETE FROM LIKES WHERE user_id = ? AND post_id = ?"

Using conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & Server.MapPath("database/Database.mdb"))
    Using sqlCmd As New OleDbCommand(strSQL, conn)

        'TODO: set the OleDbType to match the columns in the database '
        sqlCmd.Parameters.Add(New OleDbParameter With {
                              .ParameterName = "@UserId",
                              .OleDbType = OleDbType.VarWChar,
                              .Size = 32,
                              .Value = CStr(Session("user_id"))})

        sqlCmd.Parameters.Add(New OleDbParameter With {
                              .ParameterName = "@PostId",
                              .OleDbType = OleDbType.Integer,
                              .Value = CInt(Session("post_id"))})

        conn.Open()
        sqlCmd.ExecuteNonQuery()
        conn.Close()

    End Using
End Using

likebtn.Visible = True
unlikebtn.Visible = False

The ?s in the SQL command are placeholders for the parameters. The parameter names aren't used, but it makes it easier to see what is what in the code. Because the names aren't used, the parameters must be added in the same order as the corresponding placeholders. You will need to adjust the types of the parameters (and the sizes for strings) to match the column types in the database.
Incidentally, if the site is to run under IIS, then you could put the database in the App_Data directory as nothing in there will be served to a client, by default. Also, SQL Server is a more suitable database for a multi-user environment - you can use the Express edition for free.


text:
Q: Java. Get/Set returns null first post and first question.
I am a java beginner so I apologise in advance if my question is very basic, but I have tried for 2 days to find the answer on Internet and on StackOverFlow without success
What I am trying to do: I want to "set" the value of a variable, and then "get" it back multiple other times.
What is happening: the first time that I "get" it, it (correctly) returns the value that I initialized. the following times it returns "null"
Here the code
1) Main class
public class Provasetgetaltraclass {

    public static void main(String[] args) {
        set_e_get_1 set_e_get_1Obj = new set_e_get_1();
        set_e_get_1Obj.execute_var_to_set_e_get1();
        set_e_get_1Obj.execute_var_to_set_e_get2();
    }
}

2) class with the actions
public class set_e_get_1 {

    public void execute_var_to_set_e_get1(){
        var_to_set_e_get var_to_set_e_getObj = new var_to_set_e_get();
        var_to_set_e_getObj.setname("test");
        System.out.println(var_to_set_e_getObj.getname());
    }

    public void execute_var_to_set_e_get2(){
        var_to_set_e_get var_to_set_e_getObj = new var_to_set_e_get();
        System.out.println(var_to_set_e_getObj.getname());
    }
}

3) class with the variable and the set and get methods
public class var_to_set_e_get {
    private String name;

    public void setname (String new_name){
        name = new_name;
    }

    public String getname (){
        return name;
    }
}

4) the result, when I run the main, is
test
null

(what I would like is test and test)
I don't want to store the variable in a database or a file unless necessary, as I'd like to have this working on the fly
If you can help me I'd really appreciate it
Many thanks

A: Your two methods execute_var_to_set_e_get1 and execute_var_to_set_e_get2 each create a different object of var_to_set_e_get class. You set the value of the property only in one of them, so of course it will be null in the other.
If you want the value you stored in the first object to be available in the second method, your first method has to return the object it creates, and the second method should accept that object :
public var_to_set_e_get execute_var_to_set_e_get1(){
    var_to_set_e_get var_to_set_e_getObj = new var_to_set_e_get();
    var_to_set_e_getObj.setname("test");
    System.out.println(var_to_set_e_getObj.getname());
    return var_to_set_e_getObj;
}

public void execute_var_to_set_e_get2(var_to_set_e_get var_to_set_e_getObj){
    System.out.println(var_to_set_e_getObj.getname());
}

public static void main(String[] args) {
    set_e_get_1 obj = new set_e_get_1();
    var_to_set_e_get v = obj.execute_var_to_set_e_get1();
    obj.execute_var_to_set_e_get2(v);
}

A: What happens is that in each call of the methods execute_var_to_set_e_get1 and execute_var_to_set_e_get2 you are creating different objects.
In the first one you are setting name to a String, but in the last, you are not doing that.
So, it will be null (by default).
Note: The behavior that you have described is of a static attribute. If you declase name as static, it will be shared between all the instances.


text:
Q: Is there any other graphic module besides matplotlib for Python? I feel matplotlib is slow, and want to try other light-weight, agile graphic package.I  mainly use plotting for business presentation, not scientific purpose. Any recommendation ?

A: You could try:
http://code.google.com/p/visvis/
http://code.google.com/p/cagraph/
or plplot's python binding ...
If you feel like you don't necessarily need to implement your code in Python, you could try Latex based plotting:
http://www.texample.net/tikz/examples/
http://pgfplots.sourceforge.net/gallery.html

A: There is also Chaco.  It is not lightweight by any means but it is a fair bit faster than matplotlib in my limited tests.
http://code.enthought.com/projects/chaco/
I ended up staying with matplotlib however as it is more popular, so it has better community support for help with questions and such.


text:
Q: extract text without tags with beautifulsoup I want to extract this text

2020; 18 (1) DOI

I can't do it, can anyone help me?
My webpage looks like this:

Medical Device-Related Pressure Injury in health care professionals in times of pandemic
Aline Oliveira Ramalho, Paula de Souza Silva Freitas, Paula Cristina Nogueira
Estima. 2020;18(1) DOI 10.30886/estima.v18.867_IN
Abstract | Full Text
Facing the number of cases of coronavirus infection (COVID-19).

Thank you

A: You can use re and next_sibling.You can try it:
from bs4 import BeautifulSoup
import re
html_doc = """
Medical Device-Related Pressure Injury in health care professionals in times of pandemic
Aline Oliveira Ramalho, Paula de Souza Silva Freitas, Paula Cristina Nogueira
Estima. 2020;18(1) DOI 10.30886/estima.v18.867_IN
Abstract | Full Text
Facing the number of cases of coronavirus infection (COVID-19).

"""

soup = BeautifulSoup(html_doc, 'lxml')

div = soup.find("div")

result = div.find("a", attrs={"href": re.compile("^/toc/2595-7007.*")}).next_sibling

result = result.replace('.',"")

print(result)

Output will be:
2020;18(1) DOI

A: If you have BS 4.7.1 or above you can use below css selector.
html='''
Medical Device-Related Pressure Injury in health care professionals in times of pandemic
Aline Oliveira Ramalho, Paula de Souza Silva Freitas, Paula Cristina Nogueira
Estima 2020;18(1) DOI 10.30886/estima.v18.867_IN
Abstract | Full Text
Facing the number of cases of coronavirus infection (COVID-19).

'''
soup=BeautifulSoup(html,"html.parser")
print(soup.select_one('a:contains("Estima")').next_sibling)


text:
Q: Symfony + Doctrine - possible to link more than 2 tables/models together? I've created an sfGuardUserProfile model that has a relation to the sfGuardUser model. Then I define another model with a relation to sfGuardUserProfile. I don't get any errors when I create the database, but when I try saving data to sfGuardUserProfile in my actions file, I get this error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
In my schema.yml, I am defining the relationships as one to one.
I'm not sure why this would be failing. Does Doctrine simply not support adding a new relationship to a model that already has a relationship?
Edit
Here's my schema.yml:
sfGuardUserProfile:
  tableName: sf_guard_user_profile
  columns:
    sf_guard_user_id: { type: integer(4) }
    email:            { type: string(255) }
  relations:
    User:
      class:        sfGuardUser
      type:         one
      foreignType:  one
      onDelete:     CASCADE
      local:        sf_guard_user_id
      foreign:      id
      foreignAlias: Profile

FacebookAccount:
  tableName: facebook_account
  columns:
    user_id: { type: integer(4) }
    page_id: { type: integer }
  relations:
    sfGuardUserProfile:
      type:         one
      foreignType:  one
      class:        sfGuardUserProfile
      local:        user_id
      foreign:      sf_guard_user_id
      onDelete:     CASCADE
      foreignAlias: FacebookAccount

I encounter the error when I do this:
$profile = $this->getUser()->getProfile();
$profile->setEmail('someone@somewhere.com');
$profile->save();

The generated SQL:
INSERT INTO sf_guard_user_profile (sf_guard_user_id, email) VALUES (?, ?) - (1, someone@somewhere.com)

The exact error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`site`.`sf_guard_user_profile`, CONSTRAINT `sf_guard_user_profile_sf_guard_user_id_facebook_account_user_id` FOREIGN KEY (`sf_guard_user_id`) REFERENCES `facebook_account` (`user_id`))

A: I think your problem is your FacebookAccount model not linking to the primary key on your Profile model and Doctrine not knowing how to work with it.  Either change your FacebookAccount to reference the Profile primary key:
  relations:
    sfGuardUserProfile:
      type:         one
      foreignType:  one
      class:        sfGuardUserProfile
      local:        user_id
      foreign:      id
      onDelete:     CASCADE
      foreignAlias: FacebookAccount

or relate to the primary key of sfGuardUser:
  relations:
    sfGuardUser:
      type:         one
      foreignType:  one
      class:        sfGuardUser
      local:        user_id
      foreign:      id
      onDelete:     CASCADE
      foreignAlias: FacebookAccount

A: You have to ensure that you don't break database integrity: http://msdn.microsoft.com/en-us/library/ms175464.aspx . You can reach that inserting rows in correct order, for example:
$sfGuardUser = new sfGuardUser();
$sfGuardUser->id = 1;
$sfGuardUser->save();

$sfGuardUserProfile = new sfGuardUserProfile();
$sfGuardUserProfile->user_id = $sfGuardUser->id;
$sfGuardUserProfile->save();

or like this:
$sfGuardUser = new sfGuardUser();
$sfGuardUser->id = 1;

$sfGuardUserProfile = new sfGuardUserProfile();
$sfGuardUserProfile->User = $sfGuardUser;
sfGuardUserProfile->save();


text:
Q: Прокси сервер Здравствуйте. Скажите пожалуйста, что именно кэшируется на прокси-сервере ( если мы к примеру кэшируем информацию с новостного сайта, где контент меняется каждые 5 минут)?
По видам прокси-сервера делятся на прозрачный и обратный? Если так, то суть каждого вида?
A:
что именно кэшируется на прокси-сервере

Кэшируется то, что сказано кэшировать :) И, если прокси правильный, то что кэшировать а что нет, что сколько времени хранить в кэше - ему сообщает удалённый сервер для каждого элемента отдельно. А он эту информацию принимает и переваривает.

контент меняется каждые 5 минут

Любой контент состоит из множества элементов. Зайдите на страничку любого "новостного сайта" и посмотрите, сколько там картинок, подключаемых скриптов, стилей и прочего. Подумайте, что из этого стоит сохранять в кэше, а что нет.

По видам прокси-сервера делятся на прозрачный и обратный? Если так, то суть каждого вида?

Первый же тык в гугл


text:
Q: Site redirecting constantly? After a LOT of server trouble we are now seeing this:
http://www.unislim.com/
What the hell is happening here!?
Looks like a local DNS issue?
Can anyone point us in the right direction as the homepage is down but everything else is fine e.g: http://www.unislim.com/slim-with-us/find-a-meeting
I have racked my brains for HOURS over this.

A: You have this line in the meta-tag which you should not have:
<meta http-equiv="refresh" content="0;url=http://www.unislim.com/">

This is the cause of the loop.

A: You should remove this line from your homepage
<meta http-equiv="refresh" content="0;url=http://www.unislim.com/">


text:
Q: javascript function that takes two inputs: an object and a key and returns the corresponding value for that key within the object I'm trying to create a JavaScript function that takes an object as input, and returns the values of all the keys in the object. Please kindly help review my code, I'm not getting the result I expect.
var james = {
    firstName: "James",
    lastName: "John",
    age: 40,
    job: "programmer",
    married: false
};

function hasElObject(valObject, key) {
    var i = valObject.length;
    while (i--) {
        if (valObject[i] === key) {
            return valObject[i];
        }
    }
    return 'key not found';
}
var objectEl = hasElObject (['congratulations', 'top', 8, 90], 5);
log (arrayEl);

var retValue = getValue(mary,email);
log (retValue);

A: function hasElObject(valObject, key) {
  for (var k in valObject) {
    if (k == key)
      return valObject[k];
  }
  return 'key not found';
}

var jobOfJames = hasElObject(james, "job");
console.log(jobOfJames);

A: Just use the native basic JS:
function hasElObject(obj, key) {
  return obj.hasOwnProperty(key) ? obj[key] : 'key not found';
}


text:
Q: Pass empty argument as array index I have a function that takes user input for array indices and then performs a calculation. The index must be a string. Here is a snippet of the data attributes for context:
> attributes(data)
$dim
[1]  50 100 100

$dimnames
$dimnames[[1]]
 [1] "0.001"             "0.613224489795918" "1.22544897959184"  "1.83767346938775"  "2.44989795918367"  "3.06212244897959"
 [7] "3.67434693877551"  "4.28657142857143"  "4.89879591836735"  "5.51102040816327"  "6.12324489795918"  "6.7354693877551"
[13] "7.34769387755102"  "7.95991836734694"  "8.57214285714286"  "9.18436734693877"  "9.79659183673469"  "10.4088163265306"
[19] "11.0210408163265"  "11.6332653061224"  "12.2454897959184"  "12.8577142857143"  "13.4699387755102"  "14.0821632653061"
[25] "14.694387755102"   "15.306612244898"   "15.9188367346939"  "16.5310612244898"  "17.1432857142857"  "17.7555102040816"
[31] "18.3677346938776"  "18.9799591836735"  "19.5921836734694"  "20.2044081632653"  "20.8166326530612"  "21.4288571428571"
[37] "22.0410816326531"  "22.653306122449"   "23.2655306122449"  "23.8777551020408"  "24.4899795918367"  "25.1022040816327"
[43] "25.7144285714286"  "26.3266530612245"  "26.9388775510204"  "27.5511020408163"  "28.1633265306122"  "28.7755510204082"
[49] "29.3877755102041"  "30"

$dimnames[[2]]
  [1] "10"   "20"   "30"   "40"   "50"   "60"   "70"   "80"   "90"   "100"  "110"  "120"  "130"  "140"  "150"  "160"  "170"  "180"
 [19] "190"  "200"  "210"  "220"  "230"  "240"  "250"  "260"  "270"  "280"  "290"  "300"  "310"  "320"  "330"  "340"  "350"  "360"
 [37] "370"  "380"  "390"  "400"  "410"  "420"  "430"  "440"  "450"  "460"  "470"  "480"  "490"  "500"  "510"  "520"  "530"  "540"
 [55] "550"  "560"  "570"  "580"  "590"  "600"  "610"  "620"  "630"  "640"  "650"  "660"  "670"  "680"  "690"  "700"  "710"  "720"
 [73] "730"  "740"  "750"  "760"  "770"  "780"  "790"  "800"  "810"  "820"  "830"  "840"  "850"  "860"  "870"  "880"  "890"  "900"
 [91] "910"  "920"  "930"  "940"  "950"  "960"  "970"  "980"  "990"  "1000"

$dimnames[[3]]
  [1] "1"   "2"   "3"   "4"   "5"   "6"   "7"   "8"   "9"   "10"  "11"  "12"  "13"  "14"  "15"  "16"  "17"  "18"  "19"  "20"  "21"
 [22] "22"  "23"  "24"  "25"  "26"  "27"  "28"  "29"  "30"  "31"  "32"  "33"  "34"  "35"  "36"  "37"  "38"  "39"  "40"  "41"  "42"
 [43] "43"  "44"  "45"  "46"  "47"  "48"  "49"  "50"  "51"  "52"  "53"  "54"  "55"  "56"  "57"  "58"  "59"  "60"  "61"  "62"  "63"
 [64] "64"  "65"  "66"  "67"  "68"  "69"  "70"  "71"  "72"  "73"  "74"  "75"  "76"  "77"  "78"  "79"  "80"  "81"  "82"  "83"  "84"
 [85] "85"  "86"  "87"  "88"  "89"  "90"  "91"  "92"  "93"  "94"  "95"  "96"  "97"  "98"  "99"  "100"

I want to have something like this:
myfun <- function(index){
    apply(X=data[,index,], MARGIN = c(1,2),FUN =  mean)
}

However, if a user wants to select the entire data set, we need to have data[,,]. However, I am not sure how to achieve this as you cannot pass an empty argument to a function. How can I represent the empty spot between the commas as a function argument?

A: You can use missing, so that a missing index implies "select all", which I assume means that the user would just want the grand mean.
myfun <- function(index)
{
  if(missing(index)) mean(data) else apply(data[, index, ], 1:2, mean)
}


text:
Q: Is apparent horizon curvature lesser due to refraction of light in the atmosphere? I have encountered this claim while searching for sources answering " https://skeptics.stackexchange.com/questions/5310/can-we-see-the-curvature-of-earth-from-the-top-of-worlds-tallest-building ".
Wikipedia article on horizon claims (with no references), that compared to a geometrical model, the the apparent curvature of Earth is less than expected due to refraction of light in the atmosphere.
Thinking about the problem, I fail to see why this could be so. It is easy to see the refraction affects a distance of the apparent horizont, but I fail to see how it could affect its curvature, as the refraction seems to have the same effect in all directions, because your distance to horizon is the same in all directions.
Is that claim just bogus and there is no such effect, or is the effect real?

A: Yes -- because refraction influences the apparent distance to the horizon, it also has an effect on the curvature.
To visualize this, it might help to think in extreme cases, for example in the case where due to refraction the horizon is at an apparent distance of only 1 meter. In this case, the curvature of the horizon would be extreme (it would be a circle of radius 1 meter around you).
In reality the curvature effect is much smaller of course, and I doubt that it is visible.
(As an aside: one result of atmospheric refraction that is observable is a phenomena called 'the green flash'. Because refraction is colour-dependent, the red and yellow part of the sun could already have set, while a small part of the 'green sun' is still above the horizon. This can be observed by the naked eye, preferably when the horizon is sharp.)

A: Sometimes.
When you are standing on the ground, you are in air at roughly one atmosphere of pressure; so are the points on the earth that you see on the horizon; and so is the whole path of the light from the horizon to you. In this case there is no significant boundary where the refractive index (RI) changes, nor is there an appreciable deviation in RI over the path of the light you are seeing. Therefore there will be no bending of the light rays, and no effect on the perceived curvature of the horizon.1
When you are at significant altitude, you are in air at significantly lower pressure than the air at the surface of the earth. Therefore the light from the horizon moves through a region with a pronounced gradient in RI. This causes the light rays to curve, making the radius of the horizon appear larger (and thus the curvature smaller) than it otherwise would. It is this scenario that the linked Wikipedia page is talking about when it states:
At an altitude of 10 km ... the apparent curvature is less than that due to refraction of light in the atmosphere
1: There will of course be small deviations in air pressure (and therefore the RI) along the path of the ray, but these would be random and time-varying, so they will manifest as a slight blurring or "wobble" of the image of a point seen on the horizon, not a shift in it's observed location.

A: the Earth curves at the rate of 157mrad per km travelled. The refractive index of dry air at sea level is 1.00029, but at a height of 1km, the air pressure is 12% less and (neglecting temperature density and humidity), the refractive index would be 1 + 0.00029 * 88%. The difference, 0.000035 means that light at 1km altitude travels 35mm further for every km, curving the path of light by 35mrad per km travelled, about 20% of the Earth's curvature.. allowing us to see past the theoretical horizon a bit .. an extra 20% distance!


text:
Q: Force quit of Android App using System.exit(0) doesn't work when I try to quit my Android application by overwriting the function for the back-button of Android devices and "System.exit(0)", this doesn't work.
I have an activity named "LoginActivity" and an activity named "OverviewActivity".
When I start an intent in OverviewActivity to switch to LoginActivity, this works.
Intent changeViewIntent = new Intent(OverviewActivity.this,
            LoginActivity.class);
startActivity(changeViewIntent);

Now I am in LoginActivity and there is the overwritten method:
@Override
public void onBackPressed() {
    System.exit(0);
}

But when I press the back-key (e.g. in the device simulator) the screen is blank for a millisecond and then it goes back to the OverviewActivity.
Why is this happening? I just want to force the close when the back-key is pressed.
History disabling for the OverviewActivity in the manifest is no option, because there are several ways to access the OverviewActivity from other activities.
Maybe there is an idea? Android 4 is minimium requirement, so it doesn't have to work on lower versions..
Thanks!

A: The Exit is possible by deleting the whole activity-call-history and starting the Home-Activity of the Home-Scrren.
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

A: What you can do is
In your OverviewActivity:
Intent changeViewIntent = new Intent(OverviewActivity.this,
            LoginActivity.class);
startActivity(changeViewIntent);
OverviewActivity.this.finish();

after starting the intent you terminate the overview activity
and in LoginActivity
@Override
public void onBackPressed() {
    LoginActivity.this.finish();

}

This way your app will exit.
The difference between finish() and System.exit(0)
The VM stops further execution and program will be exit.
Now, in your case the first activity comes back due to activity stack.
So when you move from one activity to another using Intent, do the finish() of current activity like this.
If you want to force quit you can use
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
        getParent().finish();

But you should not use System.exit especially if your activity uses other recourses in the background e.g. Internet, Video, etc.


text:
Q: EntityCommandExecutionException happening only on AzureSQL I do have the following Class and Controller
    public class FieldHelper
    {
        public FieldHelper(RoomMeta rm, string typeClass)
        {
            this.typeClass = typeClass;
            this.Name = rm.Name;
            if (rm.Required)
                this.required = "required";
            else
                this.required = "optional";
        }

        public FieldHelper(EventTypeMeta etm, string typeClass)
        {
            this.typeClass = typeClass;
            this.Name = etm.Name;
            if (etm.Required)
                this.required = "required";
            else
                this.required = "optional";
        }

        public string typeClass { get; set; }

        public string Name { get; set; }

        public string required { get; set; }
    }

    [HttpGet]
    public JsonResult GetDefaultFields(int eventTypeID, int roomID)
    {
        using (var db = new MyDbContext())
        {
            List<FieldHelper> fields = new List<FieldHelper>();
            foreach(RoomMeta rm in db.RoomMetaSet.Where(rm => rm.RoomId == roomID))
            {
                fields.Add(new FieldHelper(rm, rm.FieldTypes.Name)); //Here the Exception gets thrown
            }
            foreach(EventTypeMeta etm in db.EventTypeMetaSet.Where(etm => etm.EventTypeId == eventTypeID))
            {
                fields.Add(new FieldHelper(etm, etm.FieldTypes.Name));
            }
            return Json(fields, JsonRequestBehavior.AllowGet);
        }
    }

My database layout looks as follows:

Now, when I run this on my local machine, where I use a SQL Server Express 2014 installation, everything works just the way I expected it. However, once I deploy the Application to a Windows Azure Website with a Azure SQL Database, I get an EntityCommandExecutionException at the line marked. The inner exception tells me "There is already an open DataReader associated with this Command which must be closed first." which seems somehow more useful to me, but still I couldn't figure out why this works localy but not online.
Any Ideas would be appreciated.

A: Looks like I've found the Answer myself. Since I didnt Include the related Entitys in my query, entity framework tried to open another connection, which failed due to the restriction of my azure sql database.
I changed
        foreach(RoomMeta rm in db.RoomMetaSet.Where(rm => rm.RoomId == roomID))

to
        foreach(RoomMeta rm in db.RoomMetaSet.Include("FieldTypes").Where(rm => rm.RoomId == roomID))

and everything works fine now.


text:
Q: Java Kryonet Error when sending object I am using Kryonet for TCP sending of objects, particularly one called TransferMessage:
public static class TransferMessage{String text; String username; Color color = Color.black;}

Now, I know that I have to call kryo.register(TransferMessage.class) but when I attempt to connect to the server with all the classes registered, I get an error:
    Exception in thread "Server" com.esotericsoftware.kryo.KryoException: java.lang.IllegalArgumentException: Class is not registered: java.awt.Color
Note: To register this class use: kryo.register(java.awt.Color.class);
Serialization trace:
color (com.andrewlalisofficial.MessageTypes$TransferMessage)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.write(FieldSerializer.java:585)
    at com.esotericsoftware.kryo.serializers.FieldSerializer.write(FieldSerializer.java:213)
    at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:571)
    at com.esotericsoftware.kryonet.KryoSerialization.write(KryoSerialization.java:50)
    at com.esotericsoftware.kryonet.TcpConnection.send(TcpConnection.java:192)
    at com.esotericsoftware.kryonet.Connection.sendTCP(Connection.java:59)
    at com.esotericsoftware.kryonet.Server.sendToAllTCP(Server.java:435)
    at com.andrewlalisofficial.ChatServer.sendMessage(ChatServer.java:204)
    at com.andrewlalisofficial.ChatServer.checkCommand(ChatServer.java:124)
    at com.andrewlalisofficial.ChatServer$1.received(ChatServer.java:72)
    at com.esotericsoftware.kryonet.Server$1.received(Server.java:61)
    at com.esotericsoftware.kryonet.Connection.notifyReceived(Connection.java:246)
    at com.esotericsoftware.kryonet.Server.update(Server.java:208)
    at com.esotericsoftware.kryonet.Server.run(Server.java:356)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Class is not registered: java.awt.Color

I don't understand because although my registered class uses the Color class, I never before had to register String objects, so I don't see what the difference here is, and how would I fix this error? Thank you in advance for your help.
EDIT :
Here is a minimal reproducible code showing an error while serializing Color :
// this works actually fine
public static void main(String[] args) {
    Kryo kryo = new Kryo();
    kryo.register(Color.class, new JavaSerializer());

    Color color = new Color(15006);

    Output output = new Output(new byte[1024]);
    kryo.writeObject(output, color);

    Input input = new Input(output.getBuffer());
    Color color2 = kryo.readObject(input, Color.class);

    if (!color.equals(color2)) throw new AssertionError();
}

A: String must be registered by default. I'm a bit surprised of this error myself because I always have been able to serialize classes I did not register simply because Kryo possesses default serializers for trivially serializable classes. Anyway, since java.awt.Color implements java.io.Serializable, I would just do
kryoRegistrator.register(Color.class, new JavaSerializer());

You can also write your own serializer (using Kryo) if you want, but I'm not sure it's worth it (it's just a simple integer to serialize, there is no way the standard library does it inefficiently). If you want it anyway, here it is :
public class ColorSerializer extends Serializer<Color> {
    @Override
    public Color read(Kryo kryo, Input input, Class<Color> clazz) {
        return new Color(input.readInt());
    }

    @Override
    public void write(Kryo kryo, Output output, Color color) {
        output.write(color.getRGB());
    }
}


text:
Q: AngularJs native slide toggle for nested submenues doesn't update height correctly I'm implementing the a slide toggle for a nested menu in AngularJS. I've been using the code from the following page: https://blog.assaf.co/native-slide-toggle-for-angularjs-1-4-x/
I'm having only one problem with it though. I'm trying to implement this on a sidenav menu with nested submenues, built with
 and
 elements. After having toggled a menu item that has submenu, and I later toggle the submenu of that same menu button, the
 element of that menu button doesn't slide in. The height remains the same.
Also, if I keep the submenu closed, and open only the top menu item, the height of the
 element remains the same when I toggle the submenu, meaning that the submenu doesn't show until I toggle it open (though remaining invisible), then close the top menu button, then open it again.
Please see it in action here:
https://codepen.io/marcus-edensky/pen/MBoWZJ
Here's my JavaScript code:
app.controller('myCtrl', function($scope, $mdSidenav) {
});

app.animation('.slide-toggle', ['$animateCss', function($animateCss) {
    var lastId = 0;
    var _cache = {};

    function getId(el) {
        var id = el[0].getAttribute("data-slide-toggle");
        if (!id) {
            id = ++lastId;
            el[0].setAttribute("data-slide-toggle", id);
        }
        return id;
    }
    function getState(id) {
        var state = _cache[id];
        if (!state) {
            state = {};
            _cache[id] = state;
        }
        return state;
    }

    function generateRunner(closing, state, animator, element, doneFn) {
        return function() {
            state.animating = true;
            state.animator = animator;
            state.doneFn = doneFn;
            animator.start().finally(function() {
                if (closing && state.doneFn === doneFn) {
                    element[0].style.height = '';
                }
                state.animating = false;
                state.animator = undefined;
                state.doneFn();
            });
        }
    }

    return {
        addClass: function(element, className, doneFn) {
            if (className == 'ng-hide') {
                var state = getState(getId(element));
                var height = (state.animating && state.height) ?
                    state.height : element[0].offsetHeight;

                var animator = $animateCss(element, {
                    from: {height: height + 'px'},
                    to: {height: '0px'}
                });
                if (animator) {
                    if (state.animating) {
                        state.doneFn =
                          generateRunner(true,
                                         state,
                                         animator,
                                         element,
                                         doneFn);
                        return state.animator.end();
                    }
                    else {
                        state.height = height;
                        return generateRunner(true,
                                              state,
                                              animator,
                                              element,
                                              doneFn)();
                    }
                }
            }
            doneFn();
        },
        removeClass: function(element, className, doneFn) {
            if (className == 'ng-hide') {
                var state = getState(getId(element));
                var height = (state.animating && state.height) ?
                    state.height : element[0].offsetHeight;

                var animator = $animateCss(element, {
                    from: {height: '0px'},
                    to: {height: height + 'px'}
                });

                if (animator) {
                    if (state.animating) {
                        state.doneFn = generateRunner(false,
                                                      state,
                                                      animator,
                                                      element,
                                                      doneFn);
                        return state.animator.end();
                    }
                    else {
                        state.height = height;
                        return generateRunner(false,
                                              state,
                                              animator,
                                              element,
                                              doneFn)();
                    }
                }
            }
            doneFn();
        }
    };
}]);

(function() {
    var app = angular.module('app', ['ngAnimate']);

    app.animation('.slide-toggle', ['$animateCss', function($animateCss) {
        return {
            addClass: function(element, className, doneFn) {
                if (className == 'ng-hide') {
                    var animator = $animateCss(element, {
                        to: {height: '0px'}
                    });
                    if (animator) {
                        return animator.start().finally(function() {
                            element[0].style.height = '';
                            doneFn();
                        });
                    }
                }
                doneFn();
            },
            removeClass: function(element, className, doneFn) {
                if (className == 'ng-hide') {
                    var height = element[0].offsetHeight;
                    var animator = $animateCss(element, {
                        from: {height: '0px'},
                        to: {height: height + 'px'}
                    });
                    if (animator) {
                     return animator.start().finally(doneFn);
                    }
                }
                doneFn();
            }
        };
    }]);
})();

Here's the HTML - a simple :

Tours

Group tours

Planning

Types

Users

Staff

Clients

Here's the CSS:
.slide-toggle {
  overflow: hidden;
  transition: all 0.25s;
}

A: The parent still holds the height after the animation. You have to remove it.
Add element[0].style.height = 'auto' after animation is done.In the generateRunner function at line 36 after the if
function generateRunner(closing, state, animator, element, doneFn) {
  return function () {
    state.animating = true;
    state.animator = animator;
    state.doneFn = doneFn;
    animator.start().finally(function () {
      if (closing && state.doneFn === doneFn) {
        element[0].style.height = '';
      }
      element[0].style.height = 'auto'; // <----- HERE
      state.animating = false;
      state.animator = undefined;
      state.doneFn();
    });
  }
}

Hope this helps. Good luck!


text:
Q: Reopening database after onpause I am new to android programming and am just starting to dabble in using a sqlite database. In my app, I am closing the database at onpause and ondestroy.
However, when using the app, I am attempting to reopen the database/app after closing it for a short while, but kept having an error 'unable to open an already closed database'?
Please help. Here is the excerpt of the java file;
public class Apple extends Activity {

DbA myDb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.apple_layout);
    openDB();
    }

  private void openDB() {
myDb= new DbA(this);
myDb.open();
}

  @Override
  protected void onDestroy() {
super.onDestroy();
myDb.close();
  }

  @Override
  protected void onResume() {
super.onResume();
myDb.open();
 }

  @Override
 protected void onPause() {
super.onPause();
myDb.close();
  }

Please tell me what I'm doing wrong.

A: In my opinions there's no need to keep an open database connection the whole lifecycle of the activity.
I usually get writable database when I'm going to perform an action and close when it finish.
For example, to add records, you can have the following method
public void addItem(Item item) {
    if (item == null) {
        return;
    }

    // get writable database and begin transaction
    final SQLiteDatabase database = dbHelper.getWritableDatabase();
    database.beginTransaction();

    // INSERT ITEM IN DATABASE

    // End transaction and close connection
    database.setTransactionSuccessful();
    database.endTransaction();
    database.close();
}


text:
Q: AES Encryption Issue between Java and C# .Net I've looked at countless examples on the web and in this forum and I can't find my answer.
I have a Java client that successfully encrypts and decrypts data.
I have a .Net client that successfully encrypts and decrypts data.
I put the .Net version up as a web service.  I encrypt some data in the java client and send it to the .Net web service.  I get:
--Padding is invalid and cannot be removed.--
So I make sure I'm using the same encoding, IV, Key, everything.  The only think I can figure is that I'm sending a byte array to the service.  When I spit out the array from the java client and compare it to the array that arrives at the service, as you would expect, the array at the service is different in that it's cast as an unsigned byte array.  Here are the two arrays:
[-47 17 -27 -32 -101 54 -93 47 85 -83 -31 -102 53 -125 115 -14]
[209 17 229 224 155 54 163 47 85 173 225 154 53 131 115 242]
So I'm guessing that this is causing the issue.  How can I get around this?  None of the Rijndael implementations accept signed byte arrays.  Is there a conversion I'm missing?
Thanks for any help.  I'm ready to gouge my brain out through my arse.
ST
EDIT -
After reviewing the code I found my error.  I had to copy some data and started at the wrong index.  Arrrgggghhhhhhh!
Sorry to trouble.

A: You've got the same actual data in both cases - it's just that Java doesn't support unsigned bytes. If each platform can decrypt its own data, and you've got the same data generated by both platforms, it's hard to see how they could tell the difference.
My guess is that you're doing something differently on the .NET side. We'll need to see code to know for sure.
What happens if you try to decrypt the exact same data in the .NET client which can decrypt data? I suggest you create a small console app which just tries to decrypt a file. Make your .NET server save whatever data it's given to the file and then try to decrypt it as normal. Then run the console app on the file. Report the results here, and we'll try to help you make sense of them.


text:
Q: Reading partial json data with MySQL and PHP I use a CMS that saves resources in JSON format in MySQL (In one table).
Together with normal data from MySQL. When I loop through the data, I get an array + the JSON data. But I need to search in the JSON data for the XNCatnCode.
Trying to load the data
 $Products = $SQL->fetchAll("SELECT * FROM `pages` WHERE `parent` = 1");

    foreach ($Products as $Product => $value) {
        foreach (json_decode($value['resources'], true) as $resources => $data) {
            // var_dump($resources);
            foreach ($resources['XNCatnCode'] as $resource => $value) {
                # code...
                // }

            }
        }
    }

I can dump the data using var_dump($resources); in the second loop.
That will return
string(5) "Model"
string(8) "ItemCode"
string(8) "ItemDesc"
string(7) "ExtDesc"

But I cannot loop through the Data, search for the XNCatnCode. (the value has to be 3 for).
When I look at the dump, directly via a var_dump from $Products = $SQL->fetchAll("SELECT * FROMpagesWHEREparent= 1"). I get this Data back :)
Bottom line, How can I loop trought the json data and select all Products who have XNCatnCode 3 :)?
array(1) {
  [0]=>
  array(26) {
    ["id"]=>
    string(1) "3"
    ["trunk"]=>
    string(0) ""
    ["parent"]=>
    string(1) "1"
    ["in_nav"]=>
    string(2) "on"
    ["nav_title"]=>
    string(9) "USB STICK"
    ["route"]=>
    string(9) "usb-stick"
    ["path"]=>
    string(19) "producten/usb-stick"
    ["title"]=>
    string(9) "USB STICK"
    ["meta_keywords"]=>
    string(0) ""
    ["meta_description"]=>
    string(0) ""
    ["open_graph"]=>
    NULL
    ["seo_invisible"]=>
    string(0) ""
    ["template"]=>
    string(8) "Products"
    ["external"]=>
    string(0) ""
    ["new_window"]=>
    string(0) ""
    ["resources"]=>
    string(1898) "{
    "Model": "Simple",
    "ItemCode": "Mijn COde",
    "ItemDesc": "Gaaf ding",
    "ExtDesc": "Heeeeeeel gaaf ding",
    "ItemKeywords": "Gaaf",
    "Size": "5 meter",
    "SizeGrid": "",
    "Gender": "",
    "WeightGR": "",
    "LengthCM": "",
    "HeightCM": "",
    "WidthCM": "",
    "DiameterCM": "",
    "SizeCombined": "",
    "QtyperCarton": "",
    "DecoPackagingIndiv": "",
    "DecoPackagingIndivType": "",
    "DecoPackaging": "",
    "GrossWeightKG": "",
    "NettWeightKG": "",
    "ExportLcm": "",
    "ExportWcm": "",
    "ExportHcm": "",
    "CountryOfOrigin": "",
    "HSCode": "",
    "ImpAllMethods": "",
    "ImpMethodDefault": "",
    "ImpAllPositions": "",
    "ImpPositionDefault": "",
    "ImpPositionSimpleDefault": "",
    "ImpWidthDefaultMM": "",
    "ImpHeightDefaultMM": "",
    "ImpDiameterDefaultMM": "",
    "ImpSizeDefaultMM": "",
    "MaxColoursDefault": "",
    "Brand": "",
    "XNGroupCode": "",
    "XNGroupDesc": "",
    "XNCatnCode": "3",
    "XNCatDesc": "",
    "ColorDesc": "",
    "SimpleColor": "",
    "PMSColorReference": "",
    "BasicColor": "",
    "PenInkColor": "",
    "Material": "",
    "BatteryType": "",
    "Features": "",
    "BestSeller": "",
    "EANCode": "",
    "ThematicItem": "",
    "Compliances": "",
    "ImageMain": "",
    "ImageDecoY1": "",
    "ImageDecoY2": "",
    "ImageDecoY3": "",
    "ImagePackage": "",
    "ImageFront": "",
    "ImageBack": "",
    "ImageExtra1": "",
    "ImageExtra2": "",
    "ImageExtra3": "",
    "ImageDetail1": "",
    "ImageDetail2": "",
    "ImageDetail3": "",
    "ImagePrintLinesDefault": "",
    "MarkSegment": "",
    "MainCat": "",
    "EOYCat": "",
    "LaunchDate": "",
    "Language": "",
    "HEXcolor": "",
    "ImageGroup": "",
    "ImageMood1": "",
    "ImageMood2": "",
    "ImageMood3": "",
    "ImageModel": "",
    "VideoUrl1": "",
    "VideoUrl2": "",
    "NewItem": ""
}"
    ["archived"]=>
    string(0) ""
    ["archived_inherited"]=>
    string(0) ""
    ["publish_at"]=>
    NULL
    ["expire_at"]=>
    NULL
    ["max_age"]=>
    string(1) "0"
    ["last_edited_by"]=>
    string(1) "1"
    ["ga_page_views"]=>
    string(1) "0"
    ["position"]=>
    string(1) "0"
    ["created_at"]=>
    string(19) "2018-12-25 08:27:55"
    ["updated_at"]=>
    string(19) "2018-12-26 05:33:41"
  }
}

A: foreach ($Products as $Product)
{

        $decoded = json_decode($Product['resources'], true);
        if(isset($decoded['XNCatnCode']))
        {
             //This $Product has XNCatnCode
        }
}

I removed the $ before JSON decode. So the script works :)


text:
Q: MVC 4 Entity Framework Model is null I have This Code in my Truck Controller, every time i run it.
My model is always null.
    [HttpPost]
    public ActionResult AddTruck(TruckDataModel model)
    {
        var newTruck = new truck()
        {
            registration_no = model.reg_no,
            make = model.make,
            model = model.model,
            engine_no = model.engine_no,
            chassis_no = model.chassis_no,
            driver_name = model.driver_name,
            driver_no = model.driver_no,
            current_run = model.current_run,

        };

        if (ModelState.IsValid)
        {
            db.trucks.Add(newTruck);
            db.SaveChanges();
            return RedirectToAction("TruckList","Trucks");
        }

        return View(model);

This is my model
public class TruckDataModel
{
    [Required(ErrorMessage = "Registration No. required", AllowEmptyStrings = false)]
    [Display(Name = "Registration No.")]
    public string reg_no { get; set; }

    [Required(ErrorMessage = "Make required", AllowEmptyStrings = false)]
    [Display(Name = "Make")]
    public string make { get; set; }

    [Required(ErrorMessage = "Model required", AllowEmptyStrings = false)]
    [Display(Name = "Model")]
    public string model { get; set; }

    [Required(ErrorMessage = "Engine No. required", AllowEmptyStrings = false)]
    [Display(Name = "Engine No.")]
    public string engine_no { get; set; }

    [Required(ErrorMessage = "Chassis No. required", AllowEmptyStrings = false)]
    [Display(Name = "Chassis No.")]
    public string chassis_no { get; set; }

    [Required(ErrorMessage = "Driver Name required", AllowEmptyStrings = false)]
    [Display(Name = "Driver Name")]
    public string driver_name { get; set; }

    [Required(ErrorMessage = "Current Run required", AllowEmptyStrings = false)]
    [Display(Name = "Current Run")]
    public int current_run { get; set; }

    [Required(ErrorMessage = "Driver no. required", AllowEmptyStrings = false)]
    [Display(Name = "Driver No.")]
    public int driver_no { get; set; }

}//just for allow to edit

I have the exception NullReference always occur, and when I breakpoint, the all the model is null.
I have the exact code in my CreateUser Action but it works perfectly fine?
Please need help TY SO MUCH!!

A: Your TruckDataModel model has a property named model and your POST method parameter is also named model. You need to change one or the other, say
public ActionResult AddTruck(TruckDataModel truck)
{
  ....
}

The reason is that the DefautModelBinder first initializes an instance of TruckDataModel. It then reads the form data, sees a name/value pair for model, then tries to set your parameter to its value (to say model="Ford") which fails and so the model becomes null


text:
Q: version concurrency control for a long session. NHibernate. ASP.NET MVC 1) What is more appropriate/commonly used approach for concurrency control? Pessimistic or optimistic locking?
2) How do I notify a user if there's a lock on an item or whether rollback had occured?
3) Suppose I've added all needed markup (like optimistic-locking="false" to exclude properties I don't want to be involved in comparing) to my entity mapping files and defined a Version property on entity classes to handle concurrency control. Would that be enough and all stuff is processed within/by NHibernate. Or additional modifiactions should be present? For example in Repository?
public class Repository<T> : IRepository<T> where T : AbstractEntity<T>, IAggregateRoot
{
    private ISession session;

    public Repository(ISession session)
    {
        this.session = session;
    }

    public T Get(Guid id)
    {
        return this.session.Get<T>(id);
    }
    public IQueryable<T> Get(Expression<Func<T, Boolean>> predicate)
    {
        return this.session.Query<T>().Where(predicate);
    }
    public IQueryable<T> Get()
    {
        return this.session.Query<T>();
    }
    public T Load(Guid id)
    {
        return this.session.Load<T>(id);
    }
    public void Add(T entity)
    {
        using(var transaction = this.session.BeginTransaction())
        {
            this.session.Save(entity);
            transaction.Commit();
        }
    }
    public void Remove(T entity)
    {
        using(var transaction = this.session.BeginTransaction())
        {
            this.session.Delete(entity);
            transaction.Commit();
        }
    }
    public void Remove(Guid id)
    {
        using(var transaction = this.session.BeginTransaction())
        {
            this.session.Delete(this.session.Load<T>(id));
            transaction.Commit();
        }
    }
    public void Update(T entity)
    {
        using(var transaction = this.session.BeginTransaction())
        {
            this.session.Update(entity);
            transaction.Commit();
        }
    }
    public void Update(Guid id)
    {
        using(var transaction = this.session.BeginTransaction())
        {
            this.session.Update(this.session.Load<T>(id));
            transaction.Commit();
        }
    }
}

// DI
public class DataAccessModule : Ninject.Modules.NinjectModule
{
    public override void Load()
    {
        this.Bind<ISessionFactory>()
            .ToMethod(c => new Configuration().Configure().BuildSessionFactory())
            .InSingletonScope();

        this.Bind<ISession>()
            .ToMethod(ctx => ctx.Kernel.TryGet<ISessionFactory>().OpenSession())
            .InRequestScope();

        this.Bind(typeof(IRepository<>)).To(typeof(Repository<>));
    }
}

I'm using a long session with multiple transactions.
Thanks!

A: Your repository should never handle transaction scopes. Its a totally different requirement and Repository cant know what boundaries should transaction be have.
Transactions should be handled somewhere outside by infrastructure code. If you are using ASP.NET MVC - action filters are appropriate(see implementation is Sharp Architecture project).
If its ASP.NET then module or global asax handling could be applied.
But just DON'T handle it in repository, its very leaky abstraction, you WILL need expose boundaries to caller.

A: You are missing the "unit of work" pattern here.


text:
Q: Why is my game not running and certain elements are not loading in? I just made a simple game on visual studio code, where a player has to chase the square. But im not sure why its not running on the live sever ? I am very new to JavaScript and programming in general so please teach me like im a 5 year old thank you.
link to code
https://code.sololearn.com/Wb0dJ50Kto9d

var canvas = document.querySelector('canvas')
canvas.height = 300
canvas.width = 300
var ctx = canvas.getContext('2d')

let player_x = 20
let player_y = 20
let base_x = Math.floor(Math.random() * 250)
let base_y = Math.floor(Math.random() * 250)

function step() {
  ctx.clearRect(0, 0, 300, 300)
  ctx.fillStyle = 'red'
  ctx.fillRect(player_x, player_y, 10, 10)
  ctx.strokeRect(base_x, base_y, 50, 50)

  if (player_x >= base_x && player_y >= base_y && player _x <= base_x + 50 && player_y <= base_y + 50)
    console.log('YOU WON') {
      let base_x = Math.floor(Math.random() * 250)
      let base_y = Math.floor(Math.random() * 250)
    }

  requestAnimationFrame(step)
}
requestAnimationFrame(step)

function handleInput(event) {
  var key = event.key
  if (key === 'a') {
    player_x -= 5
  } else if (key === 'w') {
    player_y -= 5
  } else if (key === 'd') {
    player_x += 5
  } else if (key === 's') {
    player_y += 5
  }

  document.addEventListener('keypress')
canvas {
  border: 5px solid black
}
<!DOCTYPE html>

  <title>Document</title>

Epic Square Game MK 1

    <canvas></canvas>

Score: 0

I followed a youtube video to do this as im new and just wanted to get stuck in.
https://www.youtube.com/watch?v=Z3OnwkPOfY4

A: Here are the errors:

*

*line 31: there is a space between player and _x, remove it, it should be
player_x

*line 32: the opening curly bracket should be before console.log

*line 53: you need to add a closing curly bracket to close the
function handleInput(event)

*line 55: you need to pass handleInput to addEventListener:
 document.addEventListener('keypress',handleInput)

A: There is a lot happening in your code. I understand that when learning it's easy to overlook certain aspects. So what I would recommend is to learn how to debug. In basic terms it means that whenever an error occurs you learn what the error means and how to approach it.
In this case you got this error

Uncaught SyntaxError: Unexpected token '<' Line: 1Uncaught SyntaxError: Unexpected identifier Line: 19

It ways that on line 19 there is a SyntaxError. Which means that you probably have made typing error. The token < that should not be there or is not expected. So lets check out that line.
if (player_x >= base_x && player_y >= base_y && player _x <= base_x + 50 && player_y <= base_y + 50)

It seems that you added a space at player _x which makes the next character < unexpected. Remove the space.
When fixing that another error occurs:

Uncaught SyntaxError: Unexpected token '{' Line: 20

Also a syntax error, so again probably a typo. If you look closer you'll see that the curly braces of the if statement come after the console.log('YOU WON'). You probably intended to do this:
if (yourstatement) {
  console.log('YOU WON')
}

Notice the log message inside the curly braces.
Now you've fixed this one another error occurs. Welcome to the debugging hell of JavaScript. It's hard in the beginning but if you learn from the errors you'll save yourself a lot of headaches.

Uncaught SyntaxError: Unexpected end of input Line: 45

This error tries to say. "You started something but never closed it". So look for maybe a function or code block which opens but never closes on that line. In this case it is the handleInput function.
function handleInput(event) { < opens
  ...
} < closes

Add a curly brace at the end and it is fixed.
And then, the last error.

Uncaught TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only 1 present.
  Line: 44

This one is telling you that the method addEventListener requires 2 arguments. Right now you've only giving it one. This method has to know which event to listen to and what it should do when it is fired. So add the handleInput function as the second argument and you are good to go.
document.addEventListener('keypress', handleInput);

The snippet below contains all the fixes mentioned above. Check it out and compare it with your own code.
Research your errors and learn what they mean. They sound very cryptic at first, but you'll get the hang of it.
Hope this helps you out and my explanations are coherent enough to understand.
NB Try to add semicolons to the end of each line where you call a function, declare or assign a variable. It is not mandatory to do it, but could prevent your code from breaking unexpectedly. Look in the example below to see in which places I've added the semicolons.
Edit You were on the right path to make the game reset when you win. My previous edit freezed the game whenever you won. Now the reason it wasn't resetting at first was because of the let keywords inside the if statement inside the step function.
By using let inside the if statement you declare new variables that only exist inside the if. These variables are considered as new and don't relate to the existing variables with the same name. And because you use let it can be the same name as another variable that exists globally, or in another scope.
When you remove let you use the existing base_x and base_y variables you declared earlier and give them new values.

var canvas = document.querySelector('canvas');
canvas.height = 300;
canvas.width = 300;
var ctx = canvas.getContext('2d');

let player_x = 20;
let player_y = 20;
let base_x = Math.floor(Math.random() * 250);
let base_y = Math.floor(Math.random() * 250);

function step() {
  ctx.clearRect(0, 0, 300, 300);
  ctx.fillStyle = 'red';
  ctx.fillRect(player_x, player_y, 10, 10);
  ctx.strokeRect(base_x, base_y, 50, 50);

  if (player_x >= base_x && player_y >= base_y && player_x <= base_x + 50 && player_y <= base_y + 50) {
    console.log('YOU WON');
    base_x = Math.floor(Math.random() * 250);
    base_y = Math.floor(Math.random() * 250);
  }
  requestAnimationFrame(step);
}
requestAnimationFrame(step);

function handleInput(event) {
  var key = event.key
  if (key === 'a') {
    player_x -= 5;
  } else if (key === 'w') {
    player_y -= 5;
  } else if (key === 'd') {
    player_x += 5;
  } else if (key === 's') {
    player_y += 5;
  }
}

document.addEventListener('keypress', handleInput);
canvas {
  border: 5px solid black
}
<!DOCTYPE html>

  <title>Document</title>

Epic Square Game MK 1

    <canvas></canvas>

Score: 0


text:
Q: Too much heap memory usage when reallocing Valgrind says that 42 718 bytes were allocated, however, when I see how many times the reallocation procces is called, it's 3 or 6 times and variables currentLength and currentLineLength are 10 20 30 or 10 20 30 40 50 60, so the problem isn't in the looping.
char *textInFile = (char *) calloc(currentLength + 1, sizeof(char) * currentLength);
char *currentLine = (char *) calloc(currentLength + 1, sizeof(char) * currentLineLength);
char *ptr, *ptr2;
...
while ((textInFile[index] = getc(f)) != EOF) {
    if (index >= currentLength - 2) {
        currentLength += 10;
        ptr = (char *) realloc(textInFile, currentLength);
        textInFile = (char *) calloc(currentLength, sizeof(char) * currentLength);
        free(ptr);
    }
    if (index > 0) {
        if (textInFile[index - 1] == '\n') {
            goto End;
        }
    }
    if (textInFile[index] == '\n') {
        int k = 0;
        for (int i = previousIndex; i < index; i++) {
            if (k >= currentLineLength - 2) {
                printf("\nCurrent Length: %d\n", currentLineLength);
                currentLineLength += 10;
                ptr2 = (char *) realloc(currentLine, currentLineLength);
                currentLine = (char *) calloc(currentLineLength, sizeof(char) * currentLineLength);
                free(ptr2);
            }
            currentLine[k] = textInFile[i];
            k++;
        }
        previousIndex = index + 1;
    ...
    }
    End:
    index++;
}
free(textInFile);
free(currentLine);
...

valgrind output:
==4756==
==4756== HEAP SUMMARY:
==4756==     in use at exit: 0 bytes in 0 blocks
==4756==   total heap usage: 27 allocs, 27 frees, 42,718 bytes allocated
==4756==
==4756== All heap blocks were freed -- no leaks are possible
==4756==

A: Answer:
void* calloc( size_t num, size_t size );

Calloc actually multiplies the num and size.


text:
Q: Avoid line wrap on sup element I'm trying to avoid a line wrap on a sup however the element before is a link element and I don't want the sup to be linked.  Whats the best way to force no linebreak on the last word and the sup?
My Name: *

A: You can simple use a non-breaking space   !
My Name: *

If for some reason, you don't want a space between your elements, you should wrap them both with a container using white-space property with nowrap as following :
My Name: *

(NB: inline style is used for the example only)