text:
Q: Creating a matrix of rank r from r number of rank 1 matrices? I am told that all matrices of Rank $r$ can be formed out of the combinations of $r$ number of Rank 1 matrices. So that's the original matrix can be broken down into $r$ number of rank 1 matrices. But I don't understand and see how this is possible.
Say for a matrix of this form:
$$
A=\begin{bmatrix}
1 & 3 & 2 & 6\\
3 & 0 & 1 & 4\\
2 & 1 & 1 & 4
\end{bmatrix}
$$
The $rank(A)= 3$.
So if the claim was right, then I can form back the same matrix $A$ with the combination of 3 of Rank 1 matrices. I tried to "emulate" that idea but I just don't totally get how I could do it.
Thanks for any help on this!

A: If $A=(A_{1}, \dots A_{n}), A_{i} \in K^{m}$, then the rank of $A$ is
$r=dim(Span(A_{1}, \dots, A_{n}))$. Let $\{v_{1}, \dots v_r\}$ be a basis for it. So, $\forall i=1\dots n, \exists a_{i1}, \dots , a_{ir} \in K$ such that $A_{i}=a_{i1}v_1+\dots + a_{ir}v_r $ and
$A=(a_{11}v_1+\dots + a_{1r}v_r, \dots , a_{n1}v_1+\dots + a_{nr}v_r)$ .
Now you can take $B_j=(a_{1j}v_j, \dots, a_{nj}v_j)$ $\forall j=1, \dots, r$ and observe that $rk(B_j)=1$ and $A=\sum_{j=1}^{r}B_j$.
Here's the example:
$A=(A_1 , A_2, A_3, A_4)$ with
$A_1=\begin{bmatrix}1 \\ 3 \\ 2 \end{bmatrix}$ ,
$A_2=\begin{bmatrix}3 \\ 0 \\ 1 \end{bmatrix}$ ,
$A_3=\begin{bmatrix}2 \\ 1 \\ 1 \end{bmatrix}$ ,
$A_4=\begin{bmatrix}6 \\ 4 \\ 4 \end{bmatrix}$ .
$Span(A_1,A_2,A_3,A_4) = R^3$ , and so we can take the standard basis $\{e_1=\begin{bmatrix}1 \\ 0 \\ 0 \end{bmatrix},
e_2=\begin{bmatrix}0 \\ 1 \\ 0 \end{bmatrix},
e_3=\begin{bmatrix}0 \\ 0 \\ 1 \end{bmatrix}
\}$
Now, $A_1=1e_1+3e_2+2e_3$ ,
$A_2=3e_1+0e_2+e_3$ ,
$A_3=2e_1+1e_2+1e_3$ ,
$A_4=6e_1+4e_2+4e_3$ ,
and so I make:
$B_1=\begin{bmatrix}
1 & 3 & 2 & 6\\
0 & 0 & 0 & 0\\
0 & 0 & 0 & 0
\end{bmatrix}$
$B_2=\begin{bmatrix}
0 & 0 & 0 & 0\\
3 & 0 & 1 & 4\\
0 & 0 & 0 & 0
\end{bmatrix}$
$B_3=\begin{bmatrix}
0 & 0 & 0 & 0\\
0 & 0 & 0 & 0\\
2 & 1 & 1 & 4
\end{bmatrix}$
and $A=B_1+B_2+B_3$.
N.B. The matrixes $B_i$ are so "well done" in this case because we could take the standard basis as basis of the columns.

A: You can easily write SVD http://en.wikipedia.org/wiki/Singular_value_decomposition in the form of what you need.


text:
Q: PHP/AJAX - advice on replacing iFrame with DIV (combined with AJAX) I currently have a webpage where an iframe contains data that is stored into an invisible form, and I want to replace that iFrame, with a div, where the content is being changed/updated via AJAX.

If you dont feel like reading all this, you can skip to the end and read my main question.

Now, the complicated part is that the form contains all the important and used data in an invisible form, which needs to be send via POST. But, the page also includes a form that can send data via GET. And: I've setup the forms like this, that the php file recieves the form data as an array.
At the moment it works like this:
The iFrame shows the data, and stores it in an invisible form. When you want the page to refresh automatically, every 30 seconds, you click a button, and you get redirected to another page, which recieves the data from the previous page, using POST.
When you're on the auto-refreshing page, I use Javascript to automatically submit the form containing all the important data, to refresh the page.
Resubmitting the page is nessecary because I use PHP to do some important calculations with the data I'm using. Moving all this functionality to Javascript is not an option.
Just to be clear, here is a very brief description of my case:

Main page: 2 forms, 1 POST setup so variables are in 1 array, 1 GET with 6 variables.
  The GET form could be modified to an AJAX function, as it only includes 6 variables
Auto update page: 2 forms, same as before. Though this POST form is auto-submitted via Javascript every 30 seconds (to update the PHP
  functions output).

So, my main question is:
Can I, and if so how, recieve an array from a POST form in AJAX, and then send it as an array to a php page?
EDIT:
Here is some of the code for submitting the form:

and the form is build up like this:
echo '<form action="data-reis-refresh.php" id="updateform" name="update" method="POST" style="width: 100px;">';
echo '<input type="submit" class="submit replaced" value="Volg deze trein" name="submit-search"/>';
if (round($afgelegdpercentage*100,1)==100) {
echo ' Deze trein is al aangekomen';
    } else {
echo ' Ververs gegevens (automatisch elke minuut)';
}
echo '<input type="hidden" name="provincie" value="'.$provincie.'">
      <input type="hidden" name="reisdata[Overstap]" value="'.$reisdata["Overstap"].'">
      <input type="hidden" name="reisdata[Van]" value="'.$reisdata["Van"].'">

but then longer (a lot longer, and with changing length);
I'm using this for all my AJAX requests: [though I change it for different uses]
// Algemene functie om een xmlHttp object te maken. Via dit object kunnen we later Ajax calls plaatsen

function GetXmlHttpObjectReisData() {
    var xmlHttp;
    try { // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) { // Internet Explorer
        try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    return xmlHttp;
}
function CallAjaxReisDataFunction(serverScript,arguments)
{
    var xmlHttp = new GetXmlHttpObjectReisData(); // Functie welke wordt uitgevoerd als de call naar de server klaar is State 4)
    xmlHttp.onreadystatechange = function()
    {
        if (xmlHttp.readyState == 4)
        {
            handleReisDataResult(xmlHttp.responseText);
        }
    }

    // Ajax call (Request naar de server met eventuele parameters (arguments))
    xmlHttp.open("POST", serverScript, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", arguments.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(arguments);
}

function callReisDataServer(serverScript,van,naar)
{
    CallAjaxReisDataFunction(serverScript,"?&reisdata=" + reisdata);
}

function handleReisDataResult(responseText)
{
    document.getElementById('reis').innerHTML = responseText;
}

A: JS code:
var postdata = {"provincie":"123","reisdata":{"Overstap":"234","Van":"345"}};
var post = "";
var url = "data-reis-refresh.php";
var key, subkey;
for (key in postdata) {
    if (typeof(postdata[key]) == object) {
        for (subkey in postdata[key]) {
            if (post != "") post += "&";
            post += key + "%5B" + subkey + "%5D=" + postdata[key][subkey];
        }
    }
    else post += key + "=" + postdata[key];
}
req.open("POST", url, true);
req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", post.length);
req.setRequestHeader("Connection", "close");
req.send(post);

And to transfer associative array back from PHP to JS:
In PHP script, called from AJAX request:
echo "(".json_encode($hash).")";

In JS code, parsing the result:
var hash = eval(response);

A: In the end, I ended up using jQuery .post() and .get().
Those are extremely easy to use and a lot faster and more flexible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to resolve macro precedence in C? I was trying to write a simple C program. Here I have defined a macro.
#define NAME(x) #x ## _bingo

Now which one (# and ##) of them will be solved first?
I am stuck :) . I tried to google about such macro precedence. But couldn't find anything relevant.

A:
Now which one (# and ##) of them will be solved first?

The standard says:

16.3.2 The # operator [cpp.stringize]
2/ [...] The order of evaluation of # and ## operators is unspecified.

But what are you trying to achieve here? It seems that:
#define NAME(x) x ## _bingo

Would be enough if you want to concatenate the x token and _bingo.
Example:
NAME(foo)

would be expanded as
foo_bingo

EDIT :
If you want to stringify the generated token with the NAME macro, here is an example on how you can do this (solve the problem of macro replacement -> 16.3.1 of the standard):
#define NAME(x)  x##_bingo

// Converts the parameter x to a string after macro replacement
// on x has been performed if needed.
#define STRINGIFY(x)    DO_STRINGIFY(x)
#define DO_STRINGIFY(x) #x

int main() {
    std::string n  = STRINGIFY( NAME( foo ) );
    std::string n2 = DO_STRINGIFY( NAME(foo) );

    // Will print foo_bingo as expected
    std::cout << n << std::endl;

    // Will print NAME( foo ) because the macro NAME is not expanded
    std::cout << n2 << std::endl;
    return 0;
}

Output:
foo_bingo
NAME(foo)


text:
Q: How to resize all user control when parent user control resized How to resize all user control when parent user control resized
Application has one parent user control,  which can be resized to make it small and large.
now but the same user control has 3/4 more user control. Two user controls has no size as fixed, but they are dynamically do some drawing.

A: Specify sizes in a Percent instead of hardcoding them.
An easy way to do that is create a Converter that takes the parent size as the binding and has a percent value as the parameter.
For example, converter would be something like this:
public class PercentToDoubleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double size = (double)value;
        double percent = (parameter == null ? 0.00 : System.Convert.ToDouble(parameter));
        return percent * size;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And the XAML would say something like this:
<UserControl x:Name=RootControl>
    <Button Height="{Binding ElementName=RootControl, Path=Height,
            Converter={StaticResource MyPercentToDoubleConverter}, ConverterParameter=.2}" />
</UserControl>


text:
Q: How do I unload content from the content manager? I tried using the dispose function on a texture2d but that caused problems and I'm pretty sure it's not what I'm meant to use.
What should I use to basically unload content? Does the content manager keep track itself or is there something I have to do?

A: Take a look at my answers here and possibly here.
The ContentManager "owns" all the content that it loads and is responsible for unloading it. The only way you should unload content that a ContentManager has loaded is by using ContentManager.Unload() (MSDN).
If you are not happy with this default behaviour of ContentManager, you can replace it as described in this blog post.
Any textures or other unload-able resources that you create yourself without going through ContentManager should be disposed (by calling Dispose()) in your Game.UnloadContent function.

A: If you want to dispose a texture, the easiest way to do it:
    SpriteBatch spriteBatch;
    Texture2D texture;
    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        texture = Content.Load<Texture2D>(@"Textures\Brick00");
    }
    protected override void Update(GameTime gameTime)
    {
        // Logic which disposes texture, it may be different.
        if (Keyboard.GetState().IsKeyDown(Keys.D))
        {
            texture.Dispose();
        }

        base.Update(gameTime);
    }
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, RasterizerState.CullCounterClockwise, null);

        // Here you should check, was it disposed.
        if (!texture.IsDisposed)
            spriteBatch.Draw(texture, new Vector2(resolution.Width / 2, resolution.Height / 2), null, Color.White, 0, Vector2.Zero, 0.25f, SpriteEffects.None, 0);

        spriteBatch.End();
        base.Draw(gameTime);
    }

If you want to dispose all content after exiting the game, the best way to do it:
    protected override void UnloadContent()
    {
        Content.Unload();
    }

If you want to dispose only texture after exiting the game:
    protected override void UnloadContent()
    {
        texture.Dispose();
    }


text:
Q: Python: setting recursion limit slows sorting program I'm doing a program, that compares different sorting algorithms: insertion sort, bubble sort and quick sort. When the input is a list of at least 1000 elements, the program throws an error.
  File "/Users/karol/PycharmProjects/Algorytmy6/main.py", line 52, in quickSort
return quickSort(less) + equal + quickSort(greater)
  [Previous line repeated 995 more times]
  File "/Users/karol/PycharmProjects/Algorytmy6/main.py", line 43, in quickSort
    if len(list) > 1:
RecursionError: maximum recursion depth exceeded while calling a Python object

I tried to set recursion limit by sys.setrecursionlimit(sizeOfList+1), but it dramatically slows the quick sort algorithm. For example for 10 000 elements in list, quick sort is slower than insertion sort:

Insertion sorting a list of 10000 elements took: 3.238
Bubble sorting a list of 10000 elements took: 5.618 s
Quick sorting a list of 10000 elements took: 4.239 s

Moreover, if I run only quickSort algorithm without insertionSort and bubbleSort, then it works fine. And it is as fast as it should be:

Quick sorting a list of 10000 elements took: 0.077 s

I need the real quickSort time, because the program was made to compare it with other sorting algorithms.
Here is my code:
import random, time

def insertionSort(list):
    startTime = time.time()
    for i in range(len(list)):
        min = list[i]
        for j in range(i, len(list)):
            if list[j] <= min:
                min = list[j]
                index = j
        list[index] = list[i]
        list[i] = min

    elapsedTime = round(time.time() - startTime, 3)
    print("Insertion sorting a list of {} elements took: {} s".format(len(list), elapsedTime))

    return list

def bubbleSort(list):
    startTime = time.time()
    n = len(list) - 1
    for j in range(len(list)):
        for i in range(n-j):
            if list[i] > list[i+1]:
                temp = list[i]
                list[i] = list[i+1]
                list[i+1] = temp

    elapsedTime = round(time.time() - startTime, 3)
    print("Bubble sorting a list of {} elements took: {} s".format(len(list), elapsedTime))

    return list

def quickSort(list):

    less = []
    equal = []
    greater = []

    if len(list) > 1:
        pivot = list[0]
        for x in list:
            if x < pivot:
                less.append(x)
            elif x == pivot:
                equal.append(x)
            elif x > pivot:
                greater.append(x)
        return quickSort(less) + equal + quickSort(greater)
    else:
        return list

size = 10000
list = [0]*size

for i in range(size):
    list[i] = random.randint(1, size)

insertionSort(list)
bubbleSort(list)
startTime = time.time()
quickSort(list)
elapsedTime = round(time.time() - startTime, 3)
print("Quick sorting a list of {} elements took: {} s".format(len(list), elapsedTime))

A: The problem is that you sort the list in the first two sorts so its sorted already when it reaches quicksort
insertionSort(lst)
bubbleSort(lst)
quickSort(lst)

sorts the same list 3 times but it is already sorted after the first insertionSort.
You will need to copy the list sort from the original order.
import copy

lst_b = copy.deepcopy(lst)
lst_q = copy.deepcopy(lst)

insertionSort(lst)
bubbleSort(lst_b)
quickSort(lst_q)

The reason you see the problem with quickSort in your original code is that a sorted list leads to quadratic time when the list is already sorted.


text:
Q: How could I incrementally display JSON data but not repeatedly parse and display in WEB I have a log file, which is logged by a real-time running script, now I am going to monitor the status of the script from the log at WEB/HTML, so I use JavaScript to update the WEB/HTML, also I write one CGI script to parse the log and output event status to JSON for JavaScript's reading. The JS script periodically(every 2 second for example) invoke the CGI to parse the log and invoke getJSON to read event status, then update the WEB.
eg. at time T(second), the log file logged:
event 1 start ...
doing event 1 ...
event 1 pass  ...
event 1 end   ...
at time T+2(second), the log file logged:
event 1 start ...
doing event 1 ...
event 1 pass  ...
event 1 end   ...
event 2 start ...
doing event 2 ...
event 2 fail  ...
event 2 end   ...
the CGI at time T(second) may output:
{"event":[["event 1", "pass"]]}
at some URI, which will be read by JS's getJSON
and at time T+2(second) may output:
{"event":[["event 1", "pass"],["event 2", "failed"]]}

So here, the CGI script I implemented will parse the whole log every 2 second, which may consume lot of system resource when the log is large and do repeated things for the event that already done.
Anyone have a idea how could I parse the log incrementally by output and not whole log, and how to store the already done event's status?

A: If you don't want to parse the entire log file every time, you should try to mimic the behavior of tail -f:

*

*Open the log and parse everything (the first time).

*Fetch the cursor position with getpos.

*Fetch the inode number and mtime with stat.

*Save with the cursor and the inode in a separate file.

When the next call arrives, compare the inode number with the one you saved:

*

*If it has changed, then the file was modified (like after a logrotate). You need to start reading from the beginning.

*If the mtime has changed, seek to the old position with setpos and resume parsing.

*Otherwise, nothing has changed.

With this solution, you'll be able to parse the file chunk by chunk. Be careful, you might sometimes have an edge case when only a part of a line has been written.
EDIT: @mob's comment


text:
Q: How to Convert a UNIX time stamp to XMLGregorianCalendar value in java? How to Convert a UNIX time stamp to XMLGregorianCalendar value in java ?
TIME STAMP: 1379487623

A: long time = 1379487623;
Date date = new Date((long)time*1000);
GregorianCalendar c = new GregorianCalendar();
c.setTime(date);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);


text:
Q: Can binary sequences generated from ergodic maps be chaotic? Briefly, the way symbols are generated is:
Consider a one-dimensional chaotic map $T: [0,1]→[0,1]$ and a time series $\{x_n\}_{n=1}^N$ generated with this map. Define a threshold $A$ and a thresholding function $π$:
$$\pi(x) := \begin{cases} 1 &\text{if} \quad x>A \\
  0  & \text{else}\end{cases}$$
Consider a symbolic sequence $\{s_n\}_{n=1}^N$ obtained by applying $π$ to the elements of $\{x_n\}_{n=1}^N$, i.e., $s_i := π(x_i)$
For example, let $A =0.5$ be the threshold and the time series $x = [0.1,\, 0.56,\, 0.6,\, ...]$. Then
$\pi(x_1) =  0$;
$\pi(x_1) =  1$;
$\pi(x_2) =  1$.
Thus, the symbolic representation is $s = [0,1,1]$
I am facing technical difficulties in following the paper. My question is: Such binary sequences are just i.i.d. random variables of some distribution. How can we say that these sequences $s$ are chaotic?

A:
When such 0/1 sequences are generated, they are just i.i.d random variables of some distribution.

No, they aren't.
As for identically distributed, consider any sequence when changing $A$. The higher $A$, the higher the probability that the symbol is $1$.
As for independently, consider the sequence generated by a tent map and then transform all values via
$$f(x) := \left(x-\tfrac{1}{5}\right) \bmod 1.$$
The corresponding sequence could as well have been generated by a somewhat shifted tent map, which looks like this:

If you select $A=\tfrac{7}{10}$ (see plot), it should become obvious that the probability that a $1$ is followed by another $1$ is higher than the probability that that a $0$ is followed by a $1$, so the symbol sequence has some memory.

How can we say that these sequences S are chaotic?

It all boils down to your definition of chaoticity at the end, but consider the following: Let $T$ be the classical tent map (forget the above shift) and let $A:=\tfrac{1}{2}$. Now, if we represent numbers in binary, the effect of the map on a number can be understood as removing its first digit after the decimal point, e.g., $$T(0.10100101011101) = 0.0100101011101,$$ $$T(0.0100101011101) = 0.100101011101,$$ and so on. Due to our threshold selection, we also have that $s_i$ is the digit removed from $x_i$ by $T$. Thus your sequence $s$ is the sequence of digits of $x_0$.
Thus, the more precisely, we know $x_0$, the longer can we accurately predict the sequence $s$, but any finite precision will make it impossible for us to predict $s$ forever. This is very reminiscent of the Butterfly Effect.


text:
Q: How to fix "id -u" returning 0 into my variable for if statement? I'm trying to put the result of "id -u $1" into a variable in order to verify it with an if statement but it seems like it's returning 0 into my variable even tho I've checked it and it's supposed to be 1008.Is it because the username is taken from the argument of the script?
UID=`id -u $1`
LOCK=`usermod -L $1`

if test $UID -lt 500;then

        echo "impossible to lock user"

else

        $LOCK;

fi

A: Your problem is that you use system variable in your script and try to change it.
instead of UID try to use UID1 (for example) as variable name. And your script will be something like:
UID1=`id -u $1`
LOCK=`usermod -L $1`

if test $UID1 -lt 500;then
        echo "impossible to lock user"
else
        $LOCK;
fi


text:
Q: Cannot read Delta tables created by Spark in Hive or Dbeaver/JDBC I've used Spark 3.3.1, configured with delta-core_2.12.2.2.0 and delta-storage-2.2.0, to create several tables within an external database.
spark.sql("create database if not exists {database}.{table} location {path_to_storage}")

Within that database I've got several delta tables, created and populated through Spark, e.g.:
{table_df}.write.format("delta").mode("overwrite").saveAsTable("{database}.{table}")

I can then, right away, address it so:
df = spark.sql("select * from {database}.{table} limit 10")
df.show()

And everything works fine.
When I try to run the same command (select * from {database}.{table} limit 10;) through hive, or dbeaver sql editor, I get the following error:
hive> select * from {database}.{table} limit 10;
2023-01-04T12:45:29,474 INFO [main] org.apache.hadoop.hive.conf.HiveConf - Using the default value passed in for log id: 9ecfc0dd-0606-4060-98ef-b1395fc62456
2023-01-04T12:45:29,484 INFO [main] org.apache.hadoop.hive.ql.session.SessionState - Updating thread name to 9ecfc0dd-0606-4060-98ef-b1395fc62456 main
2023-01-04T12:45:31,138 INFO [9ecfc0dd-0606-4060-98ef-b1395fc62456 main] org.apache.hadoop.hive.common.FileUtils - Creating directory if it doesn't exist: hdfs://localhost:9000/tmp/hive/user/9ecfc0dd-0606-4060-98ef-b1395fc62456/hive_2023-01-04_12-45-29_879_2613740326746479876-1/-mr-10001/.hive-staging_hive_2023-01-04_12-45-29_879_2613740326746479876-1
OK
Failed with exception java.io.IOException:java.io.IOException: file:/{path_to_file_storage}/part-00000-7708a52c-0939-4288-b56a-ecdeea197574-c000.snappy.parquet not a SequenceFile
Time taken: 1.649 seconds
2023-01-04T12:45:31,298 INFO [9ecfc0dd-0606-4060-98ef-b1395fc62456 main] org.apache.hadoop.hive.conf.HiveConf - Using the default value passed in for log id: 9ecfc0dd-0606-4060-98ef-b1395fc62456
2023-01-04T12:45:31,298 INFO [9ecfc0dd-0606-4060-98ef-b1395fc62456 main] org.apache.hadoop.hive.ql.session.SessionState - Resetting thread name to  main
hive>

I have installed the delta connectors (delta-hive-assembly_2.12-0.6.0.jar) from here:
https://github.com/delta-io/connectors/blob/master/hive/README.md
Installed it in an auxjar folder in my main hive directory and added the following properties in my hive-site.xml file:
<property>
    <name>hive.input.format</name>
    <value>io.delta.hive.HiveInputFormat</value>
</property>
<property>
    <name>hive.tez.input.format</name>
    <value>io.delta.hive.HiveInputFormat</value>
</property>
<property>
    <name>hive.aux.jars.path</name>
    <value>file:/{path_to_file}/auxjar/delta-hive-assembly_2.12-0.6.0.jar</value>
</property>

When I start hive I'm not seeing an exceptions about the file not being found. Have I missed a critical step out?
Thanks
Tried running a simple query in hive, got an IOException.

A: Hive Connector
See FAQs at base of page:

If a table in the Hive Metastore is created by other systems such as
Apache Spark or Presto, can I use this connector to query it in Hive?
No. If a table in the Hive Metastore is created by other systems such
as Apache Spark or Presto, Hive cannot find the correct connector to
read it. You can follow our instruction to create a new table with a
different table name but point to the same path in Hive. Although it's
a different table name, the underlying data will be shared by all of
systems. We recommend to create different tables in different systems
but point to the same path.


text:
Q: Conditional Logic for Gridview ItemTemplate (using mark up only) I have a gridview as shown below. When the EmpType is contract the EmpID must be masked as "XXX";  for regular employees, actual EmpID should be shown. Also, when it is masked, I need to add a button control in the EmpID column.
I need to do it using mark-up; not using code behind. How can we write the conditional logic for Gridview's ItemTemplate for this logic?
Note: .Net 4.0
    <asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField HeaderText="AssociateID" DataField="AssociateID" />
            <asp:TemplateField HeaderText="EmpID">
                <ItemTemplate>
                    <%# Eval("EmpID")%>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="EmpType" DataField="EmpType" />
        </Columns>
    </asp:GridView>

CODE BEHIND
    List<Associate> associatesList = new List<Associate>();
    associatesList.Add(new Associate { AssociateID = 1, EmpID = 101, EmpType = "Contract" });
    associatesList.Add(new Associate { AssociateID = 2, EmpID = 102, EmpType = "Regular" });
    Gridview1.DataSource = associatesList;
    Gridview1.DataBind();

A: Try this
<%# Eval("EmpType") == "Contract" ? "XXX" : Convert.ToString(Eval("EmpID"))%>

Instead of
 <%# Eval("EmpID")%>

A: Following works
 <asp:TemplateField HeaderText="EmpID">
                <ItemTemplate>
                    <%# Convert.ToString(Eval("EmpType")) == "Contract" ? "XXX" : Convert.ToString(Eval("EmpID"))%>

                    <asp:Button ID="Button1" runat="server" Text="Button"
                    Visible='<%# Eval("EmpType") == "Contract" ? true : false %>' />

                </ItemTemplate>
            </asp:TemplateField>

Related:
Row number can be obtained by following Get GridView Selected Row Values using Page Previous Page
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>"


text:
Q: Override dblclick behavior in Forge Viewer 'fitToView' is triggered by default on viewer double click. What is the best way to override this behavior with my own handler?

A: The easiest way would be to override the default double click handler:
NOP_VIEWER.clickHandler.handleDoubleClick=(mouseClickEvent)=>{
//...
}

You might also want to find out about CanvasClickBehavior config - it sets Viewer's response to canvas interaction to a set of preset options:
const config = {
        "click": {
            "onObject": ["selectOnly"],
            "offObject": ["deselectAll"]
        },
        "clickAlt": {
            "onObject": ["setCOI"],
            "offObject": ["setCOI"]
        },
        "clickCtrl": {
            "onObject": ["selectToggle"]
            // don't deselect if user has control key down https://jira.autodesk.com/browse/LMV-1852
            //"offObject": ["deselectAll"]
        },
        "clickShift": {
            "onObject": ["selectToggle"]
            // don't deselect if user has shift key down https://jira.autodesk.com/browse/LMV-1852
            //"offObject": ["deselectAll"]
        },
}

NOP_VIEWER.setCanvasClickBehavior(config)


text:
Q: Select particular Foreign key from one django model choice session to another model I am trying to do a django practice and while doing I tried to add a foreign key to one model to another model.
I have a model called "Employee_detail" and it have a session called "Position".
Position is a choice field and the choices are 'Manager', 'Supervisor' and 'Employee'.
I have another model called "Department" and I used OneToOneField to get the Employee details(Manager) in this model. I wanted to add the department manager(only) to "Dept_Manager" field.
class Department(models.Model):
    Dept_No = models.CharField(primary_key=True, max_length=6)
    Dept_Name = models.CharField(unique=True, max_length=20)
    Dept_Manager = models.OneToOneField('Employee_Detail', models.DO_NOTHING)

    def __str__(self):
        return self.Dept_No

class Employee_Detail(models.Model):
    Employee_ID = models.CharField(primary_key=True, max_length=6)
    Employee_Name = models.CharField(unique=True, max_length=30)
    Primary_Phone = models.IntegerField(unique=True, max_length=10)
    p = (
        ("Manager","Manager"),("Supervisor","Supervisor"),("Employee","Employee")
    )
    Position = models.CharField(max_length=15, choices= p, default="Employee")
    Email = models.EmailField(max_length=50, unique=True)

    def __str__(self):
        return str(self.Employee_Name)

But when I try to do it like this (please check the image blow) in the "Dept_Manager" it is showing and allowing to add "Supervisor" or "Employee" in that field.
I want it to show only the Managers name as options.
Can anyone tell me how to implement that please?

A: ForeignKey and OneToOneField both accept the parameter limit_choices_to, this will filter the options that can be chosen for the field
Dept_Manager = models.OneToOneField(
    'Employee_Detail',
    on_delete=models.DO_NOTHING,
    limit_choices_to={'Position': 'Manager'}
)


text:
Q: How to check if java hashtable contains key-value pairs from another hashtable Is there any built-in java method to check if one hash table contains all key-value pairs that exist in the other one?
For example:
h1={{0,1},{1,4},{2,5},{3,6}}
h2={{0,1},{2,5}}

In this case, it is true that h1 contains key-value pairs from h2.

A: There's no method on Hashtable that lets you directly check this, but you can use the entrySet() method on each Hashtable to obtain a Set all of its key-value pairs.
Then you can just use containsAll() to see if one of them is a subset of the other, since it

Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set, this method returns true if it is a subset of this set.

e.g.
//  h1={{0,1},{1,4},{2,5},{3,6}}
    Hashtable<Integer, Integer> h1 = new Hashtable<>();
    h1.put(0, 1);
    h1.put(1, 4);
    h1.put(2, 5);
    h1.put(3, 6);

//  h2={{0,1},{2,5}}
    Hashtable<Integer, Integer> h2 = new Hashtable<>();
    h2.put(0, 1);
    h2.put(2, 5);

    Set<Entry<Integer, Integer>> e1 = h1.entrySet();
    Set<Entry<Integer, Integer>> e2 = h2.entrySet();

    System.out.println(e2.containsAll(e1));  // false
    System.out.println(e1.containsAll(e2));  // true

A: Here is a small sample program to demonstrate how to match keys or key and values of 2 different maps:
    public class HashMapMatch {

        public boolean hasMatchingKey(String key, Map m1, Map m2){
            return m1.containsKey(key) && m2.containsKey(key);
        }

        public boolean hasMatchingKeyAndValue(String key, Map m1, Map m2){
            if(hasMatchingKey(key, m1, m2)){
                return m1.get(key).equals(m2.get(key));
            }
            return false;
        }

        public static void main(String[] args) {
            HashMapMatch matcher = new HashMapMatch();
            Map<String, Integer> map1 = new HashMap<>();
            map1.put("One",1);
            map1.put("Two",22);
            map1.put("Three",3);

            Map<String, Integer> map2 = new HashMap<>();
            map2.put("One",1);
            map2.put("Two",2);
            map2.put("Four",4);

            System.out.println("Has matching key? :" + matcher.hasMatchingKey("One", map1, map2));
            System.out.println("Has matching key? :" + matcher.hasMatchingKey("Two", map1, map2));
            System.out.println("Has matching key? :" + matcher.hasMatchingKey("Three", map1, map2));

            System.out.println("Has matching key value: :" + matcher.hasMatchingKeyAndValue("One", map1,map2));
            System.out.println("Has matching key value: :" + matcher.hasMatchingKeyAndValue("Two", map1,map2));

        }
    }

Produces the output:
Has matching key? :true
Has matching key? :true
Has matching key? :false
Has matching key value: :true
Has matching key value: :false


text:
Q: awful and awesome are synonyms or antonyms? Have I learnt correct? In some contents awful has the same meaning as awesome and in some other contents they are opposite?

Exp1: There is an awful building in the town, it's a skyscraper.
Exp2: There is an awesome building in the town, it's a skyscraper.

-

Exp3: There is an awful building in the town, I don't like it.
Exp4: There is an awesome building in the town, I like it.

In exp 1 and 2 the meaning of both are the same but in exp 3 and 4 they have opposite meanings. If I'm correct, so, is there any other words like this that could be both synonyms and antonyms?

A: In modern usage awful and awesome are antonyms.

*

*Awful means very bad

*Awesome means very good
If you want to say "it fills me with awe", nowadays you say "awe-inspiring"
There is a meaning of awful, now slightly dated, and very British.

You have an awful lot of sugar in your tea.

It is restricted to expressions like "awful lot of".
So 1 and 2 mean the opposite, and have much the same meaning as 3 and 4
There are some words that can be synonyms and antonyms: Fast can mean "quick" and "not moving"
*He was running fast/ He was stuck fast.
Quite can mean very or slightly

*

*It was quite the nicest thing to say / It was quite a nice thing to say


text:
Q: Hardness of index sets for computable structures Suppose we have a computable structure $M$ and we want to show that its index set $I(M)$ is (many-one) $\Gamma$-hard for some complexity class $\Gamma$ (like $\Sigma^0_2$). To do this, we need to show that for any $S \in \Gamma$ there is a computable $f : \mathbb{N} \rightarrow \mathbb{N}$ such that $f(n) \in S$ if and only if $n \in I(M)$.
Now in the literature, a common argument to show $\Gamma$-hardness of $I(M)$ is to show that for any set $S \in \Gamma$, there is a uniformly computable sequence of computable structures $M_i$ such that $M_i \cong M$ if and only if $i \in S$. It seems intuitive that constructing such $M_i$ is enough to show that $S \le_m I(M)$, but I want to know explicitly what the many-one reduction $f : \mathbb{N} \rightarrow \mathbb{N}$ is in this case.
Suppose we have a uniformly computable sequence $M_i$ as described above. Given an $n \in \mathbb{N}$, the $M_i$ gives us an algorithm $A$ to construct $M_n$. In theory, if we describe precisely how to compute the index of a computable function, then in particular we can compute the index $e \in \mathbb{N}$ of the algorithm $A$ that enumerates the atomic diagram of $M_n$. Using this $e$, we can decide whether $n \in S$ simply by looking at whether $e \in I(M)$.
So is the function that maps $n \in \mathbb{N}$ to the index of the algorithm that enumerates $M_n$ a many-one reduction from $S$ to $I(M)$? Does that make sense?

A: First of all, your $f$ is going the wrong way: we should have $n\in S\iff f(n)\in I(M)$, since we're reducing $S$ to $I(M)$.
Other than that, though, you're right: when you say "a uniformly computable sequence $K$ of computable structures," what you mean is "a computable function $f:\mathbb{N}\rightarrow\mathbb{N}$," where the idea is that the $n$th element of $K$ is the structure with index $f(n)$. So yes, the statement "the $n$th element of $K$ is $\cong M$ iff $n\in S$" is just the statement "$f(n)\in I(M)\iff n\in S$," which is exactly saying that $f$ is a many-one reduction from $S$ to $I(M)$.


text:
Q: nube: stdio to QTextedit I've read lots of similar threads to this one but im not such a great programmer that i can make sense of it all. Im using qtcreator to make life simple and want to maka a program that can trigger another process, monitor its stdout and then kill it if necessary.
What I assume i want to do is create a QTextedit in the designer and plug a signal into it that updates the contained text whenever the stream updates, so far so good, but thats where i get fuzzy. My initial thought was to create a subclass of QObject that starts the process as a QProcess and whenever the stdout updates the QObject and appends new data to the QTextedit box.
So my program structure would run like this:
on button press create new QObject derived class.
The QObject derived class constructor starts a QProcess and connects the readyReadStdout() signal to the derived qObject class slot.
When the derived QObject is triggered it takes readyReadStdout() and appends any new data to the QTetEdit box.
on button press, call the derived QObject destructor and which kills the process.
Has anybody done something similar? Like i say ive read similar posts but sometimes it takes asking a question in your own words to be able to understand it
Thanks everyone (also my forst post, woo:)

Ok so heres my update:
I have added an instance of QProcess class (named proc) to my mainWindow class and also new instance of a QObject derived class (named procLog) to which I added a slot. I want this slot to take the readyReadStandardOutput() signal as a trigger to call readAllStandardOutput() and emit the new line to a new signal in procLog, I'm having trouble connecting the QProcess slot to the QObject derived class. heres what I'm trying:
connect(proc, SIGNAL(readyReadStandardOutput ()), procLog, SLOT(logReady()));

I get, error: QObject::connect: Cannot connect (null)::readyReadStandardOutput () to (null)::logReady()
Do you know why this is. Aslo is there a way to add code blocks to text in the comments?
thanks!


text:
Q: GUI, two accounts to use different languages Two accounts are set-up, one normal user, one administrative. Ubuntu gui should be in English if administrator is logged in and for all man pages, but it should be in user's language every time the normal user is logged in. How to achieve this ?
Whole GUI, means OS and all software applications are addressed.

A: Use Language Support when logged in as the admin user. Make sure all languages you need are installed, select English and apply system wide. Then, when logged in as the standard user, use Language Support to switch to the desired language.


text:
Q: Canceling a timeout in useEffect() if user scrolls with react hooks Basically the same question as How to cancel a javascript function if the user scrolls the page but using react hooks.
I wrote react code that scrolls down to the end of the page after 3 seconds.

const scrollToEnd = () => { /* implementation omitted */ }

useEffect(() => {
    const id = setTimeout(() => scrollToEnd(), 3000)
    return () => clearTimeout(id)
}, [])

I want modify this code so that if the user manually scrolls the page before this timeout, the timeout is cleared.
I was thinking of a solution like:
const [hasScrolled, setHasScrolled] = useState(false);
const scrollToEnd = () => { /* implementation omitted */ }

useEffect(() => {
    const setHasScrolledCallback = () => setHasScrolled(true)
    window.addEventListener("scroll", setHasScrolledCallback);
    return () => window.removeEventListener("scroll", setHasScrolledCallback);
}, []);

useEffect(() => {
    const scrollCallback = () => { if (hasScrolled) scrollToEnd() }
    const id = setTimeout(scrollCallback, 3000)
    return () => clearTimeout(id)
}, [])

This works, but I don't think this is the correct way to approach this problem, because the scroll event is fired multiple times, even after the timeout occurs. Also the scrollCallback isn't really canceled, it runs anyway even if it does nothing.


text:
Q: How can i pass a value to local variable in terraform based on a flag. The challenge is there are multiple flags can i get some help on this please? i want to assign the local variable based on the flags. The challenge is there are multiple flags and based on the flag set to true i should have my local variable set ...
example i have the following flags
docker_enabled = true
maven_enabled = false
nugget_enabled = flase

in my local i should have a condition to set the package_type as "docker" if docker_enabled flag is true and similiarly package_type should be maven if maven_enabled is true
something like this ..
  `package_type = local.docker_enabled ? local.docker_package : null || local.generic_enabled ? local.generic_package : null || local.maven_enabled ? local.maven_package : null

  dev_repo  = formatlist("%s-dev-%s-local", local.tla, local.package_type )
  uat_repo  = formatlist("%s-uat-%s-local", local.tla, local.package_type)
  prod_repo = formatlist("%s-prod-%s-local", local.tla, local.package_type)
  virtual_repo    = formatlist("%s-%s-virtual", local.tla, local.package_type)
  premission_repos = concat(local.dev_repo, local.uat_repo, local.prod_repo)`

The issue am facing is when i make "false" all the 3 (docker,maven and nugget) it complains package_type cant be null
any help much appreciated here.. thank you


text:
Q: Join Supplier name and Supplier number using two queries I have a two queries.
  select a.supplier_nbr
     from co_global_duns_xref_t a,
          co_global_duns_t b
    where
     a.global_duns_nbr=b.global_duns_nbr(+)

and
select supplier_name_txt
from (
        select supplier_nbr,supplier_name_txt, source_system_id,
               row_number() over (order by source_system_id) precedence_nbr
        from   er_supplier_t
        where  source_system_id in (
                                        SELECT source_system_id
                                        FROM   co_source_system_t
                                        where  active_flag = 'Y' and
                                               erp_version_cd = '3.1'
                                   ) and
              -- supplier_nbr = '211394790'
      )
where precedence_nbr = 1

From the first query I will get supplier nbr . for that supplier nbr i need to search a supplier name in the second and display both.
please tell me how to do that?

A: select supplier_name_txt
from (
        select supplier_nbr,supplier_name_txt, source_system_id,
               row_number() over (order by source_system_id) precedence_nbr
        from   er_supplier_t
        where  source_system_id in (
                                        SELECT source_system_id
                                        FROM   co_source_system_t
                                        where  active_flag = 'Y' and
                                               erp_version_cd = '3.1'
                                   ) and
               supplier_nbr = '211394790'  ---
      ) a join co_global_duns_xref_t b on a.supplier_nbr = b.supplier_nbr
where precedence_nbr = 1

A: I'm still a little confused by the question, but I'll take a shot at answering it.  You should be able to put the first query inside the second one and then join by the supplier numbers.
SELECT supplier_nbr,
       supplier_name_txt
  FROM (SELECT er.supplier_nbr,
               supplier_name_txt,
               source_system_id,
               row_number() over (PARTITION BY er.supplier_nbr ORDER BY source_system_id) precedence_nbr
          FROM er_supplier_t er,
               (SELECT a.supplier_nbr
                  FROM co_global_duns_xref_t a,
                       co_global_duns_t b
                 WHERE a.global_duns_nbr=b.global_duns_nbr(+)
               ) a
         WHERE source_system_id IN (SELECT source_system_id
                                      FROM co_source_system_t
                                     WHERE active_flag = 'Y'
                                       AND erp_version_cd = '3.1'
                                   )
           AND er.supplier_nbr = a.supplier_nbr
  )
 WHERE precedence_nbr = 1

I also had to change the row_number analytic function to partition by supplier_nbr


text:
Q: Covering any surface with helix-shaped curves I have a question about the feasability of an idea.
I have a surface (which can be parametrized or defined implicitly by an equation F(x,y,z) = 0) and I want to draw some helix that fit the surface, litterally helix on the surface.
What would be the process to achieve that ?
I have a basic idea ,which is inspired from ray marching methods,  : I have my surface (which have a finite area) then I 'draw' a big helix curve around it and I decrease the radius of the helix. If the helix intersect the surface then I save that point, and finally I would obtain the set of points that draw an helix on the surface...
Feel free to ask me questions about the problem.
Thank you for your attention.
thomas

A: There are different ways to understand "drawing a helix curve" on a surface. By the way, I am not sure that you use the proper term, as a helix is a spring-like curve and is not flat at all. I will instead assume some planar curve described by an implicit C(x,y)=0 or parametric x=Xc(t),y=Yc(t) representation.
One approach is by using a (u,v) parameterization of the surface, as used in texture mapping, x=Xs(u,v), y=Ys(u, v), z=Zs(u, v). For example, for a sphere (u,v) could correspond to the angle coordinates in the spherical system. In this case, it suffices to map x=u, y=v and there will be a direct correspondence between the points of the curve and the points of the surface.
Another approach is by "extruding" the curve in the z direction to form a cylindric surface, and intersect the cylindre with the surface. In this case, you form the system
S(x, y, z)= 0
C(x, y)= 0

where z is free, and solve for (x, y) as a function of z. (You can also use the parametric equations, there are different combinations.) In fact, you perform a parallel projection of the curve.
Instead of a cylindre, you can also think of a conic surface, by choosing a vertex point, say the origin, and considering the points (zx, zy, az) where a is an "aperture" coefficient and z is free. This idea is vey close to your "radius decrease" method and corresponds to a central projection.


text:
Q: Future with Timeout in Scala Suppose I have a function, which invokes a blocking interruptible operation. I would like to run it asynchronously with a timeout. That is, I would like to interrupt the function when the timeout is expired.
So I am trying to do something like that:

import scala.util.Try
import scala.concurrent.Future

def launch(f: () => Unit, timeout: Int): Future[Try[Unit]] = {

  val aref = new java.util.concurrent.atomic.AtomicReference[Thread]()

  import ExecutionContext.Implicits.global
  Future {Thread.sleep(timeout); aref.get().interrupt} // 1
  Future {aref.set(Thread.currentThread); Try(f())}    // 2
}

The problem is that aref in (1) can be null because (2) has not set it to the current thread yet. In this case I would like to wait until aref is set. What is the best way to do that ?

A: I needed the same behavior as well, so this is how I solved it.  I basically created an object that creates a timer and fails the promise with a TimeoutException if the future hasn't completed in the specified duration.
package mypackage

import scala.concurrent.{Promise, Future}
import scala.concurrent.duration.FiniteDuration
import akka.actor.ActorSystem
import scala.concurrent.ExecutionContext.Implicits.global

object TimeoutFuture {

  val actorSystem = ActorSystem("myActorSystem")
  def apply[A](timeout: FiniteDuration)(block: => A): Future[A] = {
    val promise = Promise[A]()
    actorSystem.scheduler.scheduleOnce(timeout) {
      promise tryFailure new java.util.concurrent.TimeoutException
    }

    Future {
      try {
        promise success block
      }
      catch {
        case e:Throwable => promise failure e
      }
    }

    promise.future
  }
}

A: If you add a CountDownLatch you can achieve the behavior you want.  (Note that blocking (i.e. getting stuck at await) in lots and lots of Futures may lead to starvation of thread pools.)
import scala.util.Try
import scala.concurrent.Future

def launch(f: () => Unit, timeout: Int): Future[Try[Unit]] = {

  val aref = new java.util.concurrent.atomic.AtomicReference[Thread]()
  val cdl = new java.util.concurrent.CountDownLatch(1)

  import ExecutionContext.Implicits.global
  Future {Thread.sleep(timeout); cdl.await(); aref.get().interrupt}   // 1
  Future {aref.set(Thread.currentThread); cdl.countDown(); Try(f())}  // 2
}

A: Although you already got some answers on how to achieve it with blocking the additional thread to handle the timeout, I would suggest you to try a different way, for the reason Rex Kerr already gave. I don't exactly know, what you are doing in f(), but if it is I/O bound, I would suggest you to just use an asynchronous I/O library instead. If it is some kind of loop, you could pass the timeout value directly into that function and throw a TimeoutException there, if it exceeds the timeout. Example:
import scala.concurrent.duration._
import java.util.concurrent.TimeoutException

def doSth(timeout: Deadline) = {
  for {
    i <- 0 to 10
  } yield {
    Thread.sleep(1000)
    if (timeout.isOverdue)
      throw new TimeoutException("Operation timed out.")

    i
  }
}

scala> future { doSth(12.seconds.fromNow) }
res3: scala.concurrent.Future[scala.collection.immutable.IndexedSeq[Int]] =
  scala.concurrent.impl.Promise$DefaultPromise@3d104456

scala> Await.result(res3, Duration.Inf)
res6: scala.collection.immutable.IndexedSeq[Int] =
  Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> future { doSth(2.seconds.fromNow) }
res7: scala.concurrent.Future[scala.collection.immutable.IndexedSeq[Int]] =
  scala.concurrent.impl.Promise$DefaultPromise@f7dd680

scala> Await.result(res7, Duration.Inf)
java.util.concurrent.TimeoutException: Operation timed out.
    at $anonfun$doSth$1.apply$mcII$sp(<console>:17)
    at $anonfun$doSth$1.apply(<console>:13)
    at $anonfun$doSth$1.apply(<console>:13)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    ...

scala> res7.value
res10: Option[scala.util.Try[scala.collection.immutable.IndexedSeq[Int]]] =
  Some(Failure(java.util.concurrent.TimeoutException: Operation timed out.))

This will only use only 1 thread, that will be terminated after timeout + execution time of a single step.

A: You can go for a slightly easier approach using Await. The Await.result method takes timeout duration as a second parameter and throws a TimeoutException on timeout.
try {
  import scala.concurrent.duration._
  Await.result(aref, 10 seconds);
} catch {
    case e: TimeoutException => // whatever you want to do.
}

A: You could also try using a CountDownLatch like this:
def launch(f: () => Unit, timeout: Int): Future[Try[Unit]] = {

  val aref = new java.util.concurrent.atomic.AtomicReference[Thread]()

  import ExecutionContext.Implicits.global
  val latch = new CountDownLatch(1)
  Future {
    latch.await()
    aref.get().interrupt
  }

  Future {
    aref.set(Thread.currentThread)
    latch.countDown()
    Try(f())
  }
}

Now I'm waiting forever with my call to latch.await(), but you could certainly change that to:
latch.await(1, TimeUnit.SECONDS)

and then wrap it with a Try to handle if when/if it times out.


text:
Q: ListView или RecyclerView Filter Получаю через ретрофит списки, хочу сделать фильтр через EditText или SearchView находил в гугле кучу вариантов но не один не могу подставить под свой код, помогите пожалуйста =)
Вариант с ListView :
    public class MainActivity extends AppCompatActivity {

    TextView countryNameText;
    TextView regionText;
    TextView subRegionText;
    EditText search;

    final String LOG_TAG = "myLogs";

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

        countryNameText = (TextView) findViewById(R.id.country_name_id);
        regionText = (TextView) findViewById(R.id.region_id);
        subRegionText = (TextView) findViewById(R.id.post_reg_id);
        search = (EditText) findViewById(R.id.search_id);

        final ListView listView = (ListView)findViewById(R.id.listView);

        FileInputStream fis;
        try {
            fis = openFileInput("countries_file");
            ObjectInputStream ois = new ObjectInputStream(fis);
            final ArrayList<Countrys> returnlist = (ArrayList<Countrys>) ois.readObject();
            ois.close();
            listView.setAdapter(new MyAdapter(this, returnlist));
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent mIntent = new Intent(MainActivity.this, SecondActivity.class);
                    Countrys countrys = returnlist.get(position);
                    mIntent.putExtra("key", countrys);
                    startActivity(mIntent);
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Retrofit.getCountries(new Callback<List<Countrys>>() {
            @Override
            public void success(final List<Countrys> countries, Response response) {
                Log.d(LOG_TAG, "получили данные");

                FileOutputStream fos = null;
                try {
                    fos = openFileOutput("countries_file", Context.MODE_PRIVATE);
                    ObjectOutputStream oos = new ObjectOutputStream(fos);
                    oos.writeObject(countries);
                    oos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                listView.setAdapter(new MyAdapter(MainActivity.this, countries));
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent mIntent = new Intent(MainActivity.this,SecondActivity.class);
                        Countrys countrys = countries.get(position);
                        mIntent.putExtra("key", countrys);
                        startActivity(mIntent);
                    }
                });

            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT).show();

            }
        });
    }

    class MyAdapter extends ArrayAdapter<Countrys> {

        public MyAdapter(Context context, List<Countrys> objects) {
            super(context, R.layout.list_item, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            View rowView = convertView;
            if (rowView == null) {
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rowView = inflater.inflate(R.layout.list_item, parent, false);
                holder = new ViewHolder();
                holder.textNameofCoutry = (TextView) rowView.findViewById(R.id.country_name_id);
                holder.textRegion = (TextView) rowView.findViewById(R.id.region_id);
                holder.textSubRegion = (TextView) rowView.findViewById(R.id.post_reg_id);
                rowView.setTag(holder);
            } else {
                holder = (ViewHolder) rowView.getTag();
            }

            Countrys countries = getItem(position);
            holder.textNameofCoutry.setText(countries.getName());
            holder.textRegion.setText(countries.getRegion());
            holder.textSubRegion.setText(countries.getSubregion());

            return rowView;
        }

        class ViewHolder {

            public TextView textNameofCoutry;
            public TextView textRegion;
            public TextView textSubRegion;
        }

    }
}

Вариант с RecyclerView
    public class MainActivity extends AppCompatActivity {

    TextView countryNameText;
    TextView regionText;
    TextView subRegionText;
    EditText search;

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

        countryNameText = (TextView) findViewById(R.id.country_nameId);
        regionText = (TextView) findViewById(R.id.region_id);
        subRegionText = (TextView) findViewById(R.id.sub_region_id);
        search = (EditText) findViewById(R.id.search_id);

        final RecyclerView list = (RecyclerView) findViewById(R.id.listView);

        Retofit.getCountries(new Callback<List<Countries>>() {
            @Override
            public void success(final List<Countries> countries, Response response) {

                LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
                list.setLayoutManager(layoutManager);
                list.setAdapter(new RecyclerViewAdapter(countries, new OnItemClickWatcher<Countries>() {
                    @Override
                    public void onItemClick(View v, int position, Countries item) {
                        Intent mintent = new Intent(MainActivity.this,SecondActivity.class);
                        Countries countries1 = countries.get(position);
                        mintent.putExtra("Key", countries1);
                        startActivity(mintent);
                    }
                }));

            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT).show();

            }
        });

    }

    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements View.OnClickListener {

        private OnItemClickWatcher<Countries> watcher;
        List<Countries> countries;

        public RecyclerViewAdapter(List<Countries> countries, OnItemClickWatcher<Countries> watcher){
            this.countries = countries;
            this.watcher = watcher;

        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
            View v = getLayoutInflater().inflate(R.layout.list_item, parent,false);
            return new ViewHolder(v, watcher, countries);

        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int i) {
            holder.name.setText(countries.get(i).getName());
            holder.region.setText(countries.get(i).getRegion());
            holder.subregion.setText(countries.get(i).getSubregion());
          holder.image.setImageResource(countries.get(i).getImage());

        }

        @Override
        public int getItemCount() {
            return countries.size();
        }

        @Override
        public void onClick(View v) {

        }

        class ViewHolder extends RecyclerView.ViewHolder{
            private TextView name;
            private TextView region;
            private TextView subregion;

            public ViewHolder(View itemView, final OnItemClickWatcher<Countries> watcher, final List<Countries> names) {
                super(itemView);
                name = (TextView) itemView.findViewById(R.id.country_nameId);
                region = (TextView) itemView.findViewById(R.id.region_id);
                subregion = (TextView) itemView.findViewById(R.id.sub_region_id);
              subregion = (ImageView) itemView.findViewById(R.id.imageView);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        watcher.onItemClick(v, getAdapterPosition(), names.get(getAdapterPosition()));
                    }
                });
            }
        }

    }
}

A: *

*Вам нужны два списка объектов в адаптере. Один основной, не отображаемый. Второй же наполнять отображаемыми, отфильтрованными данными и его отображать.

*Также нужен метод в адаптере, принимающий строку (или ещё что), очищающий отображаемый список данных и пробегающийся циклом по основному списку с данными, находя средь них подходящие и добавляя их в список отображаемых данных. После черего адаптер надо уведомить об изменении данных вызовом notifyDataSetChanged()

*Теперь при вводе данных в текстовое поле вам надо получить ваш адаптер и вызвать на нём метод из второго пункта, передав в него введённый текст.


text:
Q: Foursquare Get All Unique Checkins Once Time (Checkins/VenueHistory) I need to get user's all unique checkins data.
For example, I have 12000 checkins, which 4500 checkins are unique, 7500 are multiple.
There are 2 ways to get user checkins.

*

*users/self/checkins

*users/self/venuehistory

When I used 1st method, I get max 250 items once time. I have to use a loop, but it is increasing my request count. I will make 48 (12000/250) request for get 12000 checkins, also I get 7500 checkins for nothing, because these are multiple checkins. I need just 4500 unique checkins.
When I use 2nd method, I get max unique 3000 items once time. But there are no offset, skip or paging at this method. I cant get 1500 items like this.
Is there any solution to do this once time or less request count?


text:
Q: c++ statx() syscall do not work in Cloud Foundry I would like to use syscall statx() in app deployed in Cloud Foundry. Unfortunately it does not work due to
"EPERM: Operation not permitted".

but I can use stat() without any problems.
Is there any way to allow my app to work?
Hint: I believe, the problem could be the configuration of the seccomp profile in runtime garden-runC - it filters allowed syscalls and statx is not on the allowed list.

A: I found workaround: if privileged container support is enabled, statx() can be used and works well
https://github.com/cloudfoundry/cf-deployment/blob/main/operations/enable-privileged-container-support.yml
Unfortunately, this is really bad idea and it is decreases security. More details: https://docs.cloudfoundry.org/concepts/container-security.html


text:
Q: Proof of weaker Baker-Campbell-Hausdorff Formula Prove the weaker form of the BCH Formula:
$$e^A e^B = e^{A + B + \frac{1}{2}[A,B]} $$
with the assumption $[A, [B, A]] = 0; [B, [B,A]] = 0$
Start with $f(\lambda) = e^{\lambda A} e^{\lambda B} e^{-\lambda (A + B)}$ and establish the differential equation $\frac{df}{d\lambda} = \lambda [A, B] f.$ Then integrate it to obtain the formula.
What I did is I worked backwards.It is very easy to see that
$$ \frac{df}{d\lambda} = \lambda[A,B]f$$
$$ \frac{df}{f} = \lambda[A,B] d\lambda $$
$$ \log f = \frac{\lambda^2}{2}[A,B] $$
$$ f = e^{\lambda A} e^{\lambda B} e^{-\lambda (A + B)} = e^{\frac{\lambda^2}{2}[A,B]} $$
$$ e^{\lambda A} e^{\lambda B} = e^{\lambda (A+B)} e^{\frac{\lambda^2}{2} [A,B]}$$
then take $\lambda = 1 $ to obtain
$$e^A e^B = e^{A + B + \frac{1}{2}[A,B]} $$
Now the hard part is obtaining the differential equation.
$$f(\lambda) = e^{\lambda A} e^{\lambda B} e^{-\lambda (A + B)}$$
$$ \frac{df}{d\lambda} = Ae^{\lambda A}e^{\lambda B} e^{-\lambda (A+B)} + e^{\lambda A} Be^{\lambda B} e^{-\lambda (A+B)} - e^{\lambda A} e^{\lambda B} e^{-\lambda (A + B)} (A+B) $$
The best I could make from this mess was
$$ \frac{df}{d\lambda} = [A,f] + e^{\lambda A}e^{\lambda B} [B, e^{-\lambda (A+B)}] $$
It's really difficult for me to be able to use the assumptions $[A, [B, A]] = 0; [B, [B,A]] = 0$ nor make $\lambda$ come down the exponent in the differential equation.
Can you please give a hint on how to proceed with this problem? Any helpful hint will be extremely appreciated! Thank you in advance!

A: First, I assume finite dimensional operators: otherwise you need to check certain boundedness conditions on the operators. Because the CBH series is here truncated by the vanishing double commutators, the conditions for linear operators on e.g. $\mathbf{L}^2(\mathbb{R})$ will be mild.
You need to practice operations with $\mathrm{Ad}$. Look up the following. In the Lie group $\mathfrak{G}$ with algebra $\mathfrak{g}$ the tangent vector to the path:
$$\sigma:\mathbb{R}\to\mathfrak{G};\;\sigma(\tau) = e^A\,e^{\tau\,B}\,e^{-A};\;A,\,B\in\mathfrak{g}\tag{1}$$
at the identity is $\mathrm{Ad}(e^A)\,B=\exp(\mathrm{ad}(A))\,B$. Here $\mathrm{Ad}:\mathfrak{G}\to GL(\mathfrak{g})$ is the Adjoint Representation. It is a Lie group homomorphism from the general Lie group $\mathfrak{G}$ to the matrix Lie group $GL(\mathfrak{g})$. Its kernel is the centre of $\mathfrak{G}$. Since it is a homomorphism, we have $\mathrm{Ad}(\gamma\,\zeta) = \mathrm{Ad}(\gamma)\,\mathrm{Ad}(\zeta);\,\forall \gamma,\,\zeta\in\mathfrak{G}$. Another useful identity is:
$$\begin{array}{lcl}\mathrm{Ad}(e^A)\,B &=& \exp(\mathrm{ad}(A))\,B \\&=&B + \mathrm{ad}(A) B + \frac{\mathrm{ad}(A)^2}{2!}\,B +\cdots \\&=& B+ [A,\,B] + \frac{1}{2!}\, [A,\,[A,\,B]] + \cdots\end{array}\tag{2}$$
and this series is universally convergent if the operator $B\mapsto[A,\,B]$ is suitably bounded (e.g. $\left\|[A,\,B]\right\| \leq K(A)\,\left\|B\right\|$ for some $K(A)\in\mathbb{R}$ - this is certainly true in finite dimensions).
Now, by (1) and the homomorphism property ($\mathrm{Ad}(e^{\lambda\,A}\,e^{\lambda\,B}) = \mathrm{Ad}(e^{\lambda\,A})\,\mathrm{Ad}(e^{\lambda\,B})$), you can find that:
$$\begin{array}{lcl}\mathrm{d}_\lambda f &=& A\,e^{\lambda\, A}\,e^{\lambda\,B}\,e^{-\lambda\,(A+B)} +  e^{\lambda\, A}\,B\,e^{\lambda\,B}\,e^{-\lambda\,(A+B)} - e^{\lambda\, A}\,e^{\lambda\,B} \,(A+B)\,e^{-\lambda\,A+B)}\\
&=& \left(A + e^{\lambda\,A}\,B\,e^{-\lambda\,A} - e^{\lambda\,A}\,e^{\lambda\,B}\,(A+B)\,e^{-\lambda\,B}\,e^{-\lambda\,A}\right)\,e^{\lambda\, A}\,e^{\lambda\,B}\,e^{-\lambda\,(A+B)}
\\
&=&\left(A+\mathrm{Ad}(e^{\lambda\,A})\left(B-\mathrm{Ad}(e^{\lambda\,B})\,(A+B)\right)\right)\,f\end{array}\tag{3}$$
All the above is perfectly general. You need to specialise it to your truncated case. So use the universally convergent (and here truncated to two terms) series (2) to expand $A+\mathrm{Ad}(e^{\lambda\,A})\left(B-\mathrm{Ad}(e^{\lambda\,B})\,(A+B)\right)$ and truncate it for your special case and I think you should make some headway.

A pedantic peeve: although both orders for the name are quite common, the order that accurately reflects the historical precedence is "Campbell-Baker-Hausdorff" as each of the authors made their contributions in 1897/1898 (Campbell), 1905 (Baker) and 1906 (Hausdorff), respectively. Each was aware of their forerunners' work, but, as stated in Fascicule 16 Ch 1 of Bourbaki (1960), "each found the demonstrations of his forerunners unconvincing(!)". That statement always makes me giggle and gives some comfort that I'm not the only one with about a 5% comprehension rate in reading technical literature (I reckon I need to read a paper about 20 times on average to "get" it). An amusing fact is that none of these three actually worked out the series. Instead, they established the theorem that the series was convergent within some neigbourhood of $\mathbf{0}$ in the Lie algebra and comprises linear and Lie bracket operations only. The formula itself is due to Dynkin and was fully worked out in 1947!


text:
Q: Add multiple bullets of text to PowerPoint slide via officer Using the officer package in R, when working with a PowerPoint you can add text with the function ph_with_text. However, it's not clear how to add multiple bullets of text or how to set the level of indentation.  I would like to achieve the following structure:

*

*Question 1

*

*Answer 1

*Answer 2

*Question 2

*

*Answer 1

*Answer 2

I have tried two methods which both produce very wrong results. I have tried taking my text and adding \n and \n\t to create linebreaks and tabs (like how I would create the structure in PowerPoint.
doc = read_pptx()
doc = add_slide(layout = "Title and Content", master = "Office Theme")
doc = ph_with_text(doc,type = "body",
      str = "Question 1\n\tAnswer 1\n\tAnswer 2\nQuestion 2\n\tAnswer 1\n\tAnswer 2",
      index = 1)

This creates the bullets, but not the depth. There's a whitespace tab after each bullet before each answer. Additionally, these are not new bullets, if I manually edit the file and press tab on one bullet point, every point after is also shifted. Clearly the correct structure hasn't been acheived.
I have also tried just calling ph_with_text repeatedly.
doc = add_slide(layout = "Title and Content", master = "Office Theme")
doc = ph_with_text(doc,type = "body", str = "Question 1", index = 1)
doc = ph_with_text(doc,type = "body", str = "Answer 1", index = 1)
doc = ph_with_text(doc,type = "body", str = "Answer 2", index = 1)
doc = ph_with_text(doc,type = "body", str = "Question 2", index = 1)
doc = ph_with_text(doc,type = "body", str = "Answer 1", index = 1)
doc = ph_with_text(doc,type = "body", str = "Answer 2", index = 1)

But this ends up overlaying the text on the same line and it's an unreadable mess.
How do I, via officer, add text to a slide achieving multiple bullets and indented sub-elements?

A: The function ph_with_ul is the function you need
library(magrittr)
pptx <- read_pptx()
pptx <- add_slide(x = pptx, layout = "Title and Content", master = "Office Theme")
pptx <- ph_with_text(x = pptx, type = "title", str = "Example title")
pptx <- ph_with_ul(
  x = pptx, type = "body", index = 1,
  str_list = c("Level1", "Level2", "Level2", "Level3", "Level3", "Level1"),
  level_list = c(1, 2, 2, 3, 3, 1),
  style = fp_text(color = "red", font.size = 0) )
print(pptx, target = "example2.pptx")


text:
Q: How to transfer and parse snap graph from python to c++ Stanford SNAP is a well-known package for graph mining, and has both Python implementation and C++ implementation.
I have some code in python to do graph mining using SNAP. I also have a C++ function process the snap graph. Now I need to write a wrapper so that this C++ function can be invoked from Python.
The problem is that I don't know how to parse/dereference the snap graph object from Python to C++.
The python code looks like: (More explanations come after the code examples)
import my_module;
import snap;

G = snap.GenRndGnm(snap.PUNGraph, 100, 1000);

print(type(G));
A = my_module.CppFunction(G);  # customized function
print(A);

The CPP wrapper my_module_in_cpp.cpp looks like:
// module name: my_module, defined in the setup file
// function to be called from python: CppFunction
#include <Python.h>
//#include "my_file.h" // can be ignored in this minimal working example.
#include "Snap.h"

#include <iostream>

static PyObject *My_moduleError;

  // module_name_function, THE CORE FUNCTION OF THIS QUESTION
static PyObject *my_module_CppFunction(PyObject *self, PyObject *args) {
  PUNGraph G_py;
  int parseOK = PyArg_ParseTuple(args, "O", &G_py);
  if (!parseOK) return NULL;

  std::cout << "N: " << G_py->GetNodes() << ", E: " << G_py->GetEdges() << std::endl;
  fflush(stdout);
  if ((G_py->GetNodes()!=100)||(G_py->GetEdges()!=1000)) {
    PyErr_SetString(My_moduleError, "Graph reference incorrect.");
    return NULL;
  }

  PyObject *PList = PyList_New(0);

  PyList_Append(PList,Py_BuildValue("i",G_py->GetNodes()));
  PyList_Append(PList,Py_BuildValue("i",G_py->GetEdges()));
  return PList;
}

// To register the core function to python
static PyMethodDef CppFunctionMethod[] = {
  {"CppFunction", my_module_CppFunction, METH_VARARGS, "To call CppFunction in C++"},
  {NULL,NULL,0,NULL}
};

extern "C" PyMODINIT_FUNC initmy_module(void) {
  PyObject *m =  Py_InitModule("my_module",CppFunctionMethod);
  if (m==NULL) return;
  My_moduleError = PyErr_NewException("my_module.error", NULL, NULL);
  Py_INCREF(My_moduleError);
  PyModule_AddObject(m, "error", My_moduleError);
}

I'm using Ubuntu, python-2.7. In case someone may want to re-produce the problem, the setup.py file is also provided.
from distutils.core import setup, Extension

module1 = Extension('my_module',\
    include_dirs = ['/usr/include/python2.7/','/users/<my_local>/Snap-3.0/','/users/<my_local>/Snap-3.0/snap-core','/users/<my_local>/Snap-3.0/glib-core'],
    library_dirs = ['/users/<my_local>/Snap-3.0/snap-core/'],
    extra_objects = ['/users/<my_local>/Snap-3.0/snap-core/Snap.o'],
    extra_compile_args=['-fopenmp','-std=c++11'],
    extra_link_args=['-lgomp'],
    sources = ['my_module_in_cpp.cpp'])

setup (name = 'NoPackageName', version = '0.1',\
    description = 'No description.', ext_modules = [module1])

Every time I run the python code above, the error message "Graph reference incorrect." is displayed.
Apparently G_py->GetNodes() and G_py->GetEdges() cause the problem. This must result from G_py not pointing to the right address/in right format. I tried using TUNGraph in the cpp code as well, it still does not point to the correct address. Is there any way that the pointer in C++ can point to the correct address of the original C++ object?
Although in general it is hard to dereference a PythonObject from C++, but in this case I think it is doable since Snap-Python is also implemented in C++. We just need to unwrap its python wrapper. And the snap authors also provided the SWIG files.
Of course we can write the graph file in the disk, and read from that, but this will result in I/O and incur extra time consumption. And the snap-user-group does not have as much user traffic as stackoverflow.
BTW, there are networkx and stanford-nlp tags, but no stanford-snap or similar tag referring to that tool. Can someone create such a tag?


text:
Q: Django admin widget override for all of abstract model I have an abstract model that contains a field type that I would like to override the widget for in the admin view.
Now you can't register abstract models in the admin view so I have had to override the widget for each of the models that inherit from the abstract model. This feels clunky - is there a neater way to do this?
models.py

class MyAbstractModel(Model):
    field_with_widget_i_want_to_override = MyFieldType()

    class Meta:
        abstract = True

class ModelA(MyAbstractModel):
    extra_field = AnotherFieldType()

class ModelB(MyAbstractModel):
    different_extra_field = ADifferentFieldType()

admin.py
class ModelAAdmin(ModelAdmin):
    formfield_overrides = {
        MyFieldType: {'widget': MyWidget},
    }

class ModelBAdmin(ModelAdmin):
    formfield_overrides = {
        MyFieldType: {'widget': MyWidget},
    }

admin.site.register(ModelA, ModelAAdmin)
admin.site.register(ModelB, ModelBAdmin)

Now my actual project is a bit more complicated so I don't want to combine ModelAdmins when registering the models, There are also many more Models that inherit from the abstract base model so I feel like I'm repeating myself alot.
Alternatively is there a way to globally overide the widget used in the admin for a field type (for all models)?

A: Abstract models can't be registered as ModelAdmin as they are abstract and django can't treat them as data models so most of admin functionalities can't be applied on these classes- so you need to override it with an empty class at least like at documentation here
Abstract classes
There's no way to assign data to abstract models


text:
Q: Is it possible to get a time for state transition for an Amazon EC2 instance? I'm accessing EC2 with the aws-sdk for Ruby. I have an array of instances from describe_instances().
This provides me with the state of the instances and even a state transition reason. But how can I get a time for the state transition?
Edit
So I have:
client=Aws::EC2::Client()
resp =client.describe_instances({ filters })

and I would need
resp.reservations[0].instances[0].state_transition_time #=> Time

similar to
resp.reservations[0].instances[0].state_transition_reason #=> String

A: This information is not available via the Amazon EC2 API at this time. The aws-sdk gem returns all of the information available from the DescribeInstances operation as documented here: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html

A: The State Transition Reason is not always populated with a date and time and may not even be populated at all per the documentation. I have not found any hints in the documentation that specify the conditions in which you DO get a date/time, but in my experience, the date/time are present in the State Transition Reason for between 30 and 90 days. After that, the reason seems to persist, but the date is dropped from the string.
All of the documentation that I can find is listed here:

*

*Attribute Definition

*EC2 API - Ruby


text:
Q: Cannot get jQuery-UI dialog to open with dynamically created links OK, strange issue here.
I have the following code:

Pretty simple and straightforward, works like a charm when the links that are clicked are not dynamically loaded. When they are dynamically loaded, I get the following error.
Uncaught TypeError: $(...).empty(...).append(...).dialog is not a function

I have put the referenced div into the non-dynamic part of the page, I have initialized the dialog with the following function as well, which is referenced in the snippet above.
function refreshDialog(){
    //kick up the hover form stuff
    $(".hover-form").dialog({
        autoOpen: false,
        draggable: false,
        minWidth:350,
        minHeight: 200,
        modal: true,
        buttons: [
            {
            text: "Close",
            icons: false,
            click: function() {
            $( this ).dialog( "close" );
            }

            }
        ]
    });
}

If it is relevant, here is the snippet that dynamically loads the next month in the calendar.
$("#calendar_container").on("click","#previous_month",function(e){

    //get data from link
    res = $(this).attr("href");
    res = res.replace("schedule","ajax");
    res = res.replace("view","standalone_calendar");

    $("#calendar_container").empty();
    $("#calendar_container").html("");

    $.ajax({
        async: true,
        url: res,
        method: "post",
        data: "",
        success: function(c){
            $("#calendar_container").empty().append(c);
        }
    });

    return false;
});
$("#calendar_container").on("click","#next_month",function(e){

    //get data from link
    res = $(this).attr("href");
    res = res.replace("schedule","ajax");
    res = res.replace("view","standalone_calendar");

    $("#calendar_container").empty();
    $("#calendar_container").html("");

    $.ajax({
        async: true,
        url: res,
        method: "post",
        data: "",
        success: function(c){
            $("#calendar_container").empty().append(c);
        }
    });

    return false;
});

A: Not sure if this is the best solution, but I moved the call to my refreshDialog() function into the ajax success portion and everything is working smoothly.


text:
Q: How to render an array in an html file? - Node.js, ejs I'm working on a project, which will use given coordinates from a txt file and graph them.
My problem right now: I'm trying to use ejs to render the coordinates into my html file, but it just isn't working right. Ejs always just renders: undefined.
Here is the code:
var http = require('http'),
    fs = require('fs'),
    express = require('express'),
    app     = express();
    app.use(express.bodyParser());
    app.set('view engine', 'ejs');
    app.engine('html', require('ejs').renderFile);
    app.use(express.static(__dirname + '/public'));

//Readerfunction
function readLines(input, done) {
   //.....

function done(arr) {
    var obj = {};
    var key1 = arr[0][0];
    var key2 = arr[0][1];
    obj[key1] = [];
    obj[key2] = [];

    arr.shift();

    arr.forEach(function (item) {
        obj[key1].push(item[0]);
        obj[key2].push(item[1]);
    });

      console.log('X:', obj[key1]); // all the variables are logged correctly.
      console.log('Y:', obj[key2]);

    app.get('/', function(req, res) {
          res.render('graph.html', {cordinates: obj});
});
    app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});
}

In the html file:
<%= cordinates.obj %>

I hope you can help me, solve this problem! :-)
Greetings,
JS

A: Well, I think here is the problem: you are passing obj to render as coordinates, so you should use coordinates variable in your template directly, no it's obj property, which is non-existent. I'm not sure if it will be rendered as proper array though, maybe you'll need a loop to print it's elements.


text:
Q: AWS ALB (Application Load Balancer) - "502 Bad Gateway" Issue
*

*We have using multi-container docker environment for our project to deploy the microservices(Scala) in AWS. We are using AWS ECS (Elastic container service) to deploy and manage the application in AWS Cloud. We have placed 5 microservices within separate Task definition and launched it using ECS.

*We have setup ALB (Application Load Balancer) and mapped with ECS and got the ALB (CName) domain.  We have created new listener rules to route requests to targets API is routing (Path base routing)
http://umojify-alb-1987551880.us-east-1.elb.amazonaws.com

*Finally, we got the response "502 Bad Gateway" and "Status code: 405". Please guide us on this issue.

*Where and why the issue came? Is it for ALB or API?

API URL:
http://umojify-alb-1987551880.us-east-1.elb.amazonaws.com/save-user-rating

A: AWS ECS uses dynamic ports to connect to the microservice containers. Please check if the ports are open on the container hosts(instances). I faced the same issue and had to open all the TCP ports for the ALB. See the AWS documentation for configuring the security group rules for container instances -
AWS security group rules for container instances


text:
Q: Emacs regex search then write I would like to find/extract a group in each line of a buffer, then write it to a new buffer.
So in my comma-delimted data file, my lines basically look like this:
'A-field','B-field','C-field','D-field'

i.e., four single-quoted fields of data per line. I want to extract the quoted B-field and write it to a new buffer.
Is it possible at the elisp repl to extract from one buffer and write that to a new buffer? Or is this something you'd write as a stand-alone .el file then call from the buffer (M-my-extract-write) from the mini-buffer?

A: Here's one way to do that:

*

*copy&paste your file's content to a new buffer.

*in the new buffer do C-u C-s ^[^,]*,'\([^']*\)',.* M-% \1 RET !.

A: I recommend multiple-cursors + sexp movements for stuff like this.
Macros also work well, but the immediate feedback of multiple-cursors is nice.
Writing elisp to handle simple repetitive tasks is overkill.


text:
Q: Use base64Data to save image to camera roll with meadiaScanner:true but It saved wrong place in Ionic 4 I am coding an App have a feature which save image to gallery in Ionic 4. After research I found base64ToGallery to save img to camera roll with very detail. But it didn't save to camera roll. It save to Library location.
There is my code.
let base64Data = this.convertToDataURLviaCanvas(this.listItem[0], 'image/jpeg').then(base64Data => {
      this.base64ToGallery.base64ToGallery(base64Data, { prefix: '_img', mediaScanner: true  }).then(
        res => console.log('Saved image to gallery ', res),
        err => console.log('Error saving image to gallery ', err)
      );
    }

I expect the output show /Media/.... or something to tell me image saved in camera roll. But the actual output is:
2019-05-13 16:17:18.269107+0700 MyApp[3383:933160] Saved image to gallery  /var/mobile/Containers/Data/Application/8214F568-87C5-494C-8CDE-C17C55BBEB83/Library/NoCloud/_img122206160949.png

Base64ToGallery in ionic 4 said:
Base64ToGalleryOptions
mediaScanner    boolean
On Android runs Media Scanner after file creation. On iOS if true the file will be added to camera roll, otherwise will be saved to a library folder.

I'm really appreciates if anyone can help me fix this. I'm using ionic 4, angular 7, ios 12.2.


text:
Q: Laravel order of included libraries and custom code referencing these In resources/js/app.js there is this line: require('./bootstrap');.
If I add a line below that, require('./custom-stuff');, put custom-stuff.js in resources/js I can see that it's included in app.js. So far so good.
I'm puzzled however by the order that the files are included. If in custom-stuff.js I add:
$(function () {
    $('[data-toggle="tooltip"]').tooltip()
});

it doesn't activate the tooltip, while I see the code being included in app.js.
If I add the tooltip activation code above in my Blade template right before the closing </body> tag (and before the inclusion of app.js), it does work.
Why is this? I would like to keep everything in app.js including custom code that refers to other libraries that are included.

A: You may try re-ordering the build combination in for your app.js and try checking your webpack.mix.js to do that.


text:
Q: Excel: How to create a list of all values in a column that fall between two other values provided Just wondering if someone can help me with a formula.
In column A, I have a list of incremental values (complex decimals).
I would like to create a list in column D of all values in column A that fall between a lower and upper value in column B and C.
Thanks!
image

A: There is a brilliant solution for this in http://chandoo.org/wp/2012/10/04/formula-forensics-no-030/
I use it a lot and I modified the formula based on your image.
=IFERROR(INDEX($A$2:$A$25, MATCH(MIN(MODE.MULT(IF(($A$2:$A$25>$B$2)*($A$2:$A$25<$C$2)*NOT(COUNTIF($D$1:$D1, $A$2:$A$25)), (COUNTIF($A$2:$A$25, "<"&$A$2:$A$25)+1)*{1,1}))), IF(Criteria,COUNTIF($A$2:$A$25, "<"&$A$2:$A$25)+{1}), 0)), "")

Put the formula in D2 and use Ctrl-Shift-Enter as it is an array formula. Then copy it down.
If you want numbers that are equal to the cells in B2, C2 to be included, modify the ">B2" to ">=B2" and similarly for C2.


text:
Q: Can't log into Minecraft or Mojang I wanted to use a modpack and used my account. I was asked to login to mojang, so I did. But it said it was incorrect. I reset my password and it still doesn't work. I can't log into minecraft.net or the vanilla launcher. My firewall does not block java and I have an English keyboard.

A: With minecraft it is now essential to login with your EMAIL  instead of your username, that seems to be where a lot of people fail at logging in


text:
Q: adb devices not working for redmi note 3 on ubuntu
*

*Enabled the developer options/USB debugging on redmi note 3 device

*Tried "adb devices" command ON UBUNTU Terminal, no devices listed

*"lsusb", displays the below, No vendor name displayed

"Bus 002 Device 015: ID 2717:ff48"

Is there any specific drivers for Redmi note 3 device for ubuntu operating system?
Is there general driver software for all the different device vendors ?

A: You need to add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property.
Use this format to add each vendor to the file(example vendor ID is for HTC):
SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"

For a list of vendor IDs, see USB Vendor IDs at android-udev-rules


text:
Q: Does Google Cloud Vision API detect formatting in OCRed text like bold, italics, font name (helvetica or times new roman), etc? The quick brown fox jumps over the lazy dog
In such a case like this, assuming there are different font families too, can cloud VIsion API detect this. Or any other OCR API detect this cleanly. Tesseract has capabilities but its so inaccurate.

A:
Does google cloud vision API detect formatting in OCRed text like
bold, italics, font name (helvetica or times new roman), etc?

Unfortunately, no.
In my project, I use ABBYY Cloud OCR SDK for this purpose. If you want to try, you can start free trial which includes 500 free requests (pages). After you create your trial account, you will receive an email from ABBYY which will contain your Application ID and Application password. Use these 2 values to create your authentication header according to Authentication.
See the following example:

*

*Perform processImage request. Pass your image in the request body.

Request:
POST / https://cloud.ocrsdk.com/v2/processImage?exportFormat=xml&profile=documentConversion&xml:writeFormatting=true
Authorization: <your token>

Response:
{
    "taskId": "a226a0b6-6705-4d6f-9f4c-517fa9b4e28e",
    "registrationTime": "2020-07-26T09:42:39Z",
    "statusChangeTime": "2020-07-26T09:42:39Z",
    "status": "Queued",
    "filesCount": 1,
    "requestStatusDelay": 10000
}

*Perform getTaskStatus request in order to check if your task is completed. Use taskId from the response of the previous step.

Request:
GET / https://cloud.ocrsdk.com/v2/getTaskStatus?taskId=a226a0b6-6705-4d6f-9f4c-517fa9b4e28e
Authorization: <your token>

Response:
{
    "taskId": "a226a0b6-6705-4d6f-9f4c-517fa9b4e28e",
    "registrationTime": "2020-07-26T09:42:39Z",
    "statusChangeTime": "2020-07-26T09:42:40Z",
    "status": "Completed",
    "filesCount": 1,
    "requestStatusDelay": 0,
    "resultUrls": [
        "https://ocrsdk.blob.core.windows.net/files/a226a0b6-6705-4d6f-9f4c-517fa9b4e28e.result?sv=2012-02-12&se=2020-07-26T19%3A00%3A00Z&sr=b&si=downloadResults&sig=4k9FcRoBfhodq%2BMj%2Ffj%2BGLBfwK2BsO7sj15JQOLcArk%3D"
    ]
}

*Download the result (see resultUrls from the response of the previous step).

I used the following picture

and received the following result

A: ABBYY Cloud OCR will be quite accurate, but at the end, everything depends on your fonts and scanning quality.


text:
Q: Adding persistence to local storage to a Vue app I am learning to deal with VueJS and made a simple todo app. It works well, but I want to store data locally and make it persistent even if there is a page reload.
This is the code produced following instruction of a few useful tutorials (leaving CSS outside to ease readability):
<template>

{{ header }}

        <md-field class="todo-input">
          <md-input
            v-model="currentTodo"
            @keydown.enter="addTodo()"
            placeholder="Add a todo! It's easy!"
          />
        </md-field>

              <input
                class="toggle-todo"
                type="checkbox"
                v-model="todo.completed"
              />

              {{ todo.label }}

              <input
                v-else
                class="todo-item-edit"
                type="text"
                v-model="todo.label"
                @keyup.enter="completedEdit(todo)"
              />

              delete

</template>

As it is, all the JS part referring to mount and watch does not work. I am able to add new todos and delete them as I wish, but it does not retain the data if the user reloads the page.
Could some of the colleagues spot what I am missing here?

A: It's a problem of code organization:
Your mounted and watch sections are currently inside the methods section, which will prevent them from firing as expected.
Move those out into their own sections (both should be at the same level as methods) and you should be all set.
With those edits and nothing else, I've got your code working in a fiddle here: https://jsfiddle.net/ebbishop/dc82unyb/


text: Q: JQuery-UI Style Autocomplete in JavaScript Only (No Includes) Mad props to JQuery and JQuery-UI, specifically the autocomplete plugin, as it is super handy for reducing cart abandonment and reducing UX friction in filling out address forms.  But JavaScript Reactive Extensions offer an elegant solution too, one that I'd like to explore and phase out the use of JQuery altogether.  After seeing some RX examples and the sites youmightnotneedjquery.com and rxmarbles.com I'm inspired to try a new approach.  Besides throttling and debouncing, the question becomes, how would someone create the 'pick list' below the input field?  Further, how to implement in pure rxjs?


text:
Q: Import Java class from Firebase I understand how to push a class to Firebase using the following code:
WeekViewEvent event = new WeekViewEvent();
DatabaseReference myRef = database.getReference();
myRef.child("Events").push().setValue(event);

I'm wondering what is the easiest way to retrieve this class (or any other class based on an id, or field) back into Android? I'm sure there's an easy way, but all I've found so far is the following which doesn't work:
    public void importSchedule(String ownerName){
    DatabaseReference events = FirebaseDatabase.getInstance().getReference("Events");

    Query allOwnersEvents = events.equalTo(ownerName);

    allOwnersEvents.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot post : dataSnapshot.getChildren()) {
                WeekViewEvent allDay = post.child(WeekViewEvent.class); // This doesn't compile, as the type needs to be String
            }
        }
        public void onCancelled(DatabaseError databaseError) {}
    });

The WeekViewEvent objects have the following variables:
public class WeekViewEvent {
    private long mId;
    private Calendar mStartTime;
    private Calendar mEndTime;
    private String mName;
    private String mLocation;
    private int mColor;
    private boolean mAllDay;
    private String owner;

    //setters and getters
}

and in my Firebase, the object I'm trying to query is:
Events{
 -siX1hB9k-HpCmfO3n:{
    allDay:"false",
    color:"-477870",
    endTime:{
      endHour:4,
      endMinute:10,
      ...},
    id: 1,
    location:"location",
    name: "hi",
    owner: "a@a.ca",
    startTime:{
      startHour:3,
      startMinute:45,
      ...}
    }
}

A: You can try following method to retrieve your class' object
Map<String, Object> eventMap;
for(DataSnapshot da :dataSnapshot.getChildren())
{
    if (da.getValue() instanceof Map) {
        eventMap = (HashMap<String, Object>)
                da.getValue();
        Map<String, Object> eventMap = weekMap;
        WeekViewEvent event = new WeekViewEvent();
    }
}

A: To fix t his, please use this code:
DatabaseReference myRef = database.getReference();
DatabaseReference myNewRef = myRef.child("Events").push();
String pushedKey = myNewRef.getKey();
myNewRef.setValue(event);

and to get the data back:
public void importSchedule(String ownerName){

    DatabaseReference events = FirebaseDatabase.getInstance().getReference("Events").child(pushedKey);
    Query allOwnersEvents = events.equalTo(ownerName);

    allOwnersEvents.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot post : dataSnapshot.getChildren()) {
        String allDay = post.child("yourFiedName").getValue(String.class);
        }
    }
    public void onCancelled(DatabaseError databaseError) {}
});

In which yourFiedName is the name of desired field. Hope it helps.


text:
Q: Removing Recently used items in 12.04
Possible Duplicate:
How do I delete the entire history (Recently Used Items) in the dash?

How do i remove items from my recently accessed file in ubuntu 12.04.

A: Go into System Settings. Pick the privacy app. Set the time range you want to delete for, and delete.
While you're in there you might want to change things to avoid certain items ending up there in the first place.

A: If you want to delete all the recently used items entries in a defined range (for instance: last hour, last day, etc), or just disable this feature you can use the Privacy application (installed by default on 12.04).
If you only want to delete specific entries i recommend you to use Activity Journal (available in Software Center). Just left click on the entry you want and choose "Delete".


text:
Q: LimitToLast() freezes unity I'm usig Unity 2018.3.0f2
Firebase 6.3
The problem is without using limitToLast() the code below works fine. I can get all data which Is thousands of data.
But I need to limit it and when I put 1 or 10 or any number with limittoLast or LimitToFirst (10) unity give no response and after waiting or stop to run the Unit play cpu starts to run faster, unity Freezes and I have to stop unity from Task manager and restart. Is that a bug or am I doing something wrong?
 FirebaseDatabase.DefaultInstance
          .GetReference("users").OrderByChild("score").LimitToLast(100)
          .GetValueAsync().ContinueWith(task =>{
    if (task.IsFaulted)
              {
                 Debug.LogError("failed");
              }
    else if (task.IsCompleted)
              { Debug("success")} );

A: You are calling GetValueAsync() which will override your LimitToLast() clause and grab all the data in the "users" reference.
This code should get you closer to what you want:
DatabaseReference usersReference = FirebaseDatabase.DefaultInstance.GetReference("users");
Query query = usersReference.OrderByChild("score").LimitToLast(100);
query.ValueChanged += (object sender, ValueChangedEventArgs args) =>
{
    // this lambda will get called up to 100 times
    if (args.DatabaseError != null)
    {
        Debug.LogError(args.DatabaseError.Message);
        return;
    }
    Debug.Log(args.Snapshot.GetRawJsonValue());
};