text:
Q: Same JavaScript for multiple instances of user control not working I am using a user control in my website which performs the functionality of auto complete textbox. I have used JavaScript for the keydown and onfocus client events. This is the code:
<script language="JavaScript" type="text/javascript">
function TriggeredKey(e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    if (keycode == 9) {
        document.getElementById("<%=pnlSearch.ClientID %>").style.visibility = 'hidden';
        document.getElementById("<%=pnlSearch.ClientID %>").style.display = 'none';
    }
    else {
        document.getElementById("<%=hdfkey.ClientID %>").value = keycode;
    }
    _dopostback();
}

function pasteIntoInput(el) {
    var text = document.getElementById("<%=txtSearch.ClientID %>").value;
    if (typeof text != "undefined" && text != "") {
        el.focus();
        el.value = el.value;
        if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
            var val = el.value;
            var selStart = el.selectionStart;
            el.value = val.slice(0, selStart) + val.slice(el.selectionEnd);
            el.selectionEnd = el.selectionStart = selStart + text.length;
        }
        else if (typeof document.selection != "undefined") {
            el.focus();
        }
    }
}

When I use a single instance of this control in my aspx page it works fine but when I use more than one instances in my aspx page the JavaScript of all of the controls is overwritten by the last instance of the control in my page and no other control works.

A: Here's how I've dealt with problems like this in the past...
A block like this goes in an external js file referenced in the control ascx.
    function UserControl() {
    }

    UserControl.prototype = {
        DoStuff : function() {
                var x = this.clientID;
                window.alert(this.pnlSearchClientID);
            },
        TriggeredKey : function(e) {
                var keycode;
                if (window.event) keycode = window.event.keyCode;
                if (keycode == 9) {
                    document.getElementById(this.pnlSearchClientID).style.visibility = 'hidden';
                    document.getElementById(this.pnlSearchClientID).style.display = 'none';
                }
                _dopostback();
            },
        pasteIntoInput : function() {
            var text = document.getElementById(this.txtSearchClientID).value;
        }
    };

A block like this goes in the ascx file:
<script type="text/javascript">
    function UserControl<%=this.ClientID%>() {
        this.pnlSearchClientID = <%=pnlSearch.ClientID%>;
        this.txtSearchClientID = <%=txtSearch.ClientID%>;
    }
    UserControl<%=this.ClientID%> = UserControl.prototype;

</script>

And then in the page including the user control:
<script type="text/javascript">
    var inst1 = new UserControl<%=instance.ClientID %>();
    inst1.DoStuff();
</script>

The idea is that you have a base class with the functionality you need, shared across all instances of the user control. Then a derived class per instance of the user control, with a new constructor setting properties for all of the instance-specific date (ie the ids of the controls composing the user control). The base class references these properties. The derived class is named using the ClientID of the user control, making it unique on the page.
I don't have access to an asp.net ATM so there are probably errors in here...

A: First off i would define your javascript functins in one place, perhaps the parent page or even a globally referenced file. That way you dont have the same functions rendered over and over again when you use multiple instances of your user control on a single page.
Then instead of embedding the client IDs of your pnlSearch and txtSearch controls into the JavaScript functions I would recommend passing them into the functions whenever they are called.
The way you have it set up the JavaScript functions on the last instance of your user control that is rendered will be the ones that will be invoked every time, which will cause the functions in the previously rendered user control instances to be ignored.


text:
Q: Android studio RC 1 what is the new gradle files is? After updating to AS RC 1 am bit confused about new gradle files, and i didn't find a resource on android developer site explaining what this new files do.

*

*bintaryv1.gradle.

*installv1.gradle.

*code_coverage.gradle.

*gradle-mvn-push.gradle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing through folders I just want to make it clear that I'm not nooby at Python, and I am fully aware on how to import files, and use 'from' to import through folders.
However I want to import through two folders, if that makes sense. Say I have a folder called 'First Folder', and inside that folder I have another called 'Second Folder', I want to import a file called 'Goal.py' which resides inside the Second Folder.
I have done a little research but could not find anything that actually answered my question.
Is it super simple, like:
 from SecondFolder from FirstFolder import Goal

or is it something else? Thanks in advance

A: You can do something like this.
from first.second import abc

But file hierarchy should be like this.
.
|-- first
    |-- __init__.py
    `-- second
        |-- abc.py
        |-- __init__.py


text:
Q: How to open text file and parse it I have the following question. On my form I write away my form with the value "76,50" as "07650". Now I want to open my file again in the listbox with the value 76,50 instead of 07650.
Public Class AddwhenOpen

Public number As Integer
Public name As String
Public Birthday As Integer
Public perc As Decimal
Public comboboxvalue As String

Public Function ToStringForPrinter() As Decimal

Return comboboxvalue & nummer.ToString.PadLeft(5) & naam.PadLeft(5) & Geboortejaar.ToString.PadRight(5) & (perc / 100).ToInt64("00,00")

End Function

Code for CLASS
`Public Class ChangeFormatBackToDecimal

Public number As Integer
Public name As String
Public Bday As Integer
Public perc As Decimal
Public comboboxvalue As String

Public Function TostringForPrinter() As String
    Return comboboxvalue & number.ToString.PadLeft(5) & name.PadLeft(5) & Bday.ToString.PadRight(5) & Format(perc / 100, "#00,00")
End Function`

Code when opening the file...
    Dim index As Integer = 0
    Dim lijn As String

    'Keuzelijst leegmaken.
    lstOutput.Items.Clear()

    With dlgOpenen
        .Filter = "textfiles (*.txt) | *.txt"
        .FileName = ""
        .InitialDirectory = "C:\My Documents"
        .Title = "Open"
    End With

    If dlgOpenen.ShowDialog = DialogResult.OK Then
        FileOpen(1, dlgOpen.FileName, OpenMode.Input)
        Do While Not EOF(1)
            line = LineInput(1)
            lstOutput.Items.Add(line)
        Loop
        FileClose(1)
    End If
    Resetdefaultvalue()

Dim data As New ChangeFormatBackToDecimal
    data.comboboxvalue = cboAfdeling.SelectedItem.ToString.PadRight(5) & cboKlasGetal.SelectedItem.ToString & cboAfdeling.SelectedItem.ToString & cboKlasLetter.SelectedItem.ToString.PadRight(5)

    data.number = CInt(txtNumber.Text)
    data.name = txtName.Text
    data.Bday = CInt(txtBday.Text)
    data.perc = CDec(txtPerc.Text)

    lstOutput.Items.Add(data)

Can someone help me?

A: To change string 76,50 instead of 07650.
Dim n as Integer = val("07650")

Dim s as String = format(s/100)

This is optional ...
s = s.Replace(".",",")
s = s.PadRight(5,"0")

ABOUT YOUR CODE :
It should be
Return comboboxvalue & nummer.ToString.PadLeft(5) & naam.PadLeft(5) & Geboortejaar.ToString.PadRight(5) & format(perc / 100,"#0.00")


text:
Q: c++ how to assign NULL value to a member pointer when creating new struct I'm writing a Run-length encoding project using linked list. Is it possible next to have value NULL every time i create a Node using new?
I have
struct Node{
    int x;
    char c;
    Node* next;
}

and
class RLElist{
private:
    Node* startList;
public:
    /*some member functions here*/
}

I need it to be NULL so i can check if I've reached the last Node of the list.

A: Yes. And as usual with something that is possible, in this case too there is more than single way to do it.

If you call a new operator with value initilization semantics
Node* n = new Node();

than value initialization will be triggered and this will assign 0 value to each structure's data member if there is no user defined constructor in the structure.

You can also define a default constructor that will assign null to pointer ( and maybe do something else as well)
struct Node{
    int x;
    char c;
    Node* next;
    Node() : next( 0) {}
}

and use this as before
Node* n = new Node();  // your constructor will be called

And finally, you can initialize pointer in the place of it's declaration
struct Node{
    int x;
    char c;
    Node* next = nullptr;
};

A: There are different options:
Add a constructor that value-initializes the pointer (which leaves it zero-initialized):
struct Node{
    Node() : next() {}  // you can also value initialize x and c if required.
    int x;
    char c;
    Node* next;
};

Initialize at the point of declaration:
struct Node{
    int x;
    char c;
    Node* next = nullptr;
};

Value-initialize the newed object:
node* Node = new Node(); // or new Node{};


text:
Q: Rendering github file data to div Need some help. I fetched the contents of a file from the Github repo. Now I want to display the contents of the file in a div element in the same way as it is displayed in the file; the indentation should be the same. Currently, the whole file is being displayed in a single line.

async function call() {
  let url = "https://api.github.com/repos/KushRohra/PythonProjects/contents/Basic_DSA_Codes/1. Two Number Sum.py";
  let response = await fetch(url);
  data = await response.json();
  s = atob(data.content)
  console.log(s);
  document.getElementById("code").innerHTML = s;
}
call();

A: You can replace all the new line characters with
 and all spaces with the corresponding number of  :

async function call() {
  let url = "https://api.github.com/repos/KushRohra/PythonProjects/contents/Basic_DSA_Codes/1. Two Number Sum.py";
  let response = await fetch(url);
  data = await response.json();
  s = atob(data.content)
  console.log(s);
  document.getElementById("code").innerHTML = s.replace(/\n/g, '
').replace(/\s/g, ' ')
}
call();


text:
Q: what will the Finalizer thread do if there is a infinite loop or deadlock in the Java finalize method what will the Finalizer thread do if there is a infinite loop or deadlock in the Java finalize method.

A: I would say that since the Java Specification doesn't tell how the finalize method must be invoked (just that it must be invoked, before the object is garbage collected), the behaviour is implementation specific.
The spec doesn't rule out having multiple threads running the process, but doesn't require it:

It is important to note that many finalizer threads may be active
  (this is sometimes needed on large shared memory multiprocessors), and
  that if a large connected data structure becomes garbage, all of the
  finalize methods for every object in that data structure could be
  invoked at the same time, each finalizer invocation running in a
  different thread.

Looking at the sources of the JDK7, the FinalizerThread keeps the queue of objects scheduled for finalization (actually objects are added to the queue by the GC, when proven to be unreachable - check ReferenceQueue doc):
private static class FinalizerThread extends Thread {
    private volatile boolean running;
    FinalizerThread(ThreadGroup g) {
        super(g, "Finalizer");
    }
    public void run() {
        if (running)
            return;
        running = true;
        for (;;) {
            try {
                Finalizer f = (Finalizer)queue.remove();
                f.runFinalizer();
            } catch (InterruptedException x) {
                continue;
            }
        }
    }
}

Each object is removed from the queue, and runFinalizer method is run on it. Check is done if the finalization had run on the object, and if not it is being invoked, as a call to a native method invokeFinalizeMethod. The method simply is calling the finalize method on the object:
JNIEXPORT void JNICALL
Java_java_lang_ref_Finalizer_invokeFinalizeMethod(JNIEnv *env, jclass clazz,
                                                  jobject ob)
{
    jclass cls;
    jmethodID mid;

    cls = (*env)->GetObjectClass(env, ob);
    if (cls == NULL) return;
    mid = (*env)->GetMethodID(env, cls, "finalize", "()V");
    if (mid == NULL) return;
    (*env)->CallVoidMethod(env, ob, mid);
}

This should lead to a situation, where the objects get queued in the list, while the FinalizerThread is blocked on the faulty object, which in turn should lead to OutOfMemoryError.
So to answer the original question:

what will the Finalizer thread do if there is a infinite loop or deadlock in the Java finalize method.

It will simply sit there and run that infinite loop until OutOfMemoryError.
public class FinalizeLoop {
    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                for (;;) {
                    new FinalizeLoop();
                }
            }
        };
        thread.setDaemon(true);
        thread.start();
        while (true);
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("Finalize called");
        while (true);

    }
}

Note the "Finalize called" if printed only once on the JDK6 and JDK7.

A: The spec writes:

Before the storage for an object is reclaimed by the garbage collector, the Java Virtual Machine will invoke the finalizer of that object.
The Java programming language does not specify how soon a finalizer will be invoked, except to say that it will happen before the storage for the object is reused.

I read this to mean that the finalizer must have completed before the storage may be reused.

The Java programming language does not specify which thread will invoke the finalizer for any given object.
It is important to note that many finalizer threads may be active (this is sometimes needed on large shared memory multiprocessors), and that if a large connected data structure becomes garbage, all of the finalize methods for every object in that data structure could be invoked at the same time, each finalizer invocation running in a different thread.

That is, finalization may occur in the garbage collector thread, in a separate thead, or even a separate thread pool.
A JVM is not permitted to simply abort executing a finalizer, and can only use a finite number of threads (threads are operating system resources, and operating systems don't support arbitrarily many threads). Non-terminating finalizers will therefore of necessity starve that thread pool, thereby inhibit collection of any finalizable objects, and cause a memory leak.
The following test program confirms this behavior:
public class Test {

    byte[] memoryHog = new byte[1024 * 1024];

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Finalizing " + this + " in thread " + Thread.currentThread());
        for (;;);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            new Test();
        }
    }
}

On Oracle JDK 7, this prints:

Finalizing tools.Test@1f1fba0 in thread Thread[Finalizer,8,system]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at tools.Test.<init>(Test.java:5)
        at tools.Test.main(Test.java:15)

A: The objects will not be "freed",  that is the memory will not be claimed back from them and also resources that are freed in the finalize method will remain reserved throughout.
Basically there is a queue holding all the objects waiting for their finalize() method to be executed. Finalizer thread picks up objects from this queue - runs finalize - and releases the object.
If this thread will be deadlocked the ReferenceQueue Queue will grow up and at some point OOM error will become inexorable. Also the resources will be hogged up by the objects in this queue. Hope this helps!!
for(;;)
{
  Finalizer f = java.lang.ref.Finalizer.ReferenceQueue.remove();
  f.get().finalize();
}


text:
Q: Rails if referrer then do issue I am trying to figure out the best way to build an if else if statement in the controller around a rails specific referrer. Is there a way to pull the last rails path and use it in the below statement?  I think I am close but totally stumped...
This is an update action that will be hit from one form at multiple locations on the site.
I am looking to replace "form_path"
def update
  @object = Milestone.find(params[:id])
    if @milestone.update_attributes(params[:milestone])
      if request.referer == form_path
        redirect_to root_path
      else
        redirect_to object2_path
      end
    else
      ....
    end
 end

A: Is form_path a variable you're defining somewhere else in the controller? Outside of understanding that, it looks like it should work.
Instead of messing with referer, you could place a hidden_field in the form based on where it's coming from, and pull that out of the params hash.
Something like:
hidden_field_tag :location, controller_name

Then in the controller:
if params[:location] == yadda yadda


text: Q: stuck with root user, can not return to normal user Although previously exited root user account via ctrl-d/ or exit, but new terminal still entered as root, how do I switch back to normal user upon new entry to terminal?


text:
Q: set autoPlay false on Flowplayer in jQuery I'm using jQuery and Flowplayer to turn links to FLV files into embedded videos like this:
$(document).ready(function() {
    if($('a[type^="video"]').length > 0) {
        $('a[type^="video"]').each(function() {
            var video_path = $(this).attr('href');
            var video_box  = $(this).parent();
            video_box.html('');
            video_box.css('width', '680px');
            video_box.css('height', '460px');
            video_box.flowplayer('/sites/default/files/flowplayer-3.2.7.swf', video_path);
        });
    }
});

This is working fine except that all the videos start playing simultaneously. I've tried adding autoPlay: false several different ways, but so far none have worked. From the documentation it seems like I should be able to do it this way:
video_box.flowplayer('/sites/default/files/flowplayer-3.2.7.swf', video_path, {clip: {autoPlay: false}});

But that doesn't work.

A: @Kevin
You don't need an extra div surrounding the flowplayer-a-tag. All you need to do is set display:block on the a-tag.
So your code can be condensed to this:
    $('a[type^="video"]').each(function(i) {
        $(this).css({'width': '680px','height': '460px','display': 'block'}).attr('id', 'player-' + i);
        var player = $f('player-' +i, '../flowplayer.commercial-3.2.7.swf', {
            clip: {
                autoPlay: false
            }
        });
    });

A: Have you tried the syntax, that is used in the documentation? In your each loop you can do:
$f(this.parentNode, {src: "flowplayer.swf"}, {
  clip: {
    url: video_path
    autoPlay: false,
    onStart: function(clip){alert("Clip "+ clip.url);}  // attach event listener
  },
});

A side note: The line if($('a[type^="video"]').length > 0) { is not necessary, because jQuery will only loop through the elements, if there are any, otherwise it just skips the block.

A: I got it to work like this:
$(document).ready(function() {
    $('a[type^="video"]').each(function(index) {
        var video_path = $(this).attr('href');
        var video_box  = $(this).parent();
        video_box.html('');
        video_box.css('width', '680px');
        video_box.css('height', '460px');
        video_box.attr('id', 'player-' + index);
        $f(video_box.attr('id'), '/sites/default/files/flowplayer-3.2.7.swf', {
            clip: {
                autoPlay: false,
                url: video_path
            }
        });
    });
});

The key to getting the $f() function to work was to give it an id. The divs I was using didn't have ids so I gave them one with the line video_box.attr('id', 'player-' + index);.
I still don't know why I couldn't get the jQuery object.flowplayer() method to accept the autoPlay: false property. But I suppose using the $f() function is just as good. Thanks for the help.

A: You can pass flowplayer an object of options, one of which is autoplay, here is the documentation for this: http://flowplayer.org/documentation/configuration/
This is an example from the above page:
flowplayer("player", {
    src: "flowplayer.swf"
}, {
    clip:  {
        autoPlay: false,
        autoBuffering: true
    }
});

Flowplayer has tons of options you can set on initialization including event bindings for things like onPause and onPlay.


text:
Q: Merging cells in Excel using Apache POI Is there any other way to merge cells in Excel using Apache POI library?
I was trying using the following, but its not working
// selecting the region in Worksheet for merging data
CellRangeAddress region = CellRangeAddress.valueOf("A" + rowNo + ":D"
            + rowNo);

// merging the region
sheet1.addMergedRegion(region);

A: The best answer
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));

A: I create a method that merge cells and put border if you want.
protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    sheet.addMergedRegion(cellMerge);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);
    }

}

protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

A: You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);
example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4)); will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).
for detail refer BusyDeveloper's Guide

A: You can use :
sheet.addMergedRegion(new CellRangeAddress(startRowIndx, endRowIndx, startColIndx,endColIndx));

Make sure the CellRangeAddress does not coincide with other merged regions as that will throw an exception.

*

*If you want to merge cells one above another, keep column indexes same

*If you want to merge cells which are in a single row, keep the row indexes same

*Indexes are zero based

For what you were trying to do this should work:
sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 0, 3));

A: syntax is:
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));

Example:
sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));

Here the cell 0 to cell 5 will be merged of the 4th row.


text:
Q: Does switching a laser on create multiple frequencies? I have been fascinated by a Sixty Symbols YouTube video on the topic of the maximum bandwidth that can be sent down an optical cable. In summary, we are informed of how a laser, which emits red light of one frequency, only does so when it is permanently on. Turning it on or off causes nature to create new frequencies which somehow facilitate the wave being there when it's on, and not when it isn't.
Since I'm a musician, I can place a loudspeaker in a medium such as air, and connect it to a sine wave generator in series with a switch. When the switch is open, no sound is generated, but close the switch and the loudspeaker outputs a sine wave. If I were to close the switch precisely when the phase was zero, surely there are no added frequencies other than the one in question which "turns the sound on", and likewise for "turning it off".
I think that this would not be the case for a sine wave at any other phase, as a 'pulse' or 'jolt' is needed to force the loudspeaker into the correct position when opening or closing the switch. I believe this causes the loudspeaker itself to generate odd harmonics for a brief period of time, as though it were being driven by the rising edge of a square wave. (That click/snap sound when attaching DC to a loudspeaker, also known as a Dirac delta function?)
I do not understand how this fits into using a laser of one frequency and sending 'pulses'. One comment on the video seemed to contradict it by asking what would happen if a filter was applied to the laser for its exact frequency, and whether that would cause the filter to always be letting light through like the laser was on, even if it was actually off.
It sounds like he's trying to describe sending the kind of pulse analogous to a square wave of sound which requires you to drive the transducer with multiple frequencies. It must be easier to detect a pulse if the amplitude ramps up quickly, but surely you're definitely not using a one frequency laser anymore to achieve that.
Q: Please can you shed some light onto how a laser being 'pulsed' actually works with respect to bandwidth used? And is the analogy with sound valid?

A:
If I were to close the switch precisely when the phase was zero,
  surely there are no added frequencies other than the one in question
  which "turns the sound on", and likewise for "turning it off".

I made more or less this same statement to the professor in one of my undergraduate EM classes.
He gently reminded me that this zero crossing switched on/off sinusoid is equivalent to the product of a genuine sinusoid (over all time, never stopping etc.) and a boxcar function.
As soon as he made that statement, I knew how to go the rest of the way since I had already studied Fourier transforms and, in particular, that (1) the Fourier transform of the product of two time domain signals is the convolution of their respective frequency domain representations and (2) the Fourier transform of the boxcar function extends over all frequencies,
Further, and simply put, a time domain signal with compact support (non-zero over a finite time) is necessarily non-zero over all frequencies.  See, for example, this answer at the Signal Processing Stack Exchange site:

In other words, a (nonzero) time-limited signal cannot be also
  band-limited. In other words, a function and its (continuous) Fourier
  transform cannot both have finite support.


text:
Q: in which array is the value I'm looking for? I have two or more than two arrays in PHP. For example:
$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];

I want to find which of these arrays contains the value 5, so that I can create the output "$array1 contains 5"

A: try this,
$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];
$f = 5;

for($n=1;$n<=3;$n++){
    if(in_array($f, ${"array" . $n})){
        echo "\$array$n contains $f";
    }
}

Edit different variable name
$zomer = [1,5,10,15,22,28];
$halil = [1,8,12,16,25,30];
$kaya= [10,15,20,21,22];
$f = 5;
$collection = compact("zomer","halil","kaya");

foreach ($collection as $key=>$val){
    if(in_array($f, $collection[$key])){
        echo "\$$key contains $f";
    }
}

A: As said @KrijnToet, it could be done easy with help of in_array() function:
if(in_array($val, $array1)) echo $val.' comes from $array1'.PHP_EOL;

Demo

A: Something along these lines may help:
feed the function findVal() with the arrays and a needle value you're looking for and it will return the name of the array(s) holding it.
<?php
$array1 = [1, 5, 10, 15, 22, 28];
$array2 = [1, 8, 12, 16, 25, 30];
$array3 = [10, 15, 20, 21, 22];

findVal([$array1, $array2, $array3], 30);

function findVal($arrays = [], $needle)
{
    foreach ($arrays as $key => $array) {
        foreach ($array as $value) {
            if ($value == $needle) {
                foreach ($GLOBALS as $arrayName => $value) {
                    if ($value === $array) {
                        echo 'value ' . $needle . ' found in : ' . $arrayName;
                    }
                }
            }
        }
    }
}

$GLOBALS — References all variables available in global scope, so we can use it to retrieve the array name(s).
demo

A: <?php

$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];

$compacted = compact('array1', 'array2', 'array3');

$needle = 21;
$found = array_filter($compacted, function($item) use ($needle) {
    return in_array($needle, $item);
});

var_export(array_keys($found));

Output:
array (
    0 => 'array3',
  )

A: Try this, using this function we can search in any number of array
$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];
$findval=5;
$arrayFinal = array('array1' =>$array1 ,'array2' =>$array2 ,'array3' =>$array3 );
function searchForId($find, $array) {
   foreach ($array as $key=> $value) {
      if(in_array($find, $value)){
         echo "\$$key contains $find";
      }
   }
}
searchForId($findval,$arrayFinal); //Call function


text:
Q: Bootstrap : affix + carousel + spy does not work correctly I develop a new website (http://learning-happly.azurewebsites.net). I try to do it with Bootstrap scripts (scrollspy, carousel, affix). But, affix doesn't works correctly in Safari and Chrome:
My page is
- Header
  - Carousel
  - #brands-menu (to affix)
- Content of landing page
as :

                …

                …

        …

    …

Result : http://learning-happly.azurewebsites.net


text:
Q: Error in uploading file to Creative Cloud iOS I am trying to upload document file on Creative Cloud in my iOS application. It was working fine but now I am getting following uploading error.
error uploading Error Domain=AdobeAssetErrorDomain Code=2 "(null)" UserInfo={AdobeNetworkResponseHeaders={
    connection = "keep-alive";
    "content-encoding" = gzip;
    "content-length" = 90;
    "content-type" = "application/vnd.adobe.error-response+json";
    date = "Sun, 23 Apr 2017 13:33:13 GMT";
    server = APIP;
    vary = "Accept-Encoding";
    "x-request-id" = "DB0C9B95-7D84-45EA-9BFF-F04020C3796E";
}, AdobeNetworkRequestURLStringKey=https://cc-api-storage.adobe.io/files/?order=asc&orderby=name, AdobeNetworkResponseData={"reason":"bad_request","message":"A required parameter is missing or invalid"}, AdobeNetworkHTTPDebugIDKey=DB0C9B95-7D84-45EA-9BFF-F04020C3796E, AdobeNetworkHTTPStatus=400}

Below is my code.
if ([AdobeUXAuthManager sharedManager].isAuthenticated)
        {
            NSLog(@"The user has already been authenticated. User profile: %@", [AdobeUXAuthManager sharedManager].userProfile);

            AdobeAssetFolder *root = [AdobeAssetFolder getRootOrderedByField:AdobeAssetFolderOrderByName
                                                              orderDirection:AdobeAssetFolderOrderDescending];

            [AdobeAssetFile create:_fileName
                          inFolder:root
                      withDataPath:[NSURL fileURLWithPath:filePath]
                          withType:kAdobeMimeTypeRaw
               withCollisionPolicy:AdobeAssetFileCollisionPolicyAppendUniqueNumber
                        onProgress:^(double fractionCompleted) {
                            NSLog(@"Percent complete %f", fractionCompleted);
                        }
                      onCompletion:^(AdobeAssetFile *file) {

                      }
                    onCancellation:NULL
                           onError:^(NSError *error) {
                               NSLog(@"error uploading %@", error);
                           }];
        }

A: I solved this problem. "AdobeCreativeSDKAssetModel.framework" was not linked with Embedded binaries. Deleting it and adding again in Embedded binaries solve this problem. You also need that you Adobe account is E-mail verified, otherwise you will get uploading error.


text:
Q: Add custom property to XAML ControlTemplate? I have a Button ControlTemplate to mimic Windows Store AppBar buttons in WPF project. It works fine. The idea is to use symbols from font Segoe UI Symbol as images. Binding is done by using two standard properties of the Button class: Content and Tag.
<Style x:Key="AppBarButton" TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid x:Name="grdRoot" Width="70" Background="Black">
                    <StackPanel VerticalAlignment="Top" Margin="0">
                        <Grid Width="40" Height="40" HorizontalAlignment="Center">
                            <Ellipse x:Name="borderCircle" Stroke="White" Fill="Black" StrokeThickness="2" />
                            <TextBlock x:Name="txtSymbol" Text="{TemplateBinding Tag}" Foreground="White" TextAlignment="Center" VerticalAlignment="Center" FontFamily="Segoe UI Symbol" FontSize="20" />
                        </Grid>
                        <TextBlock x:Name="txtContent" Text="{TemplateBinding Content}" Foreground="White" Margin="0,4,0,0" FontSize="10" TextAlignment="Center" TextTrimming="WordEllipsis"/>
                    </StackPanel>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver">
                                <Storyboard>
                                    <ColorAnimation Storyboard.TargetName="borderCircle" Storyboard.TargetProperty="(Fill).(Color)" To="Gray" Duration="0" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ColorAnimation Storyboard.TargetName="borderCircle" Storyboard.TargetProperty="(Fill).(Color)" To="White" Duration="0" />
                                    <ColorAnimation Storyboard.TargetName="txtSymbol" Storyboard.TargetProperty="(Foreground).(Color)" To="Black" Duration="0" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ColorAnimation Storyboard.TargetName="borderCircle" Storyboard.TargetProperty="(Stroke).(Color)" To="Gray" Duration="0" />
                                    <ColorAnimation Storyboard.TargetName="txtSymbol" Storyboard.TargetProperty="(Foreground).(Color)" To="Gray" Duration="0" />
                                    <ColorAnimation Storyboard.TargetName="txtContent" Storyboard.TargetProperty="(Foreground).(Color)" To="Gray" Duration="0" />
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The problem is that many expected symbols are missing in the font. It seems that they often are defined only once and the corresponding rotated symbols are expected to be generated by transformation.
An example:
The ArrowUp is defined in character xE110. But there is no corresponding ArrowDown!
I know it is possible to apply a RotateTransform with Angle="180" to a TextBlock. It works when applied directly to the TextBlock. But if applied to the button it will of course turn the whole template content upside down, including the text. How can I apply the transformation from OUTSIDE my ControlTemplate if the TextBlock is hidden deep inside the control hierarchy?
My suggestion is to apply a custom property ImageAngle to the ControlTemplate that can be bound to the inner Angle property. If possible the ImageAngle should have a Default value of "0" so that I don't need to specify it for all normal symbols. Unfortunately my XAML template knowledege is not deep enough to figure this out myself.
<TextBlock x:Name="txtSymbol" Text="{TemplateBinding Tag}" Foreground="White" TextAlignment="Center" VerticalAlignment="Center" FontFamily="Segoe UI Symbol" FontSize="20" RenderTransformOrigin="0.5,0.5" >
    <TextBlock.RenderTransform>
        <TransformGroup>
            <ScaleTransform/>
            <SkewTransform/>
            <RotateTransform Angle="{TemplateBinding ImageAngle}"/>
            <TranslateTransform/>
        </TransformGroup>
    </TextBlock.RenderTransform>
</TextBlock>

Other suggestions to solve the problem are also welcome.


text:
Q: Unable to connect to docker postgres with password I am trying to connect to a locally running postgres on docker.
I am running the basic tutorial initialization:
docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

when I try: pgcli -h localhost -U postgres postgres I get password denied. I have also tried with pguser. I have also tried setting the username as well with the same result.
When I try with a generic database application, DBeaver, same result password denied.
I have tried going in to the running container and resetting the password as well: docker exec -it <hash> bash and then manually setting the password again to something simple.

A: I was getting a similar error with port 5432 (default) and I had a local postgres installation too, which is creating the problem. To avoid the two instances fighting for same port, two things can be done.

*

*Stop instance of local postgres

*In docker container postgres path, open postgresql.conf and change default port.

A: I faintly remember postgresql to
a) have a different password for a postgresql account than the one you have to set for the linux user account and
b) having to activate logging in with a username and password somewhere in the config
Hope this helps, just something off the top of my head


text:
Q: Why doesn't my html parser download the entire html documentation? I am using Beautiful Soup to scrape the following page: https://www.nyse.com/quote/XNYS:AAN
I want to the stock value below the name + abbreviation. However, when I run a script, it seems that soup.find() does not work because the entire html file is not being downloaded.
main_url = "https://www.nyse.com/quote/XNYS:AAN"

import requests
result = requests.get(main_url)

from bs4 import BeautifulSoup
soup = BeautifulSoup(result.text, 'html.parser')

print(soup.find("div", class_ = "d-dquote-symbol").prettify())

I expect to see the <div> that contains the <span> with the correct stock value. However, the print returns "none" because the script cannot find this tag. I know it exists because I used inspect element to find the tag in the first place.

A: This happens because the page you're scraping is not static.
you can see that it has a "spinner" before displaying the values, or by inspecting the network tab in your browser's debug tools.
requests.get doesn't make any "follow-up" requests so you only get the empty page.
to get the stock value (by HTML scraping...) you should use the request the site itself uses to get the stock value.
NOTE: it is better to look for an official API to get this kind of structured data.

A: You can use any browser simulator to get the quote. pyppeteer can be a good choice to do the trick. The script will wait for the quote to be available and then parse it.
import asyncio
from pyppeteer import launch

url = "https://www.nyse.com/quote/XNYS:AAN/QUOTE"

async def get_quote(link):
    wb = await launch()
    page = await wb.newPage()
    await page.goto(link)
    await page.waitForSelector(".d-dquote-bigContainer [class^='d-dquote-x']")
    container = await page.querySelector(".d-dquote-bigContainer [class^='d-dquote-x']")
    quote = await page.evaluate('(element) => element.innerText', container)
    print(quote)

asyncio.get_event_loop().run_until_complete(get_quote(url))

Output at this moment:
60.09


text:
Q: wxWidget 2.8.12 not working in Codeblocks I'm learning to use wxWidget 2.8.12 with Codeblocks 12.11. I have followed the instructions on this site to install wxWidgets and Codeblocks:
http://wiki.codeblocks.org/index.php?title=WxWindowsQuickRef
When I try to create the project and run the demo app I get the error:
fatal error: wx/setup.h: No such file or directory

The following picture will show this better:

I have followed the instructions, but still I get the error...what seems to be the problem? :(
Thnx for any help
P.S.
Here is an overview what I have done:
1) I downloaded Codeblocks including MinGW (codeblocks-12.11mingw-setup.exe)
http://www.codeblocks.org/downloads/26#windows and I have installed them using the .exe file
2) I have edited my User PATH environment variable to according to the reference page I have used
3) I have downloaded wxWidgets installer from this link and installed it:
http://sourceforge.net/projects/wxwindows/files/2.8.12/wxMSW-2.8.12-Setup.exe/download?use_mirror=garr
4) I have entered the directory C:\<wxWidgets root>\build\msw and inputted the following command in command prompt:
mingw32-make -f makefile.gcc BUILD=release SHARED=1 MONOLITHIC=1 UNICODE=1 CXXFLAGS=-fno-keep-inline-dllexport

After letting wxWidgets build and trying to run my demo app I get the error I mentioned in Codeblocks :(
NOTICE FUTURE READERS: Install wxWidgets to a directory without whitespace in the path name! Otherwise this will cause trouble

A: Please have a look at the Below Link which i have put.It will be very useful.I have also installed wxWidget 2.8.12 with Codeblocks 12.11 using This Link.
Setting up wxWidgets(2.9.4) with Code::Blocks(12.11) in Windows
Type These below steps in Command Prompt after you finish installing the wxWidgets2.8.12 and CODEBLOCKS 12.11.
gcc -v
mingw32-make -v
cd /D C:\wxWidgets-2.8.12\build\msw
mingw32-make -f makefile.gcc clean
mingw32-make -f makefile.gcc BUILD=debug SHARED=0 MONOLITHIC=1 UNICODE=1
mingw32-make -f makefile.gcc BUILD=release SHARED=0 MONOLITHIC=1 UNICODE=1

*

*If the problem still persists after doing all the above steps then You're missing an important compiler search path in your build options.

*Make sure you choose the correct wxWidgets build configuration when running the wxWidgets project wizard.

*If re-running the wizard isn't an option, then open your project's build options and add "$(#wx.lib)\gcc_dll\mswu" (assuming a monolithic Unicode DLL build) to the compiler search paths.


text:
Q: Functions are not appearing while using TFilterRow in Talend I am using a tFilterRow to avoid empty rows. While trying to use it I am getting only one function value 'absolute value'.

I want to filter values with a length greater than 0.
Why I am not getting any other functions?

A: As mentioned in the comments, the length function is only available to schema columns that have the String data type.
To filter out any rows that have a null value in a column you can use a tFilterRow but configured so that the column being checked is not equal to null like so:

In the case you are dealing with the primitive int (rather than the Integer class) then the primitive can never be null and instead defaults to 0 so you'll want to set it as not equal to 0 instead.


text:
Q: Use ref with and height I was wondering how to get useRef width and height on load and when it changes.
I am trying to pass the exact dimensions of a component to its child.
MapContainer.js
const mapComponent = useRef(null);
const [mapWidth, setMapWidth] = useState(0);
const [mapHeight, setMapHeight] = useState(0);

useEffect(() => {
    if (mapComponent.current !== null) {
      setMapWidth(mapComponent.current.clientWidth);
      setMapHeight(mapComponent.current.clientHeight);
    }
  }, [mapComponent]);

<div className={`bg-white rounded-[32px] overflow-hidden relative`} ref={mapComponent}>
   <Map
     style="mapbox://styles/ayagoumi/ckyvm0dx5001714mplg2y1oz7"
     zoom={zoom}
     center={position}
     movingMethod="easeTo"
     containerStyle={{
       height: `${mapHeight}px`, // this is what i want to change
       width: `${mapWidth}px`, // this is what i want to change
       borderRadius: "32px",
       zIndex: "0",
       overflow: "hidden",
     }}
   >
   </Map>

Index.js

       <MapContainer styles="w-full md:!w-[50%] lg:w-full min-w-[300px] min-h-[300px] order-2 rounded-[32px] overflow-hidden"></MapContainer>

But this approach that I took is not getting me the width and height when parent width changes

A: To get the new width and height after resizing, you need to listen to resize event of window, as example:
const Map = () => {
  const mapComponent = useRef(null);
  const [mapWidth, setMapWidth] = useState(0);
  const [mapHeight, setMapHeight] = useState(0);

  const onResize = () => {
    const rect = mapComponent.current.getBoundingClientRect();
    if (rect) {
      setMapWidth(rect.width);
      setMapHeight(rect.height);
    }
  };

  useEffect(() => {
    onResize();
    window.addEventListener('resize', onResize);
  }, []);

  return (

      <Child width={mapWidth} height={mapHeight}>A</Child>
      <Child width={mapWidth} height={mapHeight}>B</Child>
      <Child width={mapWidth} height={mapHeight}>C</Child>
      <Child width={mapWidth} height={mapHeight}>D</Child>

  );
};


text:
Q: Get Photos and Detailed Info for Many Foursquare Venues in one call I am working on an iPhone app which allows users to search Foursquare. I am using the venues/explore endpoint for the search which works great, but the results don't include the images for a place or the priceTier.
Right now I am calling /venues/VENUE_ID for each of the returned results, which is generating a lot of API calls. Is there a better way to get this info in a single call?
Related question: If I use the multi endpoint to batch these requests, does that count as a single request towards the limit or as multiple requests?

A: Sounds like you're worried about limits more than network latency? If you're worried that making the extra call to details will make you hit rate limits faster, this is actually why we generally ask developers to cache details such as prices or photos :) A single multi request is not a single API call; it counts as how many requests are bundled into one.
There is a little help with photos though—if you pass in the venuePhotos=1 param as part of an explore request, you ought to get back photos in the response.


text:
Q: Return of FFMPEG in Background I am making a code that downloads a list of m3u8 links by FFMPEG
I had this code:
function FFMPEG($videocode, $dirvideo) {

    $ffmpeg = '"D:\FFMPEG\bin\ffmpeg.exe"' . " -hide_banner -loglevel verbose -n -i https://linkplaylist/{$videocode}.m3u8 -map 0:1 -map 0:2 -acodec copy -bsf:a aac_adtstoasc -vcodec copy {$dirvideo} 1> log.txt  2>&1";

    exec($ffmpeg, $output, $var);

    return $var;
}

$code = FFMPEG('football', 'football.mp4');

if($code){
    {ERROR CODE};
    }else{

    {SUCCESS CODE}
}

Initial problem
And that worked well. I could download the video and know if it was downloaded completely or had some error.
The problem is that this code "hangs" the script in exec () the page is loading until finalize exec () and that of timeout error (shared server) besides being visually strange to the visitor the page loading.
Resolution of the initial problem
After research I think the solution is to put the code execution in the background so I found this code:
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "error-output.txt", "a") // stderr is a file to write to
);

function FFMPEG($videocode, $dirvideo) {
$cmd = 'start /B D:\FFMPEG\bin\ffmpeg.exe  -y -i "https://linkplaylist/{$videocode}.m3u8" -map p:0 -acodec copy -bsf:a aac_adtstoasc -vcodec copy {$dirvideo}';
proc_close(proc_open ($cmd
,$descriptorspec, $foo));
}

And finally my current problem
And this works fine for the loading and timeout issue, but I can not get a return from when the download was successfully completed.
1 ° proc_open Is this the best solution for my initial problem?
2 ° How can I get a return from when ffmpeg finishes running successfully and the script continues to flow.
Extra Info
I'm trying to build a solution that works on windows (xampp) but my final server is linux.

A: I'm having the same challenge, and hopefully someone can complete my contribution.
This is only a partial answer that I don't know how to complete for Windows.  The trick is in the pipes apparently, per the ffmpeg wiki, but the solution is for Unix:

One more thing to take care about is the standard INPUT (stdin).
  Command-line ffmpeg tool is designed as an interactive utility that
  accepts user's input (usually from keyboard) and reports the error log
  on the user's current screen/terminal. When we run ffmpeg in the
  background, we want to tell ffmpeg that no input should be accepted
  (nor waited for) from the stdin. We can tell this to ffmpeg, using I/O
  redirection again "

I tried using the -nostdin, but it had no effect.


text:
Q: Provisioning Profile, Certificate is not listing in xcode 6.2 When I click on Code Signing Identity or Provisioning Profile, It gives me popup that says to enter value..

Check above Image, How to solve this???
Is it bug in xcode 6.2?
Bellow is account which has provisioning profile...

I have tried following things..
2 time restared mac
3 time restared xcode
tried on xcode 6.2 and 5.1
EDIT
I have tried Following all things.

*

*Refreshing Account

*Removed Account from Preference, Restart Xcode, Add Account again

*Removed All Certificates, Provisioning profile from Keychain Access, Removed Account from xcode, Removed All Certificates from portal. Recreated Certificates and Provisioning profile, Downloaded it again

*Removed All Certificates, Provisioning profile from Keychain Access, Removed Account from xcode, Removed All Certificates from portal. Recreated Certificates and Provisioning profile, Downloaded it again
I have Team Member Developer Account..
If I am missing anything to add here let me know..

A: Adding your Profile by typing "iPhone Developer" does not make sense.
Do the following steps:

*

*go to the Apple Member Center and download all certificates and provisioning profiles

*save them somewhere you can access theme like on desktop

*double-click all of them, certificates and profiles

*this will bring up Xcode and the Keychain

*close Keychain as you won't need it anymore

*in Xcode, go to Build Settings to verify the profiles were added correctly

*set the Developer Code Signing Identity to your profile

Everything should work now.
Hope that helps :)

A: You must open the provisioning profile with xCode to be able to see it in the menu. Also, be sure that your Developer certificate's are in your keychain. If nothing else, try revoking them in your portal and recreate them.

A: Follow these steps :-
Xcode -> Preferences -> Accounts -> click on your Apple ID -> Click View Details -> click on your projects Provisioning Profile -> click the refresh button bottom left.


text:
Q: File audit in Linux: how to watch directory tree for deletions? I have a forum script running on server and somehow small number of attachments begin to get lost. I want to find out what is deleting them and at what time. How can I setup Linux auditd (auditctl) to watch directory tree (attachments are stored inside multi-level directory tree) to watch for file deletions there?
May be I should use some other tool for this?

A: This is an answer i wrote to a previous question:

Generally if you wish to know what a process/user/file is doing without
  having to run lsof against it 24/7 you
  use auditctl.
Assuming you have a recent-ish kernel
  audit control should be a simple
  operation. (This is in Debian-fu, if
  you're running Red Hat translate as
  appropriate)
# apt-get install auditd

Make sure that its running
  (/etc/init.d/auditd status).
auditctl -a entry,always -F arch=b64 -S open -F pid=<process id>

Replace b64 with b32 if you're running
  32-bit arch, open can be replaced by
  any system call or the word 'all'
For more read the auditctl manpage.

You can use this method and ask it to watch for the 'unlink' system call.
The -w parameter is useful for watching files/directories, but the as the man page explains there are caveats.
-w path
Insert a watch for the file system object at path. You cannot insert a watch to the    top level directory. This is prohibited by the kernel. Wildcards are not supported either and will generate a warning. The way that watches work is by tracking the inode internally. This means that if you put a watch on a directory, you will see what appears to be file events, but it is really just the updating of meta data. You might miss a few events by doing this. If you need to watch all files in a directory, its recommended to place an individual watch on each file. Unlike syscall auditing rules, watches do not impact performance based on the number of rules sent to the kernel.

A: Maybe incron could be used?

A: While fenix's auditd recommendation seems ideal, you may find a filesystem IDS such as AIDE helpful.  Unfortunately, it's unlikely to be fine-grained enough for what you're attempting to isolate.
I'll often write scripts as a solution for problems like what you describe.  If you cannot accomplish what you want with solutions recommended, write something yourself.  It's often not very complicated.

A: A couple of ideas. You can use strace to see what your application is doing, but it may generate a log of logs and may slow down the system.
Another idea is to use inotifywait, then lsof/fuser on the file to see what is using it. You can try run this script at high priority (if you can) to have information as accurate as possible. It will probably not catch the unlink call, since the file will be gone before the event is delivered.


text:
Q: Hybrid Django Application - REST API Authentication I am new to Django and have built a basic application (Django 3.1) which uses session authentication and a simple login page (username + password) to login a django user. It works fine. I would like to use javascript (vue.js) on pages accessible to the logged in user to call Django REST APIs, hosted on the same Django application.
Despite lots of googling, no one seems to give a clear authentication example of a hybrid Django app, augmented with APIs. I have used lots of APIs before so am familiar with the authentication options. My issue is how to get credentials to the javascript loaded by django templates in a secure manner.
IDEALLY I would like:

*

*User logs in with username/password

*django redirects to PAGE B, AUTOMAGICALLY SOMEHOW inserting user's token into a cookie/sessionStorage

*A javascript function on PAGE B gets credentials from cookie/sessionStorage and calls API (using all the various options supported by django-rest-framework)

My Questions:
Question 1 ==> in my do_login view function (below), after successful authentication with Djangos inbuilt login method, do I need to create a cookie in HttpResponse (e.g. token=XXXXXXX), so javascript can access it? Is this secure?
    def do_login(request):
       ....
       login(request, user)
       ...
       #create token here and return to user somehow in cookie/sessionStorage
       return render(request, 'hello/logged_in_ok.html')

So my javascript can do something like this (demo code only):
function onButtonClick(){
    let token = sesssionStorage.getItem("django_gave_me_this_token");
    let response = callGetAPISomehow(token, "https://demo/rest/api/account/1")
    .....
}

Question 2 ==> Most view methods finish up with:
    return render(request, 'blah/blah.html', {'data': blah})

How do I set the cookie in the response this way? There is no response object to access.
All help appreciated


text:
Q: R quantmod chartseries shifting a moving average to the left and right library(quantmod)
getSymbols("SPY", from="2013-01-01", to=Sys.Date())
chartSeries(SPY, TA="addSMA(20)")

Is there a way of shifting a moving average to the left and right?

A: lag is key here
s <- get(getSymbols('SPY'))
sma <- SMA(Cl(s),20)

chart_Series(s ,subset="2013::")
add_TA(sma , on = 1)
add_TA(lag(sma,10) , on = 1 , col ='red')
add_TA(lag(sma,-10) , on = 1 , col = 'blue')

outcome


text:
Q: Get pixel count according to a shapefile's identity I have a raster that has 5 classes and a polygon shapefile with 10 rows.
This is the raster:

This is the shapefile with various shapes

I want to get the pixel count

*

*by classes - 5

*by identity (there are 10 in the shapefile).

A: Tabulate Area will work for this. Shown below, is the result when I used the ROI feature class as the feature zone data, OBJECTID as the zone field, and Raster as the input raster. The result is a table that identifies the area per raster value per ROI area.
To determine the number of cells, you would need to divide the values in the Tabulate Area table by the area of the cells within your raster. For example, dividing 47.57 by 5.95 (the area of my raster cells) is 8, which is the number of raster cells with the value of 2 in the ROI where OBJECTID is 12.


text:
Q: Why is xCode asking for Android Studio Gradle files? I had to delete Android Studio off my MacBook Air to free up space for an xCode update. Now xCode is complaining its missing Android Studio files that have nothing to do with it but are somehow titled

file:///Users/administrator/Documents/Retrographic/Sprocket/Android/Gradle%20Binaries/gradle-2.2.1/lib/plugins/xbean-reflect-3.4.jar: warning: Missing file: /Users/administrator/Documents/Retrographic/Sprocket/Android/Gradle Binaries/gradle-2.2.1/lib/plugins/xbean-reflect-3.4.jar is missing from working copy

What the heck is this and how do I fix it? I tried re-downloading the branch in SourceTree and pointing xCode at it but its still having the same problem. Do I need to just nuke and re-install xCode?
:(

A: This seems very unusual...
My best guess would be to go through your various build settings in your project targets and ensure that this file isn't listed under anything for linking, building, etc.
If it is, delete it, provided you don't need it for your XCode project.

A: This error occurs as that file was under your version control system such as git and now it is removed. xcode checks the status of git and complains if a file was removed. You can go to your version control system and commit this change so that xcode doesn't complain. If you are using git, you can do the following:

*

*git status
--> This should tell the file was removed

*git commit ...

A: Some possible solutions.
Solution 1

*

*Open your xcodeproj/project.pbxproj in a text editor

*Search for "xbean".

*Remove that line.

Solution 2
If you are using an xcworkspace, there may be some other project that is including that file. In that case, I'd do that for all project files. If that is infeasible, do a grep grep -r xbean . and then edit the named files. This command will recursively search for all files mentioning this particular file.

A: I'm not sure why is this happening, but i think there might be some file references in your project which are no more existing.
You can try this:
Search and delete missing files.


text:
Q: How to render only an embedded table after removing a row - search expression problem I've one table embedded into another table. My problem: How to render only the inner table when a row was removed?
Bean:
@Named
@ViewScoped
public class TestBean implements Serializable {
    private static final long serialVersionUID = -5633666299306108430L;
    private List<String> strLst1;
    private List<String> strLst2;

    @PostConstruct
    public void init() {
        strLst1 = Arrays.asList("a", "b", "c");
        strLst2 = Arrays.asList("d", "e", "f");
    }

    public List<String> getStrLst1() {
        return strLst1;
    }

    public List<String> getStrLst2() {
        return strLst2;
    }

    public void removeFromStrLst2(String val) {
        strLst2.remove(val);
    }
}

Facelet:
<!DOCTYPE html>
<html
  xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
  xmlns:h="http://xmlns.jcp.org/jsf/html"
  xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
  xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
</h:head>
<h:body>
  <h:form id="form">
    <h:dataTable
      id="outerTable"
      var="str1"
      value="#{testBean.strLst1}"
      border="1">
      <h:column>
        <h:panelGroup id="innerTableContainer">
          <h:dataTable
            id="innerTable"
            var="str2"
            value="#{testBean.strLst2}"
            border="1">
            <h:column>
              <h:outputText value="#{str1}: #{str2}" />
            </h:column>
            <h:column>
              <h:commandButton
                id="removeButton"
                action="#{testBean.removeFromStrLst2(str2)}"
                value="RemoveFromStrLst2">
                <f:ajax render="innerTableContainer" /> <!-- Problem location -->
              </h:commandButton>
            </h:column>
          </h:dataTable>
        </h:panelGroup>
      </h:column>
    </h:dataTable>
  </h:form>
</h:body>
</html>

My problem is the Ajax-render attribute which doesn't get the correct id (examples for the first row):
innerTableContainer leads to mojarra.ab(this,event,'action',0,'innerTableContainer') It doesn't work!
innerTable leads to mojarra.ab(this,event,'action',0,'form:outerTable:0:innerTable:0') It doesn't work!
@parent leads to mojarra.ab(this,event,'action',0,'form:outerTable:0:innerTable:0:j_idt14') It doesn't work!
@namingcontainer leads to mojarra.ab(this,event,'action',0,'form:outerTable:0:innerTable:0') It doesn't work!
@form works but this isn't I was looking for.
The correct and working id would be form:outerTable:0:innerTableContainer but how to get it?
Mojarra 2.3.9.SP01


text:
Q: how to tell the compiler that a loop can be safely parallelized? I'm updating a few elements in a large array.
The updates consists of:

*

*multiplying the current value by ten (if it's not zero)

*clearing the current value

*moving the updated value to a new position in the array

I know there will be no collision when a move occurs.
How can I tell the compiler that it can safely parallelized the loop?
do i = 1, 1e6
    if ( v[i] /= 0 ) then
        temp = v[i] * 10
        v[i] = 0
        ndx = get_move_to_ndx(i)
        v[ndx] = temp
    end if
end do

I'm on ifort, but I guess this is compiler independent.

A: Here is a mongrel approach, so you have some ideas using temporary vectors. The WHERE may not be correct, you would have to try it. The Main advantage of WHERE/ELSEWHERE is readability, as it is usually not as fast as loops... Just easier to read.
!DIR$ SIMD
FillTemp: Do I = 1, 1000000
  Temps(I) = v(I)*10
ENDDO FillTemp

!$OMP PARALLEL DO
FindIndex: Do I = 1, 1000000
  ndx_vect(I) = get_move_to_ndx(i)
ENDDO FindIndex

WHERE( Temps /= 0 )
  V = 0
ELSEWHERE
  v(ndx_Vect) = tempz
ENDWHERE


text:
Q: Rails Engine проблема интеграции с gem draper В Rails Engine приложении необходимо подключить gem draper. После выполнения всех инструкций по докам, а именно:
После установки гема и выполнения команды rails generate decorator создаю декоратор:
class OrderDecorator < Draper::Decorator
  delegate_all

  delegate :hide_part_number, :expiration_date, to: :credit_card, prefix: true

  decorates_association :credit_card
  decorates_association :shipping_address
  decorates_association :billing_address
  decorates_association :order_items

end

При запуске приложения разит ошибку
Мой engine_name.gemspec.rb
s.add_dependency "rails", "~> 5.0.0", ">= 5.0.0.1"
  s.add_dependency 'aasm', '~> 4.10', '>= 4.10.1'
  s.add_dependency 'wicked', '~> 1.3'
  s.add_dependency 'haml', '~> 4.0', '>= 4.0.7'
  s.add_dependency 'bootstrap-sass', '~> 3.3', '>= 3.3.6'
  s.add_dependency 'draper', '~> 2.1'
  s.add_dependency 'activesupport-decorators', '~> 1.0'

  s.add_development_dependency 'pg'

На одном из сайтов нашел совет как побороть эту проблему, но к сожалению не помогло:
Там советую добавить в engine.rb
config.to_prepare do
      Dir.glob(Rails.root + 'app/decorators/**/*_decorator*.rb').each do |c|
        require_dependency(c)
      end
    end

Но это ничего не изменило.

A: В контроллере, когда декорируте коллекцию или объект (например, @orders) укажите класс декоратора явно при помощи опции with
class ShoppingCard::OrdersController < ActionController::Base
  ...
  decorates_assigned :orders, with: OrderDecorator
  ...


text:
Q: ¿Cómo acceder a las propiedades del store? No logro acceder a las props del state, lo que intento hacer es que muestre o no una barra de navegación en función de si una propiedad esta en false o true.
Cuando intento acceder a la propiedad showMainHeader de esta forma this.props.config.showMainHeader me da el siguiente error:
Property 'config' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>', no se si tengo que declararlo de alguna forma antes.El console log muestra lo siguiente por si es de utilidad: {config: {…}, dispatch: ƒ}
config: {moduleId: 'HOME_MODULE', showMainHeader: false, showDetailHeader: true, detailTitle: 'Actualidad!'}
dispatch: ƒ (action)
[[Prototype]]: Object

import React, { Component } from 'react'
import { Fragment } from 'react'
import { Disclosure, Menu, Transition } from '@headlessui/react'
import { Bars3Icon, BellIcon, XMarkIcon } from '@heroicons/react/24/outline'
import { connect } from 'react-redux'

const navigation = [
  { name: 'Inicio', href: '#', current: true },
  { name: 'Colegio', href: '#', current: false },
  { name: 'Documentos', href: '#', current: false },
  { name: 'Mi perfil', href: '#', current: false },
]

function classNames(...classes) {
  return classes.filter(Boolean).join(' ')
}

function mapStateToProps(state) {
    const { configNavigation } = state
    return { config: configNavigation }
  }

  class  Navigation extends Component {
      constructor (props) {
        super(props);
        this.state = { config: {} };
    }

    render () {
        console.log(this.props);
    return (

                        {/* Phone logo */}
                        {/*  */}
                        {/* Desktop logo */}

                                        <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-home mx-2 stroke-neutral-500 hover:stroke-teal-600" width="20" height="20" viewBox="0 0 24 24" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                                            <polyline points="5 12 3 12 12 3 21 12 19 12" />
                                            <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7" />
                                            <path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6" />
                                        </svg>
                                    Inicio

                                        <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-building-skyscraper mx-2 stroke-neutral-500 hover:stroke-teal-600" width="20" height="20" viewBox="0 0 24 24" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                                            <line x1="3" y1="21" x2="21" y2="21" />
                                            <path d="M5 21v-14l8 -4v18" />
                                            <path d="M19 21v-10l-6 -4" />
                                            <line x1="9" y1="9" x2="9" y2="9.01" />
                                            <line x1="9" y1="12" x2="9" y2="12.01" />
                                            <line x1="9" y1="15" x2="9" y2="15.01" />
                                            <line x1="9" y1="18" x2="9" y2="18.01" />
                                        </svg>
                                    Colegio

                                        <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-files mx-2 stroke-neutral-500 hover:stroke-teal-600" width="20" height="20" viewBox="0 0 24 24" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                                            <path d="M15 3v4a1 1 0 0 0 1 1h4" />
                                            <path d="M18 17h-7a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h4l5 5v7a2 2 0 0 1 -2 2z" />
                                            <path d="M16 17v2a2 2 0 0 1 -2 2h-7a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h2" />
                                        </svg>
                                    Documentación

                                        <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-user mx-2 stroke-neutral-500 hover:stroke-teal-600" width="20" height="20" viewBox="0 0 24 24" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                                            <circle cx="12" cy="7" r="4" />
                                            <path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" />
                                        </svg>
                                    Mi perfil

                                <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-brand-twitter" width="20" height="20" viewBox="0 0 24 24" stroke-width="1" stroke="#ffffff" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                                    <path d="M22 4.01c-1 .49 -1.98 .689 -3 .99c-1.121 -1.265 -2.783 -1.335 -4.38 -.737s-2.643 2.06 -2.62 3.737v1c-3.245 .083 -6.135 -1.395 -8 -4c0 0 -4.182 7.433 4 11c-1.872 1.247 -3.739 2.088 -6 2c3.308 1.803 6.913 2.423 10.034 1.517c3.58 -1.04 6.522 -3.723 7.651 -7.742a13.84 13.84 0 0 0 .497 -3.753c-.002 -.249 1.51 -2.772 1.818 -4.013z" />
                                </svg>

                                <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-brand-youtube" width="20" height="20" viewBox="0 0 24 24" stroke-width="1" stroke="#ffffff" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                                    <rect x="3" y="5" width="18" height="14" rx="4" />
                                    <path d="M10 9l5 3l-5 3z" />
                                </svg>

                                <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-brand-instagram" width="20" height="20" viewBox="0 0 24 24" stroke-width="1" stroke="#ffffff" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                                    <rect x="4" y="4" width="16" height="16" rx="4" />
                                    <circle cx="12" cy="12" r="3" />
                                    <line x1="16.5" y1="7.5" x2="16.5" y2="7.501" />
                                </svg>

                                <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-brand-facebook" width="20" height="20" viewBox="0 0 24 24" stroke-width="1" stroke="#ffffff" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                                    <path d="M7 10v4h3v7h4v-7h3l1 -4h-4v-2a1 1 0 0 1 1 -1h3v-4h-3a5 5 0 0 0 -5 5v2h-3" />
                                </svg>

                {/* Navegación móvil */}

                {
                   this.props.config.showMainHeader === false ?

                        <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-home mx-2 h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="#737373" fill="none" stroke-linecap="round" stroke-linejoin="round">
                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                            <polyline points="5 12 3 12 12 3 21 12 19 12" />
                            <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7" />
                            <path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6" />
                        </svg>
                        Inicio

                        <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-building-skyscraper mx-2 h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="#737373" fill="none" stroke-linecap="round" stroke-linejoin="round">
                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                            <line x1="3" y1="21" x2="21" y2="21" />
                            <path d="M5 21v-14l8 -4v18" />
                            <path d="M19 21v-10l-6 -4" />
                            <line x1="9" y1="9" x2="9" y2="9.01" />
                            <line x1="9" y1="12" x2="9" y2="12.01" />
                            <line x1="9" y1="15" x2="9" y2="15.01" />
                            <line x1="9" y1="18" x2="9" y2="18.01" />
                        </svg>
                        Colegio

                        <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-files mx-2 h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="#737373" fill="none" stroke-linecap="round" stroke-linejoin="round">
                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                            <path d="M15 3v4a1 1 0 0 0 1 1h4" />
                            <path d="M18 17h-7a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h4l5 5v7a2 2 0 0 1 -2 2z" />
                            <path d="M16 17v2a2 2 0 0 1 -2 2h-7a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h2" />
                        </svg>
                        Documentación

                        <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-user mx-2 h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="#737373" fill="none" stroke-linecap="round" stroke-linejoin="round">
                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                            <circle cx="12" cy="7" r="4" />
                            <path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" />
                        </svg>
                        Mi perfil

                :

                    <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-home mx-2 h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="#737373" fill="none" stroke-linecap="round" stroke-linejoin="round">
                        <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                        <polyline points="5 12 3 12 12 3 21 12 19 12" />
                        <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7" />
                        <path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6" />
                    </svg>
                    Inicio

                    <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-building-skyscraper mx-2 h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="#737373" fill="none" stroke-linecap="round" stroke-linejoin="round">
                        <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                        <line x1="3" y1="21" x2="21" y2="21" />
                        <path d="M5 21v-14l8 -4v18" />
                        <path d="M19 21v-10l-6 -4" />
                        <line x1="9" y1="9" x2="9" y2="9.01" />
                        <line x1="9" y1="12" x2="9" y2="12.01" />
                        <line x1="9" y1="15" x2="9" y2="15.01" />
                        <line x1="9" y1="18" x2="9" y2="18.01" />
                    </svg>
                    Colegio

                    <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-files mx-2 h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="#737373" fill="none" stroke-linecap="round" stroke-linejoin="round">
                        <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                        <path d="M15 3v4a1 1 0 0 0 1 1h4" />
                        <path d="M18 17h-7a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h4l5 5v7a2 2 0 0 1 -2 2z" />
                        <path d="M16 17v2a2 2 0 0 1 -2 2h-7a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h2" />
                    </svg>
                    Documentación

                    <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-user mx-2 h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="#737373" fill="none" stroke-linecap="round" stroke-linejoin="round">
                        <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                        <circle cx="12" cy="7" r="4" />
                        <path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" />
                    </svg>
                    Mi perfil

                }

    )
   }
}

export default connect(mapStateToProps)(Navigation)

A: Creo que estas configurando de forma incorrecta el connect
const MyComponent = ({ configNavigation }) => {
   //... code
}

const mapStateToProps = ({ configNavigation }) => ({ configNavigation })

export default connect(mapStateToProps)(MyComponent)

El mapStateToProps es quien tiene los valores que necesitas del store; luego con connect le pasas esos valores al componente para que los puedas usar.
De todas maneras, considera realizar la conexión con el store, utilizando el hook useSelector, ya que como indica la página oficial de react-redux, se recomienda utilizar el hook en desmedro de connect por una futura y posible deprecación.
Con el hook sería
import { useSelector, shallowEqual } from 'react-redux'

const MyComponent = () => {
   const { configNavigation } = useSelector(state => state, shallowEqual)

   //... code
}

shallowEqual es una función que se encarga de manejar la comparación a niveles más profundos de la versión actual del store vs la versión anterior, ya que por defecto, el hook useSelector sólo realiza esta comparación a nivel "superficial" (===), lo que daría posibles impactos en la performance del aplicativo.


text:
Q: cholesky decomposition ScaLapack error I'm getting the following error and i'm not sure why.
{    1,    1}:  On entry to PDPOTRF parameter number    2 had an illegal value
{    1,    0}:  On entry to PDPOTRF parameter number    2 had an illegal value
{    0,    1}:  On entry to PDPOTRF parameter number    2 had an illegal value
{    0,    0}:  On entry to PDPOTRF parameter number    2 had an illegal value

 info < 0:  If the i-th argument is an array and the j-entry had an illegal value, then INFO = -(i*100+j), if the i-th argument is a scalar and had an illegal value, then INFO = -i.

I Know what the error messages means but I followed the dated documentation available on the web as best as possible and tried to piece together a parallel cholesky factorization from working example codes on the web. I'm not sure where I went wrong.
Could some one explain where I went wrong in the code below? Here's an overview of what the code does, I'm testing with 4 processors and divide the 8x8 matrix into 2 x 2 processor block grid
 loads a matrix from file, heres an example 8 x 8 matrixfile ,
182   147   140   125   132    76   126   157
147   213   185   150   209   114   166   188
140   185   232   129   194   142   199   205
125   150   129   143   148    81   104   150
132   209   194   148   214   122   172   189
76   114   142    81   122   102   129   117
126   166   199   104   172   129   187   181
157   188   205   150   189   117   181   259

I followed examples to distribute the Matrix to 4 separate 4x4 local arrays one on each of the 4 nodes. I then run descinit_ and call the associated pdpotrf_ routine which yields the above error. I have no idea where i went wrong and tried to follow documentation as best as I could. A working example of a parallel cholesky decomposition in fortran would also greatly help
References for function calls
pdpotrf_
descinit_
Run Parameters
code name - Meaning = Value
N - Global Rows = 8
M - Global Cols = 8
Nb - Local Block Rows = 2
Mb - Local Block Cols = 2
nrows - Local Rows = 4
ncols Local Cols= 4
lda - Leading dimension of local array = 4 (i've tried 2,4,8)
ord - Order of Matrix = 4   (i've also tried many different things here as well)

I Printed the above parameters on every node and they are the same
#include <mpi.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <sstream>
using namespace std;

/*
  To compile:
  mpic++ test.cpp -o test -L/home/admin/libs -lscalapack -lrefblas -ltmg -lreflapack -lgfortran -Wall -O2
  To run:
  mpirun -np 4 ./test matrixfile 8 8 2 2

*/

extern "C" {
  /* Cblacs declarations */
  void Cblacs_pinfo(int*, int*);
  void Cblacs_get(int, int, int*);
  void Cblacs_gridinit(int*, const char*, int, int);
  void Cblacs_gridinfo(int, int*, int*, int*,int*);
  void Cblacs_pcoord(int, int, int*, int*);
  void Cblacs_gridexit(int);
  void Cblacs_barrier(int, const char*);
  void Cdgerv2d(int, int, int, double*, int, int, int);
  void Cdgesd2d(int, int, int, double*, int, int, int);

  int numroc_(int*, int*, int*, int*, int*);

  void pdpotrf_(char*, int*, double*,
        int*, int*, int*, int*);

  void descinit_( int *, int *, int *, int *, int *, int *, int *,
          int *, int *, int *);

}

int main(int argc, char **argv){
  /* MPI */
  int mpirank,nprocs;
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &mpirank);
  MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
  double MPIelapsed;
  double MPIt2;
  double MPIt1;

  /* Helping vars */
  int iZERO = 0;
  int verbose = 1;
  bool mpiroot = (mpirank == 0);

  if (argc < 6) {
    if (mpiroot)
      cerr << "Usage: matrixTest matrixfile N M Nb Mb"
       << endl
       << " N = Rows , M = Cols , Nb = Row Blocks , Mb = Col Blocks "
       << endl;

    MPI_Finalize();
    return 1;
  }
  /* Scalapack / Blacs Vars */
  int N, M, Nb, Mb;
  int descA[9];
  int info = 0;
  //  int mla = 4;
  int ord = 8;

  double *A_glob = NULL, *A_glob2 = NULL, *A_loc = NULL;

  /* Parse command line arguments */
  if (mpiroot) {
    /* Read command line arguments */
    stringstream stream;
    stream << argv[2] << " " << argv[3] << " " << argv[4] << " " << argv[5];
    stream >> N >> M >> Nb >> Mb;

    /* Reserve space and read matrix (with transposition!) */
    A_glob  = new double[N*M];
    A_glob2 = new double[N*M];
    string fname(argv[1]);
    ifstream file(fname.c_str());
    for (int r = 0; r < N; ++r) {
      for (int c = 0; c < M; ++c) {
    file >> *(A_glob + N*c + r);
      }
    }

    /* Print matrix */

      if(verbose == 1) {
    cout << "Matrix A:\n";
    for (int r = 0; r < N; ++r) {
      for (int c = 0; c < M; ++c) {
        cout << setw(3) << *(A_glob + N*c + r) << " ";
      }
      cout << "\n";
    }
    cout << endl;
      }

  }

  /* Begin Cblas context */
  int ctxt, myid, myrow, mycol, numproc;
  //<TODO> make dynamic
  int procrows = 2, proccols = 2;
  Cblacs_pinfo(&myid, &numproc);
  Cblacs_get(0, 0, &ctxt);
  Cblacs_gridinit(&ctxt, "Row-major", procrows, proccols);
  Cblacs_gridinfo( ctxt, &procrows, &proccols, &myrow, &mycol );
  /* process coordinates for the process grid */
  // Cblacs_pcoord(ctxt, myid, &myrow, &mycol);

  /* Broadcast of the matrix dimensions */
  int dimensions[4];
  if (mpiroot) {
    dimensions[0] = N;//Global Rows
    dimensions[1] = M;//Global Cols
    dimensions[2] = Nb;//Local Rows
    dimensions[3] = Mb;//Local Cols
  }
  MPI_Bcast(dimensions, 4, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&ord, 1, MPI_INT, 0, MPI_COMM_WORLD);
  N = dimensions[0];
  M = dimensions[1];
  Nb = dimensions[2];
  Mb = dimensions[3];

  int nrows = numroc_(&N, &Nb, &myrow, &iZERO, &procrows);
  int ncols = numroc_(&M, &Mb, &mycol, &iZERO, &proccols);

  int lda = max(1,nrows);

  MPI_Bcast(&lda, 1, MPI_INT, 0, MPI_COMM_WORLD);

  /* Print grid pattern */
  if (myid == 0)
    cout << "Processes grid pattern:" << endl;
  for (int r = 0; r < procrows; ++r) {
    for (int c = 0; c < proccols; ++c) {
      Cblacs_barrier(ctxt, "All");
      if (myrow == r && mycol == c) {
    cout << myid << " " << flush;
      }
    }
    Cblacs_barrier(ctxt, "All");
    if (myid == 0)
      cout << endl;
  }

  if(myid == 0){
    cout <<"Run Parameters"<<endl;
    cout <<"Global Rows = " << M <<endl;
    cout <<"Global Cols = " << N <<endl;
    cout <<"Local Block Rows = " << Mb <<endl;
    cout <<"Local Block Cols = " << Nb <<endl;
    cout << "nrows = "<<nrows<<endl;
    cout << "ncols = "<<ncols<<endl;
    cout << "lda = "<<lda<<endl;
    cout <<"Order = "<<ord<<endl;
  }

  for (int id = 0; id < numproc; ++id) {
    Cblacs_barrier(ctxt, "All");
  }
  A_loc = new double[nrows*ncols];
  for (int i = 0; i < nrows*ncols; ++i) *(A_loc+i)=0.;

  /* Scatter matrix */
  int sendr = 0, sendc = 0, recvr = 0, recvc = 0;
  for (int r = 0; r < N; r += Nb, sendr=(sendr+1)%procrows) {
    sendc = 0;
    int nr = Nb;
    if (N-r < Nb)
      nr = N-r;

    for (int c = 0; c < M; c += Mb, sendc=(sendc+1)%proccols) {
      int nc = Mb;
      if (M-c < Mb)
    nc = M-c;

      if (mpiroot) {
    Cdgesd2d(ctxt, nr, nc, A_glob+N*c+r, N, sendr, sendc);
      }

      if (myrow == sendr && mycol == sendc) {
    Cdgerv2d(ctxt, nr, nc, A_loc+nrows*recvc+recvr, nrows, 0, 0);
    recvc = (recvc+nc)%ncols;
      }

    }

    if (myrow == sendr)
      recvr = (recvr+nr)%nrows;
  }

  /* Print local matrices */
  if(verbose == 1) {
  for (int id = 0; id < numproc; ++id) {
    if (id == myid) {
    cout << "A_loc on node " << myid << endl;
    for (int r = 0; r < nrows; ++r) {
      for (int c = 0; c < ncols; ++c)
        cout << setw(3) << *(A_loc+nrows*c+r) << " ";
      cout << endl;
    }
    cout << endl;
      }
      Cblacs_barrier(ctxt, "All");
    }
  }

  for (int id = 0; id < numproc; ++id) {
    Cblacs_barrier(ctxt, "All");
  }

  /* DescInit */
  info=0;
  descinit_(descA, &N, &M, &Nb, &Mb,&iZERO,&iZERO,&ctxt, &lda, &info);

  if(mpiroot){
    if(verbose == 1){
      if (info == 0){
    cout<<"Description init sucesss!"<<endl;
      }
      if(info < 0){
    cout <<"Error Info < 0: if INFO = -i, the i-th argument had an illegal value"<< endl
         <<"Info = " << info<<endl;
      }
    }
    // Cblacs_barrier(ctxt, "All");
  }

  //psgesv_(n, 1, al, 1,1,idescal, ipiv, b, 1,1,idescb,  info) */
  //    psgesv_(&n, &one, al, &one,&one,idescal, ipiv, b, &one,&one,idescb,  &info);
  //pXelset http://www.netlib.org/scalapack/tools/pdelset.f

  /* CHOLESKY HERE */
  info = 0;
  MPIt1=MPI_Wtime();

  pdpotrf_("L",&ord,A_loc,&Nb,&Mb,descA,&info);

  for (int id = 0; id < numproc; ++id) {
    Cblacs_barrier(ctxt, "All");
  }

  MPIt2 = MPI_Wtime();
  MPIelapsed=MPIt2-MPIt1;
  if(mpiroot){
    std::cout<<"Cholesky MPI Run Time" << MPIelapsed<<std::endl;

    if(info == 0){
      std::cout<<"SUCCESS"<<std::endl;
    }
    if(info < 0){

      cout << "info < 0:  If the i-th argument is an array and the j-entry had an illegal value, then INFO = -(i*100+j), if the i-th argument is a scalar and had an illegal value, then INFO = -i. " << endl;
      cout<<"info = " << info << endl;
    }
    if(info > 0){
      std::cout<<"matrix is not positve definte"<<std::endl;
    }
  }

  //sanity check set global matrix to zero before it's recieved by nodes
  if(mpiroot){
    for (int r = 0; r < N; ++r) {
      for (int c = 0; c < M; ++c) {
    A_glob2[c *N + r]  = 0;
      }
    }
  }

  /* Gather matrix */
  sendr = 0;
  for (int r = 0; r < N; r += Nb, sendr=(sendr+1)%procrows) {
    sendc = 0;
    // Number of rows to be sent
    // Is this the last row block?
    int nr = Nb;
    if (N-r < Nb)
      nr = N-r;

    for (int c = 0; c < M; c += Mb, sendc=(sendc+1)%proccols) {
      // Number of cols to be sent
      // Is this the last col block?
      int nc = Mb;
      if (M-c < Mb)
    nc = M-c;

      if (myrow == sendr && mycol == sendc) {
    // Send a nr-by-nc submatrix to process (sendr, sendc)
    Cdgesd2d(ctxt, nr, nc, A_loc+nrows*recvc+recvr, nrows, 0, 0);
    recvc = (recvc+nc)%ncols;
      }

      if (mpiroot) {
    // Receive the same data
    // The leading dimension of the local matrix is nrows!
    Cdgerv2d(ctxt, nr, nc, A_glob2+N*c+r, N, sendr, sendc);
      }
    }
    if (myrow == sendr)
      recvr = (recvr+nr)%nrows;
  }
  /* Print test matrix */
  if (mpiroot) {
    if(verbose == 1){
      cout << "Matrix A test:\n";
      for (int r = 0; r < N; ++r) {
    for (int c = 0; c < M; ++c) {
      cout << setw(3) << *(A_glob2+N*c+r) << " ";
    }
    cout << endl;
      }
    }
  }

  /* Release resources */
  delete[] A_glob;
  delete[] A_glob2;
  delete[] A_loc;
  Cblacs_gridexit(ctxt);
  MPI_Finalize();
}

A: Right - I solved this. Here's what you have to do (I checked the result of the modified MPI program against a Cholesky decomp of your matrix in Octave -- it works.).
I found the following LAPACK reference by IBM to be more helpful than the one in your link:
http://publib.boulder.ibm.com/infocenter/clresctr/vxrx/index.jsp?topic=%2Fcom.ibm.cluster.pessl.v4r2.pssl100.doc%2Fam6gr_lpotrf.htm
PDPOTRF( UPLO, N, A, IA, JA, DESCA, INFO )
You are passing Mb and Nb as IA and JA. However, those parameters are meant to provide the starting row and column of your global matrix inside a larger matrix. They are only relevant if you have a big matrix and only want the Cholesky decomp of a submatrix. In your case, IA and JA both have to be 1!
So all you need to do is:
int IA = 1;
int JA = 1;
pdpotrf_("L",&ord,A_loc,&IA,&JA,descA,&info);

You may also want to change your hardcoded int ord = 8; so that it depends on the value read from the command line, otherwise you'll run into problems later.
Output of your program modified as described above:
Cholesky MPI Run Time0.000659943
SUCCESS
Matrix A test:
13.4907 147 140 125 132  76 126 157
10.8964 9.70923 185 150 209 114 166 188
10.3775 7.4077 8.33269 129 194 142 199 205
9.26562 5.0507 -0.548194 5.59806 148  81 104 150
9.78449 10.5451 1.72175 0.897537 1.81524 122 172 189
5.63349 5.41911 5.20784 0.765767 0.0442447 3.63139 129 117
9.33974 6.61543 6.36911 -2.22569 1.03941 2.48498 1.79738 181
11.6376 6.30249 4.50561 2.28799 -0.627688 -2.17633 7.27182 0.547228

Octave output for comparison:
octave:1> A=dlmread("matrixfile4")
A =

   182   147   140   125   132    76   126   157
   147   213   185   150   209   114   166   188
   140   185   232   129   194   142   199   205
   125   150   129   143   148    81   104   150
   132   209   194   148   214   122   172   189
    76   114   142    81   122   102   129   117
   126   166   199   104   172   129   187   181
   157   188   205   150   189   117   181   259

octave:2> C=chol(A)
C =

   13.49074   10.89636   10.37749    9.26562    9.78449    5.63349    9.33974   11.63761
    0.00000    9.70923    7.40770    5.05070   10.54508    5.41911    6.61543    6.30249
    0.00000    0.00000    8.33269   -0.54819    1.72175    5.20784    6.36911    4.50561
    0.00000    0.00000    0.00000    5.59806    0.89754    0.76577   -2.22569    2.28799
    0.00000    0.00000    0.00000    0.00000    1.81524    0.04424    1.03941   -0.62769
    0.00000    0.00000    0.00000    0.00000    0.00000    3.63139    2.48498   -2.17633
    0.00000    0.00000    0.00000    0.00000    0.00000    0.00000    1.79738    7.27182
    0.00000    0.00000    0.00000    0.00000    0.00000    0.00000    0.00000    0.54723

(My earlier comment -now deleted- about matrices being wrongly copied to the nodes does not apply, the rest of your program seems fine to me.)


text: Q: Is it possible to use a spring boot application for controlling a website and as an api at the same time? So I have build a spring boot application which I use to run my website which contains of different html files), if I enter a certain url. But I also want it to be an api and to return json data, when given another url. Is that possible or do I have to implement two different applications for that?


text:
Q: Get Table Data from op2 file using pyNastran I am trying to read final separation distances from an op2 file. I can see the table name (OSPDS1) is included in model.table_names, where model is the return value from read_op2(file_name, build_dataframe=True, debug=False).
I have read every page of pyNastran's documentation and cannot for the life of me figure out how to retrieve the data for a table. I know the name I'm looking for is OSPDS1 based on the op2_scalar source code (https://pynastran-git.readthedocs.io/en/latest/_modules/pyNastran/op2/op2_interface/op2_scalar.html?highlight=separation#). I think one of set_additional_generalized_tables_to_read() or set_additional_result_tables_to_read(tables) is part of the answer. I've gotten each of them to run using the _table_mapper output, but then don't know what to do from there. Do I reread the op2 file somehow now that I've set this table to be read?
I can't really provide a minimum running example because I can't upload the op2 file. If absolutely necessary, I can create a new run of some simplified geometry.