Cutting segments from convex objects

Question: Let $X$ be some convex object in the plane. For every pair of points $A,B$ that are not in $X$, and the distance between them is at most $1$, we remove from $X$ its intersection with the segment $AB$. For example, in the picture below, $X$ is the green circle, and if the distance between $A$ and $B$ is at most $1$, then the entire black segment is removed from $X$:

Note that we first find all A,B with distance at most $1$ and define the to-be-removed segments, and then remove them all at once.
Denote the new object (after the removals) by $Y$.
I am trying to understand how $Y$ looks like.
If $X$ is a disc (with diameter larger than $1$), then it is easy to see that $Y$ is a disc too: it has the same center as $X$ and a smaller radius.
MY QUESTION: if $X$ is an arbitrary convex object, is $Y$ convex too?
Comment: Assuming you don't cut away slice by slice (you would end up with the empty set) but first find all all such $A, B$ and define the to-be-removed segment, and then remove them all at once, the result would be convex.  It's basically an intersection of convex shapes (the cutting away of a segment is just the intersection with the corresponding half-plane).
Comment: Is this distinct from the following? "For a given convex object $C$, let $S$ denote the set of all chords of $C$ with length $1$. Find the envelope of all elements of $S$." I think this reformulation works, as long as $C$ is convex, and (for me at least) it's a bit easier to work with.
Comment: @fweth is right - intersecting convex regions means $D$ will be convex. Are you interested in the actual shape of $D$ too?
Comment: Note that it's not clear to me how you decide which side of the line you cut away, e.g. if the line cuts the shape in half.  But basically you can take any set of half-planes and intersect them, whatever the process of describing the set.
Comment: Good point - my reformulation falls apart when the shape is too small. But I suppose those shapes are entirely cut away?
Comment: @fweth: what I meant is to cut only the segment itself (not the entire half-plane on one side of it). When $C$ is a circle, and you cut such segments, you still end up cutting an entire "envelope" of $C$. But I don't know how to prove this for general convex sets.
Comment: Hmm, not sure if I understand.  After the cut, you want something like the gray shape here to remain?  https://i.imgur.com/1E1g69k.png
Comment: @fweth. After the cut of a single segment, the remainder is only $C$ minus that segment (the green region in my picture). Of course, if you cut many segments, you will end up with something like in your picture.
Comment: But the green region is the whole circle?  You only want to remove the line segment itself, so you end up with a disconnected subset of the disk?
Comment: @fweth the green region is the whole circle minus the black segment. Indeed, it is disconnected (but after removing many segments, it becomes connected again).
Comment: Ah, now I see what you mean.  Once you removed such a segment (and split the region in two), there will be one half of which you can remove any point using a segment parallel to your first one (and same length).  Hence you can describe the process of removing the segments equivalently as intersections with half-planes.  Should I write down the proof for this?
Comment: Ah sorry, there is some subtetly still going on with non-open sets.  I didn't realize that e.g. the open square with a single point added from its border is still convex.  Are you interested in open regions only or also ones neither open nor closed?
Comment: @fweth For my application, it is sufficient to handle only closed sets.
Comment: @ChrisLewis your alternative reformulation is interesting - I am looking for simpler ways to describe the process. Can you elaborate - what do you mean by the "envelope" of the chords?
Answer: I'll consider closed sets only, as you mentioned in your comment.  Please let us denote regions with $X,Y,Z,\dots$ and reserve $A,B,C,\dots$ for points, especially let $X$ be the total region.  If $[A,B]$ is a segment as described in your question, we can assume w.l.o.g. that removing it dissects $X$ into two parts $Y,Z$ (the other case is easy).  My claim is that after removing all segments of your kind, either $Y$ or $Z$ vanishes.  Assume not, then you have points $y\in Y,z\in Z$ which are not part of any such segment.  In particular you can choose segments $[C,D]\subseteq Y$ containing $y$ and $[E,F]\subseteq Z$ containing $z$, both of length $1$ and paralell to $[A,B]$.  Since $X$ is convex and $C,D,E,F\in X$, the segments $[C,E]$ and $[D,F]$ must be fully contained in $X$ as well.  But also at least one of those segments must intersect with the line through $A,B$ outside of $(A,B):=[A,B]\setminus\{A,B\}$, a contradiction, as no such point is contained in $X$.
Hence for each line segment $[A,B]$ you remove, there is a set of line segments whose removal includes all points to the left or all points to the right of $[A,B]$.  So removing all your line segments is equivalent to intersecting with a set of open half-planes, which yields a convex set.  It can also be checked that the set is closed.
Comment: I do not understand why "at least one of those segments must intersect with the line through $A,B$ outside of $(A,B)$". See this picture: https://i.stack.imgur.com/Rrlgk.png where both [C,E] and [D,F] intersect with $(A,B)$.
Comment: Maybe you meant: "you can choose segments [C,D]⊆Y containing y and [E,F]⊆Z containing z, both paralell to [A,B], **such that their length is larger than 1.**"?
Comment: Ah yes, will do an edit!
Comment: Length $1$ will do, I think.
Comment: Thanks! Based on your proof, is there a simpler way to describe the entire process of removal? I thought of "remove from $X$ the entire halfplane at one side of the line through $AB$", but it is not clear how to define that "one side".
Comment: I'd describe it this way.  For every angle $\alpha$, you can measure the diameter of $X$ along every line at angle $\alpha$.  This gives you a map $\mathbf{R}\to\mathbf{R}$ which is non-decreasing up to a point and then non-increasing.  If it gets above $1$, slice away the two open half-planes made up from lines at angle $\alpha$ along which the diameter is less than $1$.  Repeat for all angles $\alpha$.

Cutting segments from convex objects


expectation of $n$-sided die

Question: Assume a dice has n sides, what is the expected value of the dice?
My solution:
The PMF of the die would be 1/n, so you would multiply this by the summation of n.
Comment: The question has no unique answer for several $n\in\{3,5,7,9,\dots\}$.
Comment: What do you mean by *"summation of $n$"*? It seems you have almost the answer, but you have to clarify a bit. I assume that the dice is numbered from $1$ to $n$? Also, conceptually a dice with $n$ side is really like an urn with numbered balls: it's pretty hopeless to try to build a dice with $n$ sides and equiprobability for value of $n$ not in $\{4,6,8,12,20\}$.
Comment: The geometry of the problem is presumably being ignored @Jean-Claude.  We should assume that the die exists (*in whatever universe is necessary for it to*) and that the sides are in fact numbered $1,2,3,\dots,n$.  If you choose to reject either of those hypotheses then the question is unanswerable.  Worded another way, let $X_n$ be a random variable defined so that $Pr(X_n = k) = \begin{cases} \frac{1}{n}&\text{if} ~k\in\{1,2,\dots,n\}\\0&\text{otherwise}\end{cases}$ and we ask to find $E[X_n]$
Comment: Under that interpretation, the OP probably has the correct answer but phrased it very poorly, it being $\frac{1}{n}\cdot \left(\sum\limits_{i=1}^n i\right)$.  This can of course be simplified very easily as the summation is well known.  (*as a further aside, the word "dice" is plural.  You mean to use the singular word "die"*)
Comment: @JMoravitz We have the same conclusion. Regarding the singular/plural question, I referred to [this](https://en.wiktionary.org/wiki/dice). The Collins Cobuild dictionary seems to agree with the singular dice. I was surprised though.
Comment: What do you mean by  "expected value of die"?
Comment: @JMoravitz Yes sorry about the poor wording. what you posted:1n⋅(∑i=1ni)1n⋅(∑i=1ni) is what i meant
Answer: Following definition of expected value of a discrete random variable, we have:
$$E[X_n] = \sum\limits_{x\in \Omega}x\cdot Pr(X_n=x) = \sum\limits_{k=1}^n k\cdot \frac{1}{n} = \frac{1}{n}\cdot\left(\sum\limits_{k=1}^n k\right)$$
Recognizing the sum on the right as the triangle summation, one has then:
$$=\frac{1}{n}\cdot\left(\sum\limits_{k=1}^n k\right)=\frac{1}{n}\cdot \frac{n(n+1)}{2} = \frac{n+1}{2}$$

expectation of $n$-sided die


Change a letter after clicking on a button

Question: I want to change the first letter of my TextView after clicking on a button in Eclipse Android. I already can change the whole TextView, but I only want to change the first letter. How does it work?
XML:
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/BtnKlick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="209dp"
        android:text="Button" />

    <TextView
        android:id="@+id/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="Eclipse"
        android:textSize="70sp" />

</RelativeLayout>

JAVA:
package com.example.testapp;

import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

    public Button btn;
    public TextView tw;

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

        btn=(Button)findViewById(R.id.BtnKlick);
        tw=(TextView)findViewById(R.id.Text);

        btn.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        {}}}

Answer: Something like this may work.
@Override
public void onClick(View v) {
    // get the current string
    String toChange = tw.getText().toString();

    // get the part of the string you want to keep [everything after the first letter]
    String toKeep = toChange.subString(1, toChange.length);

    // put the letter you want before the part of the string you wanted to keep.
    toChange = "PUT_YOUR_NEW_LETTER_HERE".concat(toKeep);

    // finally set the new string in your TextView
    tw.setText(toChange);
}

If you explain more clearly what you want to achieve I could help you better.
As you've asked on how to replace a character amid a String I recommend you to have a look at @Rafik991 's answer. You simply can use something like the following:
@Override
public void onClick(View v) {
    int index = 0; // the index at which you want to replace a char.
    StringBuilder stringBuilder = new StringBuilder(tw.getText);
    stringBuilder.replace(index, index + 1, "YOUR_NEW_CHAR_AS_A_STRING");
    tw.setText(stringBuilder.toString());
}

To understand the methods of StringBuilder better have a look at the official documentation,
Comment: Just looked at the [StringBuilder documentation](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html). Wouldn't it be even better to use replace(0, 1, "NEW_CHAR") for your answer? :)
Comment: Yes ;) it is better but I was hurrying up with writing this post. I will change it. Thanks for suggestion!
Answer: Implementation of onChange method:
@Override
public void onClick(View v) {
        String cos = tw.getText();
        StringBuilder stringBuilder = new StringBuilder(cos);

        stringBuilder.replace(0, 1, 'c'); // c is your new character
   //or stringBuilder.deleteCharAt(0);
   //   stringBuilder.setCharAt(0,'c');

        tw.setText(stringBuilder.toString());

}

Comment: Didn't know about that solution. That's pretty nice actually.
Comment: I did not ask the question and thus can't accept your answer but I voted it up.
Answer: Try this in your onClick function:
String text = tw.getText().toString();
String newText = "C" + text.substring(1);
//                ^-- your new letter
tw.setText(newText)

UPDATE:
If you want to change another letter, its quite easy!
String text = tw.getText().toString();
int n = 3; // <-- nth letter
String newText = text.substring(0, n) + "C" + text.substring(n + 1);
//                                       ^-- your new letter
tw.setText(newText)

Comment: Thank you very much! Do you know how to colour the C?
Comment: @user3341325 Directly it is impossible, But you can get a workaround to achieve your purpose, In this workaround you should put 3 `TextView`s together in a line, then you can change the color on the middle one. However if you found my answer helpful please accept it by clicking on the tick icon
Answer: try this:
String text = tw.getText().toString();
String substring = text.substring(1, text.length());
tw.setText(substring);

Comment: This only deletes the first letter?!


How to get wifi working on Dell inspiron mini 1011 without wifi on Ubuntu 15.04?

Question: I recently installed Ubuntu 15.04 32-bit on my Dell inspiron mini 1011, and I can't use wired, nor does most other solutions people have said helped, so what do I do?
~Thanks in advanced,
Blade
Comment: buy a compatible Wi-Fi Dongle
Comment: Please [update](http://askubuntu.com/posts/675408/edit) your question with `lspci -nnk | grep Net -A2` output from a terminal (Ctrl + Alt + t)
Answer: Well lets go over the obvious first
The mini series should have an ethernet port so that would be your best bet.
It should also have bluetooth so there should be some options there:
From Android and From Ubuntu.
If you are still having issues try copying the files to a usb or use a generic usb wifi dongle since they do not usually require non standard drivers.
Would you be able to give a short list of the things you have already tried and the reasons why they have not worked?


Spark dataframe query for sum

Question: Suppose I am having the following spark dataframe:
COLA   COLB  COLC
2019   A     10
2019   A     20
2019   B     30
2019   B     40

any function to generate the following dataframe?
COLA   COLB       COLC
2019   A          10
2019   A          20
      SUB_TOTAL   30
2019   B          30
2019   B          40
      SUB_TOTAL   70

Answer: You haven't really specified how you'd like to group by your columns as the year is the same in all rows.
But you can use simple groupBy with union to achieve that:
# calculate sub totals grouping by COLB
sub_total_by_colb = df.groupBy(col("COLB")).agg(sum("COLC").alias("COLC")) \
            .select(lit(None), col("COLB"), col("COLC"))

# union original df with sub total df
df.union(sub_total_by_colb) \
    .sort(*[col("COLB").asc_nulls_last(), col("COLA").asc_nulls_last()])\
    .show()

Output:
+----+----+----+
|COLA|COLB|COLC|
+----+----+----+
|2019|   A|  10|
|2019|   A|  20|
|null|   A|30.0|
|2019|   B|  40|
|2019|   B|  30|
|null|   B|70.0|
+----+----+----+

This is said, I would, however, suggest you have a look at multi-dimensional aggregations, this is better when you want to calculate sub totals.
Example using rollup:
df.rollup(col("COLA"), col("COLB")) \
 .agg(sum("COLC").alias("COLC"), grouping_id().alias("gid")) \
 .sort(*[col("COLA").desc_nulls_last(), col("COLB").asc_nulls_last()]) \
 .filter(grouping_id() != 3) \
 .select(col("COLA"), col("COLB"), col("COLC"))\
 .show()

Answer: val tab = Seq((2019,"A",10),
(2019,"A",20),
(2019,"B",30),
(2019,"B",40)).toDF("COLA","COLB","COLC")
tab.show
val inter = tab.groupBy(col("COLA"),col("COLB")).agg((sum("COLC").alias("COLC")))
val final = tab.union(inter).orderBy(col("COLC"))
final.show

Spark dataframe query for sum


A group $(G,\circ)$ does not have any proper subgroups if and only if $\text{ord}(G)=p$,where $p$ is a prime number.

Question: A non-trivial group $(G,\circ)$ does not have any proper subgroups if and only if $\text{ord}(G)=p$,where $p$ is a prime number.
$\Longleftarrow$ If  $(G,\circ)$ is a group of prime order, then Lagrange's theorem implies that the order of the subgroups of $G$ divides $p$, which happens if the order is either $1$ or $p$, and hence the subgroups are improper subgroups of $(G,\circ)$, shows the only subgroups of $G$ are proper ones.
$\Longrightarrow$ Assume $(G,\circ)$ does not have any proper subgroups, if $G$ is not cyclic then it's generated by two distinct elements (generators) $a,b \in G$ (such elements exist since $G$ is non-trivial), Hence $\langle a\rangle$ and $\langle b\rangle$ are two distinct proper subgroups of $G$, a contradiction. (I think it's not true to say "two" distant proper subgroups, since it may happen that one of them is the identity element of $G$, but in either case at least one of them is a proper subgroup of $G$ ad this leads to the desired contradiction)
Now we should show that $G$ is a finite group (I guess we need to show that if $G$ is generated by an element $g \in G$, and does not exist a positive integer for which $g^n=1$ does hold, then this leads to a contradiction).
For the prime part, If $n$ is a composition number then we can find a prime number $m <n$,then $\langle g^m\rangle$ has order $\frac{n}{\gcd\left(m,n\right)}$,how to get the desired contradiction?
Comment: If $\langle g\rangle$ is infinite then $\langle g^2\rangle$ is a proper subset of $\langle g\rangle$
Answer: One direction is clear by Lagrange (since $p$ has no divisors).
For the converse, if $G$ is finite, we could use Cauchy's theorem to get an element of order $p$, where $p||G|$.  Then the cyclic group generated by that element has to be the whole group.
If $G$ is infinite, we can just take an element and consider the cyclic subgroup it generates.  It must be the whole thing.  So we have $\Bbb Z$.  But $\Bbb Z$ has nontrivial proper subgroups.  So $G$ can't be infinite.
Answer: No need for Cauchy's theorem. Pick an element $g$. It must generate the whole group, else as you mentioned there is another subgroup distinct from $\langle g \rangle$. Therefore $G$ is cyclic. If it is infinite then $\langle g^2 \rangle$ is a proper subgroup, so $G$ is finite. If it is of order $m$ and $d\neq 1$ divides $m$, then $\langle g^d \rangle$ is a proper subgroup. Therefore $m$ is prime.
Comment: If $\langle g \rangle$ is infinite it is isomorphic to $\mathbb{Z}$ under the map generated by $g \mapsto 1$ (this is straightforward to prove); the multiples of $2$ are a nontrivial subgroup of $\mathbb{Z}$, and their preimage under this map is $\langle g^2 \rangle$. Therefore if $\langle g \rangle$ is infinite it has a nontrivial subgroup, which is a contradiction to our assumption that $G$ has no nontrivial subgroups.


Moz appearance for radio button shows radio still

Question: I'm using -webkit-appearance and -moz-appearance so that I can style my radio buttons differently.  When I do this in Chrome I get what I want:

When I use -moz-appearance for Firefox browsers, it does change but not exactly...

The radio button is still there!  Is there a way to get rid of it completely and show my background images??
Answer: the -moz-appearance property is still a bit buggy it seems: https://bugzilla.mozilla.org/show_bug.cgi?id=649849
A workaround would be to hide the radio buttons themselves and use the :before pseudo element on something like a  to display different things depending on if the input is checked or not:
html:

    <input id="one" type="checkbox" name="stars" value="one"/>

    <input id="two" type="checkbox" name="stars" value="two"/>

    <input id="three" type="checkbox" name="stars" value="three"/>

    <input id="four" type="checkbox" name="stars" value="four"/>

    <input id="five" type="checkbox" name="stars" value="five"/>

css:
label {
    display: inline-block;
    cursor: pointer;
    position: relative;
    margin-right: 15px;
    font-size: 16px;
    color:#a8cdc3;
}
input[type=checkbox] {
    display: none;
}

label:before {
    display: inline-block;
    content:"\2606";
}
input[type=checkbox]:checked + label:before {
    content:"\2605";
}

for your application relating to a rating system, since you want the stars to indicate a rating you may want to consider switching the <input> type to a checkbox so that more than one input can be checked at one time. This way, all of the previous stars are starred when someone selects a rating (i.e., checking the third star also checks the first and second star). But that's just a suggestion.
jsfiddle of what I'm talking about:
http://jsfiddle.net/4Dm3g/1/
a lot of code credit goes to the following link:
http://www.hongkiat.com/blog/css3-checkbox-radio/
Comment: Please make your post self-standing and summarize the links within your answer. You can keep the links in your answer, but just in case the links become dead, it will prevent your answer from degrading into a useless answer.


Capitalizing letters

Question: I have got a small problem. I want to capitalize on doubled letters in a string. I managed to compile a program, but not successfully.
#include <iostream>
#include <cctype>
#include <string>

std::string::iterator function(
   std::string::const_iterator a,
   std::string::const_iterator b,
   std::string::const_iterator e)
{
   for (; a < b; a++)
   {
      if (*a == *(a + 1))
      {
         toupper(*a);
         toupper(*(a + 1));
      }
   }
}

int main()
{
   std::string in = "peppermint 1001 bubbles balloon gum", out(100, '*');
   auto e = function(in.cbegin(), in.cend(), out.begin());

   int n = e - out.begin();
   std::string s = out.substr(0, n);
   bool b = (s == "pePPermint 1001 buBBles baLLOOn gum");
   std::cout << std::boolalpha << b << std::endl;
}

What do I do wrong?
Answer: You have a couple of issues there.
Firstly, your function promised to return std::string::iterator
std::string::iterator function(....)
{
  //... return statement is missing here!
}

and you are not keeping the promise. This will leads to undefined behaviour.  For example, in your case, it just compiles and does not give the output.
In order to get a defined behaviour, you should return from the function
std::string::iterator function(...)
{
   // ... code
   return {}; // return appropriately iterator of std::string
}

Secondly, you want to modify the characters of the string, which requires a modifiable iterator rather than std::string::const_iterator.
Then in the loop, you need to alter the capitalized charector by reassigning to it. For example:
*a = toupper(*a);

Thirdly, you should be careful about doing this in the for-loop of your function
 for(; a here
     // ... code
 }

What would happen for the case when a== str.end()-1, you still would do the increment(i.e.  *(a + 1)), right?. Incrementing the end iterator again leads you Undefined behaviour.
In that case, you could use std::next from <iterator> header to safely check this.
Following is the demonstrative code which clears the issues mentioned above:
#include <iostream>
#include <string>
#include <iterator>  // std::next

std::string::iterator function(
   std::string::iterator a,
   std::string::iterator b,
   std::string::iterator e)
{
   auto beg = a;
   for (; a < b; a++)
   {
      if (std::next(a) != b && *a == *std::next(a)) {
         *a = toupper(*a);
         *std::next(a) = toupper(*std::next(a));
      }
   }
   std::cout << std::string{ beg, b };
   return {}; // return appropriately iterator of std::string
}

prints for now: https://godbolt.org/z/ZsLHxw
pePPermint 1001 buBBles baLLOOn gum

I assume that you want somehow to get the output to the third function parameter std::string::iterator e. I will let that part for you to figure it out. Meanwhile, have a look at the standard algorithm function std::transform, which might be handy to do such kind of transformation.
Answer: Answers are already given. I want additionally to show an answer based on existing C++ functionality. For your given task there is a function existing in the C++ standard algorithm library. It is called std::adjacent_find. Please see here.
With that you could rewrite your code simply to:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
    std::string test{ "peppermint 1001 bubbles balloon gum" };

    // Find all duplicates
    for (auto il = std::adjacent_find(test.begin(), test.end()); il != test.end(); il = std::adjacent_find(il+1, test.end())) {

        // If duplicate found, then convert both to uppercase
        *il = std::toupper(*il);
        *(il + 1) = std::toupper(*(il+1));
    }
    std::cout << test << '\n';
    return 0;
}

We call this function in a simple for loop, until no more duplicates could be found.
Maybe it can give you an idea for a more simple implementation.
Answer: Your function exhibits undefined behavior because it never returns a value.  Please compile with -Wall -Wextra to enable all compiler warnings to avoid such unnecessary bugs.

Capitalizing letters


How can I rotate text in Shutter?

Question: Is there any way to rotate text in Shutter Screenshot Tool?
Example of the interface:
Answer: It seems there is no way to rotate texts in Shutter. There was a bug report requesting this feature on launchpad. See here. You can visit the bug report and click on This bug affects me link (I too clicked on that link btw).
However, You can easily create a vertical text line using GIMP. To do so, after completing your edits with shutter. Use Menu -> Screenshot -> Open with to directly open the file in Gimp.
From GIMP's toolbox, add text (don't forget to set matching color with arrow if you like) and then using Menu -> Layer -> Transform rotate it. Then move the text object at your desired location on the picture.
Use Menu -> File -> Overwrite to save it. You'll have the edited screenshot with rotated text in shutter.
Comment: What a pity. Shutter is an excellent piece of software. If you have any ideas how to revive the project, then please do let me know.
Comment: Thank you for the reference to the bug report! Do you happen to know if Shutter is still being developed?
Comment: It seems shutter development is currently not very active. The last version released was around 2014. So...

How can I rotate text in Shutter?


Having trouble with binding an entity in Blazor

Question: I am trying to build an ASP.NET Core hosted Blazor web app. I have two entities with a one-to-many relationship.
There is one portfolio that has many securities.
Portfolio entity
public class Portfolio
{
    [Key]
    public int PortfolioId { get; set; }
    [Required]
    public string NameOfPortfolio { get; set; }
    public string Description { get; set; } = string.Empty;
    public DateTime DateTimeCreated { get; set; } = DateTime.UtcNow;

    public virtual ICollection<Security>? Securities { get; set; }
}

Security entity
public class Security
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string SecurityName { get; set; } = string.Empty;
    [Required]
    public float Price { get; set; }
    [Required]
    public int StockesOwned { get; set; } = 0;
    [Required]
    public float StocksValue { get; set; }
    public DateTime DateTimeObtained { get; set; } = DateTime.UtcNow;
    public string? Description { get; set; } = string.Empty;

    public Portfolio Portfolio { get; set; }
}

The Security must have a Portfolio, but a portfolio may not have a security.
I am trying whenever I want to add a security I must specify the portfolio that contains that security. I am trying to bind the security.Portfolio to a Portfolio and I can not implement it correctly.
Whenever I try to bind it that way

        Portfolio

        <select class="form-control" >
            <option value="" email@example.com>Select Portfolio</option>
            @foreach (var portfolio in Portfolios)
            {
                <option value="@portfolio.PortfolioId">@portfolio.NameOfPortfolio</option>
            }
        </select>

It returns an error 400 and it mentions that the portfolio is required
Also here is the service in the client
public async Task CreateSecurity(Security security)
{
    var response = await _http.PostAsJsonAsync("api/security", security);

    if (response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadFromJsonAsync<ServiceResponse<int>>();

        if (!(result?.Success ?? false))
        {
        }
    }
}

The controller
[HttpPost]
public async Task<ActionResult<ServiceResponse<int>>> CreateSecurity(Security security)
{
    var result = await _securityService.CreateSecurityAsync(security);
    return Ok(result);
}

The service in the server
public async Task<ServiceResponse<int>> CreateSecurityAsync(Security security)
{
    _context.Securities.Add(security);
    int result = await _context.SaveChangesAsync();

    return new ServiceResponse<int>
        {
            Data = result,
            Success = result > 0,
            Message = "The" + security.SecurityName + "has been saved!"
        };
}

Sorry if I misspelled something or did something wrong. I am new to this. Thanks in advance.
Answer: Your issue is that you are trying to bind on a normal HTML element, and on top of that, you are binding to the option element:
...
        <select class="form-control">
            <option value="" email@example.com>Select Portfolio</option>
            @foreach (var portfolio in Portfolios)
            {
                <option value="@portfolio.PortfolioId">@portfolio.NameOfPortfolio</option>
            }

Solution 1
Your Security class requires a foreign key to bind against. So add this property to your Security class:
[ForeignKey(nameof(Portfolio))] //Add the Portfolio namespace like nameof(MyNameSpace.Portfolio)
public int PortfolioId { get; set; } //Make sure this property name matches the column name in the Security table in the database.

You need to set the value on the change event of the select element:
Implement the following:
<select class="form-control" @onchange="@OnPortfolioChange">
    <option value="">Select Portfolio</option>
    @foreach (var portfolio in Portfolios)
    {
        <option value="@portfolio.PortfolioId" selected="@portfolio.Id == Security.PortfolioId">@portfolio.NameOfPortfolio</option>
    }
</select>

@code {
    void OnPortfolioChange(ChangeEventArgs args)
    {
        if (int.TryParse(args.Value?.ToString(), out int portfolioId))
            Security.PortfolioId = portfolioId;
        else
            Security.PortfolioId = null;
    }
}

Solution 2
Like the first solution, but you don't add the extra property to the Security class. Instead you need to make your OnPortfolioChange this:
void OnPortfolioChange(ChangeEventArgs args)
{
    if (int.TryParse(args.Value?.ToString(), out int portfolioId))
        Security.Portfolio = Portfolios.First(p => p.PortfolioId == portfolioId);
    else
        Security.Portfolio = null;
}

With that your option element's selected attribute will look like this:
selected="@portfolio.Id == Security.Portfolio?.Id"

Recommendation
Since you are using the normal HTML elements, I suggest creating a generic component that does your casting in a standard manner that can be reused when required.
Comment: I tried to do the second solution but it gave me the same error, when trying to add the Portfolio to the Security in the client.
Comment: Debug and check your object before the `PostAsJsonAsync` method invocation. Does it contain a populated `Portfolio` object?
Answer: The firstname.lastname@example.com is likely supposed to be on the  tag instead.
Also, I'm not sure if you can bind the whole Portfolio object to the option value.
When you are submitting the model, I would suggest you get the Portfolio by the selected id and putting it on the Security model manually before committing it through the api.


Math writing from code- how to write equations?

Question: I have written code (in R) for my research project and am trying to publish a paper. Is there a good guide on how to take the concepts in my code and write them in a paper mathematically?
Specifically, I have two questions:

How do I write that a number has to be a divisor? Is it: If a|b, then... where a is one of the divisors of b?
If I have an array of indices v, how do I define the values of another array, G, at the index values $\bar{v}$? Is it: $G_{v}= \ $ or maybe $G_{\bar{v}}= \ $?

For example, in my project, objects exist along an axis Z. They occur only when a value is a divisor of the maximum value of an object along Z. Therefore, if $v_{max}$ occurs on Z, then vector $\bar{v}$ is all divisors of $v_{max}$. Also $\bar{v}$ represents the occurrences of all objects along the Z axis. The G values depend on the location of the occurrences, $\bar{v}$. G in the code is defined at these locations. In R, v is a vector and G is a vector. Defining G in R would read as:
<code>G[seq(1,length(v)] = function(v)
</code>
G is therefore a function of v, but how would I reference G at a particular v?
Comment: Take the concepts in my code and write them in a paper mathematically
Comment: a paper isn't a program. If you can convey an important idea clearly with plain text, you should probably just write plain text. Also, very few people like to read (pseudo) code longer than a page...
Comment: You should write instead (in 5 lines) a paragraph you care about, and we will rewrite it with the preferred notation.
Comment: Are you asking how to make your _code_ more readable to mathematician, or take the concepts in your code, and write them in a paper mathematically?
Comment: Also, what language are you writing in? What does your supervisor recommend? You may want to add the relevant tags, or maybe even ask the question on LanguageUsed.SE (which exists for Sage/Mathematica and should do for quite a few other mathematical programming languages)
Comment: what thoughts have you had so far about this problem? Personally, i would look at how various algorithms have been presented in arXiv, find a paper which develops some sort of algorithmic solution and see how it is presented there (or a different sort, depending on what you have found)
Answer: In response to your very specific questions

1)

One would indeed write $a \mid b$ for $a$ divides $b$. However as a general rule, you can find common notation just by searching the English aspect in a search engine.
For instance, searching "Divisor mathematics" gets you to the wiki, which 4 lines down in the definition part says $a \mid b$. After that, deciphering the correct $\LaTeX$ code can be done by Detexify.

2)

Ultimately you can choose the notation you like. Personally, it would depend on the number of times and density I use the character. If it is dense at a particular page or few then maybe the latter $G_{ \bar v}$. However, if I have to use the symbol often, then I would prefer $G_v$ purely because it looks less squashed. If I refer to $\bar v$ a lot and then have to refer to $G_v$, I might the first time use $G_{ \bar v}$ and explain that I'll also use $G_v$.
It would appear, from the above paragraph at least, that you have some rigorous construction for this $G_v$. So, you might want to start off with an introduction as to why your paper is worth my half-day of reading and digesting the material. This could include a problem that is initially unsolved that the new $G_v$ solves. Then you might want to define standard terms and then construct the $G_v$ giving lemmas of various properties that $G_v$ might hold. You don't need to give every step, but at various points just reference an algorithm you use and say "Using the Gram-Schmidt algorithm, we can find a vector $w$ which has a bunch of cool properties" (or something along those lines). Other examples would be "From methods discussed in [CoolGuy15], we can find $H_v$ which acts as an intermediate step for finding $G_v$."
One author that comes to mind is Dan Yasaki, with these particular papers Perfect Forms and Bianchi Forms. Particularly in the second paper, there is a problem discussed and solved by work done in chapter 2 and 3, relying on algorithmic work done in Gunnels' papers.
Comment: Perfect, thank you for the help. Definitely my end goal is to get the point across to the reader, so I reference particular G values. My writing is very similar to the examples, so I'm glad the notations made some sense at least without the rest of the context


Is there a series that is asymptotic to $\log(\log(\log x))$

Question: We know: $\sum\limits_{n=1}^x\dfrac{1}{n}\sim\log(x)$, $\sum\limits_{n=1}^x\dfrac{1}{\text{prime}(n)}\sim\log(\log(x))$.
I wonder if there is another interesting series that diverges even slower than reciprocals of primes, at a rate of $\log(\log(\log x))$. Or perhaps if there is a family of series that diverge ever more slowly, that are asymptotic to $\log(x)$ nested once, twice, thrice, etc.
Answer: By the prime number theorem, $\text{prime(n)}\sim n\log(n)$. Therefore
$$\sum^x_{n=1}\frac{1}{\text{prime}(n)\log\Big(\frac{\text{prime}(n)}{n}\Big)}\sim \int_3^x \frac{1}{n\log(n)\log(\log(n))}\,dn\sim\log(\log(\log(x)))$$
In a similar way, you can obtain  more examples (though not so "interesting" I guess...).
Comment: Maybe something involving the twin primes: https://en.wikipedia.org/wiki/Twin_prime#Brun's_theorem
Comment: I was imagining something along the lines of "subset of reciprocals of primes" gives triple nested logx, just as "subset of reciprocals of integers" gives double nested logx.
Comment: @GappyHilmore - since the triple $\log(x)$ goes to infinity when $x$ does, the according series must diverge. I think, I have seen a statement like that using the twinprimes the series becomes convergent instead.


Display list of artifacts inside confluence page

Question: I have a list of artifact which I can see as JSON list:
http://artifactory.server/artifactory/api/storage/my-folder
and I want to display them in a Confluence page.
Is there a Macro? Maybe JS option?
thanks.
Answer: In your user case the best way to add/update content in Confluence is using Confluence Server/Cloud REST API.
You can send your list to a Confluence page or create a new page, for example, in every release version from your CI(Jenkins, Bamboo...).
Comment: thanks for the answer, it's a good idea but my privilege are not allow me to do so. I can only read from artifactory and update pages in confluence inside the system. I am not an admin
Comment: @aviram83 as a normal user is more complicated but you can do a Selenium script, for example.


Are carpet and pad salvageable with partial flooding?

Question: We had a storm that caused a flood in one part of the basement where the water level actually went above a window and started coming in through it. I immediately shopvacd it and pulled up the carpet and pad to dehumidify and run a blower over, but as you can see from the pics they're pretty wet and I'll have to clean up the dirt the water brought in as well. Is this carpet even worth salvaging or is it better just to recarpet this room?
Comment: Depends on the cost of the carpet.  The padding is cheap and might just get new padding.  Cost of cleaning/drying the carpet to cost of new is different.
Comment: Personally, I'd just recarpet, unless you can be confident that you dried it out *tout de suite.*
Answer: If both the carpet and pad can be thoroughly dried prior to mildew growth, it should be fine to reuse. I had the same thing happen and laid out the carpet and pad flat, vacuumed it dry, elevated it outdoors on sawhorses to dry. I then re-laid the pad and stretched the carpet back in place.


How do I play splitscreen multiplayer in Titanfall 2?

Question: I bought Titanfall 2 last year (2018) for the Xbox. I have heard and seen on Google that the developers have updated the game to support a four player mode, as well a two player co-op mode. But I don't know how to make my team do this.
I think it supposed to update on its own but if it is it isn't working right. Please let me know how to play splitscreen?
Comment: The 4 player mode you were referring to sounds like Frontier Defense but I've looked everywhere and found nothing referring to a 2 player co-op mode. Where did you hear about it?
Comment: I read it on google, I'm going to get you a link to the site. So how do I get frontier defense? I don't see it on my games menu
Comment: I may have been mistaken about the 2 player co-op
Comment: On the front menu under multiplayer you should be able to choose to launch multiplayer or frontier defense. It's also the very right gamemode when you go onto the menu deciding what gamemode you want to play. But as I said in my answer this does not have split screen.
Answer: There is no split screen in Titanfall 2. You can however play with your friends in multiplayer if they all have their own consoles.


How can I debug an embedded process?

Question: I have a problem with debugging a process on arm + Linux platform:
This is a daemon process working with CAPWAP protocol, so it continuously communicates with another remote process. When it crashes with a segmentation fault, my usual means of debugging is to add some log output via printf, to find where the process has crashed, but it's not very efficient.
Is there any other way to debug this problem?
Answer: You could also enable core(5) dump, then use gdb post-mortem on that core with
  gdb yourprogram core

To enable core dump, you need to call the setrlimit(2) syscall with RLIMIT_CORE, usually in some parent process (e.g. the shell with ulimit)
BTW, you could also start your program thru gdb using
  gdb --args yourprogram argtoyourprogram

Don't forget to compile your program with gcc -Wall -g. The -Wall options give almost all warnings (very useful), and the -g produces debugging information.
Answer: There are two options for debugging in this case.

Debug your program using GDB debugger. You can set breakpoints in your program using GDB.
Use Android-ndk for debugging your segmentation fault. This kind of debug can provide the exact location of the error.
Comment: The oriinal poster might have an embedded Linux running on ARM which is not an Android...

How can I debug an embedded process?


Treehouse ladder - 12ft and corrosion resistant from pressure treated wood?

Question: I'm designing an elevated deck/swingset combo and am trying to figure out how I'm going to build the ladder.
But I've got a couple of challenges. One is that the main posts will be ground-contact rated pressure-treated wood, which from what I read corrodes basically all metal except stainless steel.
Another is that most ladder rungs I've found you need to weld in place, and I don't have welding equipment or training.
This is my first shot at a ladder design (safety cage is planned but not pictured):

Deck height is 12ft.
I've been looking up hardware to build this but having a bit of trouble. A stainless steel ladder rung mount would be nice but I can't find it. Basically I just need a ladder I can attach to this pressure treated frame.
Anyone have any ideas?
Comment: Any ideas questions don't do well in our Q&A format. What's the question, exactly? Why aren't you building the ladder from the same material as the rest of the structure?
Comment: @blacksmith37 https://fastenerengineering.com/what-fasteners-should-be-used-with-pressure-treated-wood/
Comment: Dead vertical is highly dubious, ladder design-wise.
Comment: Thanks. Going to update the design with a 4:1 slope instead.
Comment: my fort had a rope ladder. took some extra dexterity to use, but you could pull it up to keep dad out...
Comment: Is this already built or is it still in the design stage? Because did anyone happen to tell you that you should not use pressure treated wood for things like play structures where the kids will come in direct contact with it? The pressure "treatment" is a toxic chemical cocktail that, if it gets into their bloodstream via a splinter or absorbed through their skin, can cause serious issues. It's fine for the sub-structure and ground contact, but not for things like hand rails and ladders. Change the ladder to something like cedar, then drill to put pipes through it with caps on either side.
Comment: Still in design stage. The danger of pressure treated wood is generally from workers in plants that pressure-treat the wood and the effects of simply touching pressure treated wood is not serious. Anyway, I was planning on adding something easier to grip for the handrails, so they wouldn't be touching it anyway.
Comment: As for "what's the question", you could phrase it as "how do you build a ladder to attach to a pressure treated frame?" The answers I have gotten have been quite helpful, for the most part.
Answer: This is what I ended up building:

The main deck frame is resting on top of ground-contact pressure treated posts, with a notch sticking up on the inside to keep it from sliding off. So it is not relying on any fasteners to stay up. The post holes are filled with concrete to also minimize rotting effects.
The ladder is secured to the railing posts and does not touch the main support posts. I changed it to have a slope as suggested and also added a few more safety features. It turns out having the handholds at the top is important to help people get confidently started on the way down.
The ladder itself is made entirely from 2x6s, stained Western Red Cedar. Each rung and spacer is screwed in from the outside
Answer: For ground contact, besides the corrosion problem, there are general strength and stability issues potentially lurking.
Solutions include creating a concrete base, such as (from here):

Or pouring your own concrete base and incorporating post standoffs such as (from here)

Another issue is for whom is the ladder intended?  If it is teenagers, then your layout is probably adequate for all but the least athletic.  Otherwise, the ladder should extend above the deck for hand holds.
Comment: Having the hand rails go above the deck is a good plan. Also it hadn't occurred to me that I could downgrade the pressure treatment rating by using a concrete base. I was already planning on doing the concrete. I'll have to see if my Home Depot carries that in the length I need.
Comment: This answer doesn't go very far at all toward answering the (rather vague, I admit) question about ladder construction.
Comment: @isherwood:  It wasn't meant to answer all aspects.  Just some of the details I didn't see anyone else addressing.
Answer: Drill holes, use stainless steel pipe.
Buy a stainless steel ladder, such as from a swimming pool supplier.
Change materials where you come out of the ground and no longer need ground contact, or apply the ladder supports (of non-ground contact treated material) to the face of the ground-contact posts. I've seen laminated posts with a ground contact bottom and a transition to non-ground contact top, for one thing.
All the ones I grew up with were wooden rungs/steps, but your insurance company may disapprove these days.
Comment: The classic site-built construction ladder has rungs nailed to posts with supporting uprights also nailed to the posts. Google 'job built ladder'. You'll also see in the pictures that they are typically angled and the posts extend past the deck by about 3'.
Comment: The "job built ladder" looks encouraging. Angling it out would also make the whole structure more stable. Though it will be more complicated to construct the "safety cage" like this.

I am not sure how I'd fit the stainless steel pipe into the drilled holes. Lining up all of the rungs at once and placing the whole 4x6 seems like it would be tricky.

Also the whole structure needs to be pressure-treated to some degree since it will be exposed to the elements. Though I suppose I could try and find western red cedar to attach and provide a buffer to attach rungs to.


How to give Schema Level permission in Azure Data Warehouse (Synapse)?

Question: In our Azure SQL Data Warehouse (Synapse), we have two schemas dbo and staging.
I want to give schema level permission to my Azure Active Directory Group users only to 'dbo' schema. The expected behaviour I'm looking for is that after giving this permission, the Azure Active Directory Group users shouldn't see staging schema when opening the database in ssms. I tried the following to create the user and give permissions but still, users see staging schema in their ssms.

I created the user and added db_datareader role using the following:

CREATE USER [Azure Active Directory Group] FROM EXTERNAL PROVIDER WITH DEFAULT_SCHEMA = dbo;
EXEC sp_addrolemember 'db_datareader', 'Azure Active Directory Group'

And then grant schema level permission using:

GRANT SELECT ON SCHEMA::dbo TO [Azure Active Directory Group]

The following query returns:

select pr.name,
       pr.type_desc,
       pe.permission_name,
       pe.state_desc,
       pe.class_desc,
       object_name(pe.major_id)

FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
    ON pe.grantee_principal_id = pr.principal_id where name='Azure Active Directory Group Users';

Does anybody know how I can give schema level permission? I'm stuck!
Answer: db_datareader: Members of the db_datareader fixed database role can read all data from all user tables. It means the db_datareader role can view all the schemas. So we need to revoke this permission.
There are two ways to reslove the problem:

Revoke the db_datareader permission and grant the permission to the user.

EXEC sp_droprolemember 'db_datareader', 'Azure Active Directory Group'

GRANT SELECT ON SCHEMA::dbo TO [Azure Active Directory Group]

We also can add a custom role and grant the permission to the role.

CREATE ROLE <Role_Name>;

GRANT SELECT ON schema::dbo TO <Role_Name>;

EXEC sp_addrolemember '<Role_Name>', 'Azure Active Directory Group'

Comment: thanks, @Joseog Xu, why can't I directly use `GRANT SELECT ON SCHEMA::dbo TO [Azure Active Directory Group]` after revoking `db_datareader`? why do I need to create `external_users` role?
Comment: You also can directly use `GRANT SELECT ON SCHEMA::dbo TO [Azure Active Directory Group]`.  `external_users` is the name of the custom role I created, you don't need to create a role. The custom role is created so that this permission can be reused.


Group by multiple variables and summarise dplyr

Question: I'm trying to average CO2 concentration data every 30 seconds, for each of my sensors:
    head(df)
# A tibble: 6 x 7
# Groups: BinnedTime [1]

  Sensor Date       Time   calCO2 DeviceTime          cuts   BinnedTime
  <fctr> <date>     <time>  <dbl> <dttm>              <fctr> <chr>
1 N1     2019-02-12 13:24     400 2019-02-12 13:24:02 (0,10] 2019-02-12 13:24:02
2 N1     2019-02-12 13:24     400 2019-02-12 13:24:02 (0,10] 2019-02-12 13:24:02
3 N1     2019-02-12 13:24     400 2019-02-12 13:24:03 (0,10] 2019-02-12 13:24:03
4 N2     2019-02-12 13:24     400 2019-02-12 13:24:03 (0,10] 2019-02-12 13:24:02
5 N3     2019-02-12 13:24     400 2019-02-12 13:24:03 (0,10] 2019-02-12 13:24:02
6 N3     2019-02-12 13:24     400 2019-02-12 13:24:05 (0,10] 2019-02-12 13:24:04

I use:
df %>%
  group_by(Sensor)%>%
  group_by(BinnedTime = cut(DeviceTime, breaks="30 sec")) %>%
  summarize(Concentration = mean(calCO2))

But it doesn't group by Sensor first, it ignores them and calculates the average over the BinnedTime instead. Any thoughts would be welcomed.
I've read about .dots=c("Sensor","BinnedTime") but this doesn't work.
Note, I haven't created dummy data so you can see exactly what mine looks like, as there seem to be some subtleties with time and date that I can't quite get my head around.
Comment: You need to set `add = TRUE` in the second `group_by`, otherwise the grouping by BinnedTime overwrites the grouping by Sensor. Alternatively you could also do: `df %>% group_by(Sensor,BinnedTime = cut(DeviceTime, breaks="30 sec")) %>%  summarize(Concentration = mean(calCO2))`
Comment: Use `mutate` instead of `summarize`, but this will duplicate the value of Concentration for each Sensor and BinnedTime
Comment: Works perfectly, thank you! Small add add-on but related question- How do I get dplyr to just add Concentration as an additional column of df instead of dropping all the ones I haven't used in the above function?
Answer: So to summarize the comments by @kath with some improvements to address your follow-on question:
df %>%
    group_by(Sensor, BinnedTime = cut(DeviceTime, breaks="30 sec")) %>%
        mutate(Concentration = mean(calCO2)) %>%
    ungroup()

The above will maintain all columns, but duplicate the Concentration calculation for each row of the df.  An alternative that would allow you to both roll up and retain more columns of interest is to simply add them to the summarize operation, as illustrated below.
    df %>%
    group_by(Sensor, BinnedTime = cut(DeviceTime, breaks="30 sec")) %>%
        summarize(Concentration = mean(calCO2),
                   Date = min(Date),
                   Time = min(Time),
                   StartDeviceTime = min(DeviceTime),
                   EndDeviceTime = max(DeviceTime))


Online Tool for creating a sequence diagram in Mac

Question: Sorry this is not a programming question. I want to develop a sequence diagram for my iOS application.
I googled a lot but couldn't find any helpful tool
Can anyone please help me with any online tool or any other tool for creating a sequence diagram in Mac.
Comment: https://www.genmymodel.com is now supporting sequence diagrams and works under any operating systems including MacOS.
Answer: I found a useful tool.  Please navigate to here
<code>  [1]: https://cacoo.com/r/KmWnV
</code>


QTabWidget - how to "include" a pointer to every tab?

Question: I'm trying to make a simple communicator, with UI based on tabs (QTabWidget). I want tabs to be closeable and movable. Still, for every tab I would like to remember a pointer to my class (where I keep socket etc.), so I could manage closing tabs and disconnecting sockets.
One way is to keep them(pointers) in array / any container, analyze any move that was done by a user, and change indexes or swap pointers dependently on index of tabs, that were moved, but this involves a lot of work, and even more bugs. Is there any other and simpler way I could get it?
Answer: Use myTabWidget->widget(index).
There is one for each tab.
Doc
You can set the widget as the parent of your class if your class inherits from QObject, or connect its signals (like destroyed()) with that of your class.
Or you can even do
QVariant prop = QVariant::fromValue<intptr_t>((intptr_t)workerObject);
myTabWidget->widget(index)->setProperty("workerObject", prop);

to really store the pointer, and
QVariant prop =  myTabWidget->widget(index)->getProperty("workerObject");
WorkerClass *ptr = (WorkerClass*) prop.value<intptr_t>();

to get it back.


Split work between writing output from .exe and reading the output

Question: I have a simple .exe downloaded from the apple app store. It gives real-time updates on crypto prices and their percentage change. I am extracting percentage changes of bitcoin.
I am using a subprocess to extract the output. I am storing the output into four separate text files, then I'm reading the text from the files, extracting the data I need and saving it into a pandas dataframe.
Additionally, I have a 60 second timeout for each .exe run, and I read the file after 70 seconds. I truncate the file by removing its content, and by the time the next file has output in it, I'll read that file also, then truncate and repeat.
I want to know how to split the work between saving the output into a textfile and reading the content then truncate it. For example, I am running a simple thread that should run the .exe and extract the output with write_truncate_output. However, I only have append_output_executable running.
Here's my script:
from subprocess import STDOUT, check_call as x
import os
from multiprocessing import Pool
import time
import re
from collections import defaultdict
import pandas as pd
from multiprocessing import Process

cmd = [r'/Applications/CryptoManiac.app/Contents/MacOS/CryptoManiac']
text_file = ['bitcoin1.txt','bitcoin2.txt','bitcoin3.txt','bitcoin4.txt']

def append_output_executable(cmd):
    while True:
        i = '1234'
        for num in i:
            try: #append the .exe output to multiple files
                with open(os.devnull, 'rb') as DEVNULL, open('bitcoin{}.txt'.format(num), 'ab') as f:
                    x(cmd,  stdout=f, stderr=STDOUT, timeout=60)

            except:
                pass

def write_truncate_output(text):
    while True:
        time.sleep(70)
        with open(text, 'r+') as f:
            data = f.read()
            f.truncate(0)
            #read and truncate after reading the data

            #filter and format
        percentage=re.findall(r'\bpercent_change_24h:\s.*', data)
        value= [x.split(':')[1] for x in percentage]
        key = [x.split(':')[0] for x in percentage]

        #store in dictionary
        percent_dict = defaultdict(list)

        for ke, val in zip(key, value):
            percent_dict[ke].append(val)
            percent_dict['file'].append(text)

        percent_frame = pd.DataFrame(percent_dict)

        print(percent_frame)

if __name__ == '__main__':
    for text in text_file:
        execute_process = Process(target = append_output_executable, args=(cmd,))
        output_process = Process(target = write_truncate_output, args=(text,))
        execute_process.start()
        execute_process.join()
        output_process.start()
        output_process.join()

this stil just runs the first function.
Comment: frankly, I don't undestand why to run it in seprated threads/processes. It can make only problems to synhronize data. System decides when processes are exactly executed and they can run in different moments when you expect. I would do all at once after getting from external program. Besides it can work little faster if you don't use files but keep all in memory.
Comment: you use threads in wrong way - `target` needs  function's name without `()` and arguments - and later it will use `()` to start it - `Thread(target=append_output_executable, args=(cmd,))`. Current code runs `append_output_executable(cmd)` at once - and when you exit this program then it tried to create `Thread()`
Comment: in example with process you have another problem - you assing process to `p2` inside loop but you starts `p2.start()` after loop. But `p2` can keep only one value - so it keep only last process, and finally you runs only last `p2`. You should run `p2.start()` inside loop or you should keep processes on list and later run `for`-loop to run `.start()` on every element on this list.
Comment: as for me it could be faster to execute `check_call` once and laster write the same output to 4 files.
Comment: @furas I am running these separately because when I have them all in one function, I cannot get past the executable running. So I still cannot get it to read the output. I have updated my script with `args` also, but the same issue occurs. Perhaps it's because I am running  ```append_output_executable``` within a `while` loop, but I want it to run 24/7, and when I set a `timeout` it would close it. So the `while` loop continues it after closing.
Comment: did you remove `()` from `target=`?  Did you use `start()` inside `for`-loop? Maybe first use `print()` to see which part of code is executed and what you have in variables.
Comment: frankly, as for me you should do all calculations directly in this `while`-loop
Comment: BTW: your code in `write_truncate_output` would also needs some loop - at this moment it runs it only once so you may not see differences.
Comment: BTW: thread can't send result to main process so using `return percent_frame` is useless. But threads share memory so it would need to use `global` to send data to main process. And you could also use `global` to send data from one thread to anothers without using files.
Comment: @furas I have updated it as you mentioned; it's just as you mentioned `write_truncate_output` would only do it once. I have tried wrapping it all under a `while True` however, it does not seem to work. I'll look into how to wrap alternative loops for it - additionally, I'll look into `global` also
Comment: you have to run `while`-loop inside function `write_truncate_output` - similar to `while`-loop inside `append_output_executable`. But I would use global variable `running = True` and `while running:` - this way you can later set `running = False` to stop loops in functions.
Comment: @furas I do not think the issue is with the `while` loop. I have updated the post, but I think the issue lies in `execute_process` and `output_process`. I put everything in a loop, and it would just run `output_process` once. Then keep running `execute_process`, the same happens if I put `execute_process` outside the `for` loop. However, when that happens `output_process` runs first and then `execute_process`.
Comment: @furas the `append_output_executable ` has stronger precedence over `write_truncate_output`. Not sure why this happens, but it seems that `write_truncate_output` gets put on hold after it runs once.
Comment: you run it in wrong way - you run `append_output_executable` inside `for`-loop so it runs 4 times the same functiona - and all 4 functions do the same. You should run it before `for`-loop. And don't use `join()` inside loop becaues `join()` waits for end of function - and this blocks other code,. You should first `start()` all processes and later `join()`
Comment: another mistake - don't use `return` inside `while`-loop. This way you run it only once.
Comment: problem is that you have few different mistakes - when you repair one mistake then it still doesn't work because you have other mistakes.
Comment: @furas LIFESAVER! fixed the issues. Also, back to your first comment. What is your suggestion with loading it into memory? I could not find a way to accomplish this. The difficulty I had was storing the output from `check_call` into an empty list.
Answer: I don't know if this answer resolve all your problems because you have few mistakes in program - when you repair one mistake then it still doesn't work because there are other mistakes.

First:
target in Thread and Process needs function's name without () and arguments - (this is called callback) - and later (when you use .start() ) it will use () to run this function inside new Thread or Process
Thread(target=append_output_executable, args=(cmd,))

Process(target=append_output_executable, args=(cmd,))

Second:
Thread and Process runs this function only once so it needs while-loop to run all time. And it can't use return because it ends function.

Third:
.join() block code because it waits for end of Thread or Process and it should be used after starting all threads/processes - usually it is used at the end of program when you want to stop all threads/processes

And small suggestion(s):
You could use global running = True and inside function while running - and later you can set running = False to stop loops in function (and finish functions)

Code could look like this
# ... other imports ...
from threading import Thread

def append_output_executable(cmd):
    while running:
        # ... code ... (without `return`)

def write_truncate_output(text):
    while running:
        # ... code ... (without `return`)

# --- main ---

# global variables

running = True

if __name__ == '__main__':

    # --- create and start ---

    t0 = Thread(target=append_output_executable, args=(cmd,))
    t0.start()

    other_threads = []

    for text in text_file:
        t = Thread(target=write_truncate_output, args=(text,))
        t.start()
        other_threads.append(t)

    # ... other code ...

    # --- at the end of program ---

    running = False

    # --- wait for end of functions ---

    t0.join()
    for t in other_threads:
        t.join()

Exactly the same is with Process
(I keep the same names of variables to show that all is the same)
EDIT
Processes doesn't share memory so it would need to use queue to send information running to processes. So this version need changes.
# ... other imports ...
from multiprocessing import Process

def append_output_executable(cmd):
    while running:
        # ... code ... (without `return`)

def write_truncate_output(text):
    while running:
        # ... code ... (without `return`)

# --- main ---

# global variables

running = True

if __name__ == '__main__':

    # --- create and start ---

    t0 = Process(target=append_output_executable, args=(cmd,))
    t0.start()

    other_threads = []

    for text in text_file:
        t = Process(target=write_truncate_output, args=(text,))
        t.start()
        other_threads.append(t)

    # ... other code ...

    # --- at the end of program ---

    running = False

    # --- wait for end of functions ---

    t0.join()
    for t in other_threads:
        t.join()


Navigating from App.xaml.cs

Question: I want to add an application bar to multiple pages of my app. So, I'm defining the application bar as an application resource so that it can be used by multiple pages. Now, the event handlers for these buttons are in the App class as mentioned here http://msdn.microsoft.com/en-us/library/hh394043%28v=VS.92%29.aspx.
But, these app bar buttons are basically shortcuts to important pages. So, clicking a button would just take you to the corresponding page. But, since I'm defining the event handlers in App.xaml.cs, it doesn't allow me to navigate. I understand the reason for this. But, I don't know how to solve the problem.
NavigationService.Navigate(new Uri("/Counting.xaml", UriKind.RelativeOrAbsolute));

says "An object reference is required for the non-static field, method or property System.Windows.Navigation.NavigationService.Navigate(System.Uri)"
Answer: Does it work if you get access to the frame?
(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/Counting.xaml", UriKind.RelativeOrAbsolute));

Edit:
Each application has only one Frame. It's this frame that exposes the NavigationService. Therefore, the NavigationService is always accessible via the frame since there's always an instance of it in any Windows Phone app. Since you don't usually instantiate a new NavigationService, it's easy to think that it's a static method. However, it's actually a non-static class that gets instantiated automatically when your app is run. All you're doing in this case is getting the global instance, which is attached to the always-present Frame, and using that to navigate between pages. This means your class does not have to instantiate, or explicitly inherit, a NavigationService.
Comment: You're welcome. I've edited my post - hope it explains why it works.
Comment: Thanks a lot. It worked. Could you please explain this a little?
Answer: an other way to navigate to an other page from App.xaml.cs (using the app bar) is using the rootFrame var (at the end line):
private Frame rootFrame = null;
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
    ...
    SettingsPane.GetForCurrentView().CommandsRequested += App_CommandRequested;
}

private void App_CommandRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
SettingsCommand cmdSnir = new SettingsCommand("cmd_snir", "Snir's Page",
              new Windows.UI.Popups.UICommandInvokedHandler(onSettingsCommand_Clicked));
args.Request.ApplicationCommands.Add(cmdSnir);
}

void onSettingsCommand_Clicked(Windows.UI.Popups.IUICommand command)
{
if (command.Id.ToString() == "cmd_snir")
      rootFrame.Navigate(typeof(MainPage)); //, UriKind.RelativeOrAbsolute);

}

Answer: I found this approach a better one. The RootFrame object is already in the App.xaml.cs file, you just need to call it. Also putting this in a UI thread dispatcher is safer.
 Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    // change UI here
                    RootFrame.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                });

Navigating from App.xaml.cs


Washing machine won't turn on

Question: Washing machine: GE GTW490
One day heard a washing machine trying to drain when it was inactive. Unplugged it and plugged it back in, still tried to drain on start up. Now every time it starts it tries to drain itself
There are no visible water in the machine. It's a top loading one. I've checked the drain pump and it seems to work when plugged in. No water is in the hose or pump.
Took it apart and can't see any mechanical problems. Won't enter the diagnostic mode as the manual states. All LEDs should blink but only the first left one does. Pressing start does nothing (should display an error code on LEDs)
Update: got it to enter a diagnosis mode (wait for machine to initialize and then hold the button). Gave a binary error code: ...*.. or 4 "UI software version non-critical
Comment: [Service manual](http://members.msaworld.com/wp-content/uploads/sites/3/2017/04/31-9254.pdf) btw, for reference
Comment: That's not a fault code, it's a menu option -- give the cycle selection option a spin while in that mode and it'll change.  You're in the "Field Service Mode" by the way...
Comment: @ThreePhaseEel yes I figured that out eventually. Would be much easier if they had an LCD screen with words/numbers rather than converting LED lights into binary. But hey, it works
Answer: Figured it out eventually. There is a debugging menu. I ran the drain pump test cycle and then cleared error codes. Rebooted and worked fine
Comment: I'm having the exact same issue. Where did you find the debugging menu to run the drain pump test cycle? Thanks.
Comment: @Lynette There was a paper manual on the inside wall of machine. It had steps how to access debugging menu

Washing machine won't turn on


Hide navigation bar in all the views, swiftUI

Question: Currently I am working on SwiftUI project. I want to hide the build-in navbar. For this purpose I have to add these lines,
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)

to each of view before pushing it into navigation controller in SwiftUI.
   NavigationLink(destination:
                    ForgotPasswordView()
                              .navigationBarBackButtonHidden(true)
                              .navigationBarHidden(true)

    ) {
            Text("Forgot Password?")
                .foregroundColor(.white)
    }

Same will be done for LoginView
NavigationLink(destination:
                        LoginView()
                                  .navigationBarBackButtonHidden(true)
                                  .navigationBarHidden(true)

        ) {
                Text("Login")
                    .foregroundColor(.white)
        }

So I need any generic method like we did in storyboard, hide it from root view and no child will have the navbar on top.
Answer: You can create a custom modifier to hide the navigation bar like this:
struct HideNavBar : ViewModifier {

    func body(content: Content) -> some View {
        content
            .navigationBarTitle("")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
    }
}

extension View {
    var hideNavigationBar: some View {
        modifier(HideNavBar())
    }
}

And use it like this:
NavigationLink(destination:
                    ForgotPasswordView()
                              .hideNavigationBar

    ) {
            Text("Forgot Password?")
                .foregroundColor(.white)
    }

Answer:
Updated for iOS 16+

You can wrap the view by creating a new view that accepts a child view, which adds all the necessary modifiers so that you don't have to repeat it every time.
struct NavigationWrapper<Content: View>: View {
    @ViewBuilder var childView: Content

    var body: some View {
        childView
            .toolbar(.hidden)
    }
}

Now, you can use that wrapper for your navigation link's destination.
Here is an example:
struct ContentView: View {
    var body: some View {
        NavigationStack {
            List {
                ForEach(0..<10) { i in
                    NavigationLink("Row \(i)") {
                        NavigationWrapper {
                            Text("Detailed view for \(i)th row.")
                        }
                    }
                }
            }

            .navigationTitle("RowGap")
            .toolbar(.hidden)
        }
    }
}

It hides out the navigation bar and toolbar completely.


How do I suppress this Analyzer suggestion about a strong reference

Question: I have a class method which uses a while loop to create and use NSTextStorage objects. The object or what's happening isn't really important, but essentially I need to keep a strong reference to the object before the loop ends, so that it isn't released in memory before the loop next runs.
NSTextStorage *strongTextStorageForLoop;
while (condition)
{
    ...
    NSTextStorage *storageObject = [[NSTextStorage alloc] init...
    ...
    strongTextStorageForLoop = nil;
    strongTextStorageForLoop = storageObject
}

Xcode's Static Analyzer is telling me that this variable is useless because its value is never read. That is correct but I still need it for my code to execute properly.
So I'd like to know either how to accomplish this in a cleaner way, or how to suppress the Analyzer's suggestion (without simply doing an NSLog).
Comment: This line is useless: `strongTextStorageForLoop = nil;` because on the next line `strongTextStorageForLoop` is set to another value.
Answer: Why not simply do this:
NSTextStorage *storageObject;
while (condition)
{
    ...
    storageObject = [[NSTextStorage alloc] init...
    ...
}

Does this do what you need? It will keep the last object right up to the point the next one is created.
Comment: Can't believe I didn't just do that in the first place. Thanks!


Center div between two divs

Question: How to center .middle div between two other divs? I tried margin: 0 auto; margin-left: auto, margin-right: auto; etc. But I can't achieve the right effect. This .middle div should be in between the two.
Go full screen to see what I mean.
Thank You.

div {
    border-radius: 4px;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;
}
#header {
    height: 52px;
    width: calc(100% - 16px);
    background-color: #B2D490;
    z-index: 1;
    position: fixed;
    top: 10;
}
h1 {
    color: #FFFFFF;
    padding-left: 25px;
    margin: 0;
    display: inline;
    font-size: 27px;
    line-height: 50px;
}
h2, h3, h4, h5, h6 {
    padding-left: 10px;
    margin: 10px 0 10px 0px;
    color: #00457D;
}
.left {
    width: 300px;
    background-color: #C7E6FF;
    float: left;
    margin-top: 64px;
}
.middle {
    width: 300px;
    background-color: #DEF0FF;
    margin-top: 64px;
    float: left;
}
.right {
    width: 300px;
    background-color: #C7E6FF;
    float: right;
    margin-top: 64px;
}
#footer {
    height: 35px;
    width: 100%;
    background-color: #57C449;
    clear: both;
    position: relative;
    margin-top: 10px;
}
p {
    color: #00579E;
}
#footer p {
    color: #FFFFFF;
    text-align: center;
    margin: auto;
    line-height: 35px;
}
span {
    color: #D4EBFF;
}

  <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
  <title>My Resume</title>

My Resume

Left Column

Some Text

Some Text

Some Text

Some Text

Some Text

Centered Center Column

Some Text

Some Text

Some Text

Right Column

Some Text

Some Text

Some Text

© 2015 Me - the Programmer

Answer: You could wrap your 3 containers into one and the use flexbox
Basically I added a container with a class container-centerand this css:
.container-center {
    display: flex;
    justify-content: space-between;
    }

as in this JSFIDDLE
(I also removed the float from the right, middle, left)
Answer: There is no really easy way to do this with floats but it's simpler if you wrap all the elements in a div (or other sectoning element) and use flexbox.
You should note however, that even with flexbox this requires that the two "side" elements have the same width.
Codepen Demo as the SO Snippets are of resticted width.

div {
  border-radius: 4px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -ms-box-sizing: border-box;
  box-sizing: border-box;
}

h1 {
  color: #FFFFFF;
  padding-left: 25px;
  margin: 0;
  display: inline;
  font-size: 27px;
  line-height: 50px;
}

h2,h3,h4,h5,h6 {
  padding-left: 10px;
  margin: 10px 0 10px 0px;
  color: #00457D;
}

main {
  overflow: hidden;
  padding-top: 64px;
  display: flex;
  justify-content: space-between;
}

.left {
  width: 300px;
  background-color: #C7E6FF;
}

.middle {
  width: 300px;
  background-color: #DEF0FF;
}

.right {
  width: 300px;
  background-color: #C7E6FF;
}

p {
  color: #00579E;
}

span {
  color: #D4EBFF;
}

Left Column

Some Text

Some Text

Some Text

Some Text

Some Text

Centered Center Column

Some Text

Some Text

Some Text

Right Column

Some Text

Some Text

Some Text

Answer: Here is one way of doing it using your HTML as given and using floats.
First, in #header, fix the syntax so that top: 10px, you need units (px).
Since your three div's have known widths, you can take advantage of this with the calc CSS function to determine the right margin for .left as
follows:
margin-right: calc(50% - 300px);

The center of the page is at the 50% position.  Take away 200px for the width of the .left element, and then 100px for the half-width of the .middle element.  The net result is that the .middle element appears in the middle of the page, as you desired.
However, you may want to specify a min-width for the page otherwise the .middle element could overlap the .left if the page width is narrow enough.  Alternatively, take care of small screens using media queries.
(Note that I used widths of 200px instead of 300px so that the demonstration fitted in the small windows of the code editor.)

div {
    border-radius: 4px;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;
}
#header {
    height: 52px;
    width: calc(100% - 16px);
    background-color: #B2D490;
    z-index: 1;
    position: fixed;
    top: 10px;
}
h1 {
    color: #FFFFFF;
    padding-left: 25px;
    margin: 0;
    display: inline;
    font-size: 27px;
    line-height: 50px;
}
h2, h3, h4, h5, h6 {
    padding-left: 10px;
    margin: 10px 0 10px 0px;
    color: #00457D;
}
.left {
    width: 200px;
    background-color: #C7E6FF;
    float: left;
    margin-top: 64px;
    margin-right: calc(50% - 300px);
}
.middle {
    width: 200px;
    background-color: #DEF0FF;
    margin-top: 64px;
    float: left;
}
.right {
    width: 200px;
    background-color: #C7E6FF;
    float: right;
    margin-top: 64px;
}
#footer {
    height: 35px;
    width: 100%;
    background-color: #57C449;
    clear: both;
    position: relative;
    margin-top: 10px;
}
p {
    color: #00579E;
}
#footer p {
    color: #FFFFFF;
    text-align: center;
    margin: auto;
    line-height: 35px;
}
span {
    color: #D4EBFF;
}

  <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
  <title>My Resume</title>

My Resume

Left Column

Some Text

Some Text

Some Text

Some Text

Some Text

Centered Center Column

Some Text

Some Text

Some Text

Right Column

Some Text

Some Text

Some Text

© 2015 Me - the Programmer

Comment: Thank You! Everything works perfectly.
Although I assume you mean 300px (of which 150px is a half) not 200px.
Comment: @ArtemZ I fixed the numbers in my original post to make it consistent with the 200px widths.  In you case with 300px wide elements, the offset would be 450px (300 + 300/2). All the best!
Answer:  .middle {
    margin: auto;
    width: 300px;
    background-color: #DEF0FF;
    margin-top: 64px;
}

This is what you are looking for?
Comment: margin: auto; should horizontally center an element within its container.
If i remember right.
Comment: If the op doesn't want my answer the op can just choose not mark it as an answer. I just know that margin:auto is centering the element. You do not have to be a smartass about it :-)

Center div between two divs


aglio API blueprint render installing error

Question: I am trying to install aglio, https://github.com/danielgtaylor/aglio and unable to proceed forward due to an error i am getting.
npm ERR! Failed at the email@example.com install script 'node-gyp rebuild'.

My server is cento OS 6.5,
I installed node js as explained here https://www.digitalocean.com/community/tutorials/how-to-install-and-run-a-node-js-app-on-centos-6-4-64bit
And then it showed another error as coffee script 1.8.0 is not found. the i installed it as npm install -g coffee-script
so please suggest me how to get rid of this error.
This is the full information about the error.
[root@hellop ~]# npm install -g aglio
npm WARN optional dep failed, continuing firstname.lastname@example.com

> email@example.com install /usr/local/lib/node_modules/aglio/node_modules/socket.io/node_modules/engine.io/node_modules/ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)

^C[root@hellop ~]# npm install aglio
npm WARN optional dep failed, continuing email@example.com

> email@example.com install /root/node_modules/aglio/node_modules/socket.io/node_modules/engine.io/node_modules/ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)

make: Entering directory `/root/node_modules/aglio/node_modules/socket.io/node_modules/engine.io/node_modules/ws/build'
  CXX(target) Release/obj.target/bufferutil/src/bufferutil.o
  SOLINK_MODULE(target) Release/obj.target/bufferutil.node
  SOLINK_MODULE(target) Release/obj.target/bufferutil.node: Finished
  COPY Release/bufferutil.node
  CXX(target) Release/obj.target/validation/src/validation.o
  SOLINK_MODULE(target) Release/obj.target/validation.node
  SOLINK_MODULE(target) Release/obj.target/validation.node: Finished
  COPY Release/validation.node
make: Leaving directory `/root/node_modules/aglio/node_modules/socket.io/node_modules/engine.io/node_modules/ws/build'

> email@example.com install /root/node_modules/aglio/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)

make: Entering directory `/root/node_modules/aglio/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/build'
  CXX(target) Release/obj.target/bufferutil/src/bufferutil.o
  SOLINK_MODULE(target) Release/obj.target/bufferutil.node
  SOLINK_MODULE(target) Release/obj.target/bufferutil.node: Finished
  COPY Release/bufferutil.node
  CXX(target) Release/obj.target/validation/src/validation.o
  SOLINK_MODULE(target) Release/obj.target/validation.node
  SOLINK_MODULE(target) Release/obj.target/validation.node: Finished
  COPY Release/validation.node
make: Leaving directory `/root/node_modules/aglio/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/build'

> firstname.lastname@example.com install /root/node_modules/aglio/node_modules/protagonist
> node-gyp rebuild

make: Entering directory `/root/node_modules/aglio/node_modules/protagonist/build'
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/CBlueprint.o
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/CBlueprintSourcemap.o
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/CSourceAnnotation.o
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/HTTP.o
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/Section.o
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/Serialize.o
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/SerializeJSON.o
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/SerializeYAML.o
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/Signature.o
  CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/snowcrash.o
g++: Internal error: Killed (program cc1plus)
Please submit a full bug report.
See <http://bugzilla.redhat.com/bugzilla> for instructions.
make: *** [Release/obj.target/libsnowcrash/snowcrash/src/snowcrash.o] Error 1
make: Leaving directory `/root/node_modules/aglio/node_modules/protagonist/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23)
gyp ERR! stack     at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:784:12)
gyp ERR! System Linux 2.6.32-431.20.3.el6.x86_64
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /root/node_modules/aglio/node_modules/protagonist
gyp ERR! node -v v0.10.4
gyp ERR! node-gyp -v v1.0.2
gyp ERR! not ok
npm ERR! Linux 2.6.32-431.20.3.el6.x86_64
npm ERR! argv "node" "/usr/local/bin/npm" "install" "aglio"
npm ERR! node v0.10.4
npm ERR! npm  v2.1.16
npm ERR! code ELIFECYCLE

npm ERR! firstname.lastname@example.com install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the protagonist package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls protagonist
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /root/npm-debug.log
[root@hellop ~]# npm install protagonist

Answer: You have two different problems here.
One is that you are using quite an old node and npm.  The digital ocean guide you are following is a bit out of date.  Instead of building your own node version 0.10.4, you should update to a new packaged node 0.10.35 by following the guide here: https://github.com/nodesource/distributions#usage-instructions-1

sudo -s
curl -sL https://rpm.nodesource.com/setup | bash -
yum install -y nodejs
yum groupinstall 'Development Tools'
ctrl+D

Then update to the latest npm

sudo npm install -g npm@latest

That will fix your first problem, an out-of-date node and npm.  Now on to your second problem, which is that you can't build protagonist.  You are running into an internal compiler error:
CXX(target) Release/obj.target/libsnowcrash/snowcrash/src/snowcrash.o
g++: Internal error: Killed (program cc1plus)
Please submit a full bug report.
See <http://bugzilla.redhat.com/bugzilla> for instructions.
make: *** [Release/obj.target/libsnowcrash/snowcrash/src/snowcrash.o] Error 1
If this persists even after you have updated node and npm, then the most likely causes are a hardware error, a corrupt compiler or utility, or a very serious problem in the protagonist package.  Please let me know, and I will try to help you troubleshoot it further.


Is there anyway to access values from the EC2 tags in cloud-init

Question: I know I can access the tags via the metadata and cli tools, but is there anyway to access them whilst running cloud-init? Ideally I'd like to look for a tag called hostname and use it to set the machine host name.
Thanks
Answer: This command can be run from userdata (or any time, really) to access the instance ID from the metadata, and use it to pull the tag called "hostname".  You could assign this to a variable, or use the output to directly set the hostname of the instance.
aws ec2 describe-instances --output text --query 'Reservations[*].Instances[*].Tags[?Key==`hostname`].Value' --instance-id `curl -s http://169.254.169.254/latest/meta-data/instance-id`

Answer: In more recent versions of cloud-init, metadata is available via jinja templates. EC2 also recently started exposing tags via the EC2 instance metadata store. Taken together, you can use this information to retrieve tags as part of your cloud-init.
Example:
cloud-init query -f "{{ds.meta_data.tags.instance}}"
As part of the user data:
## template: jinja
#cloud-config

final_message: |
  My name is {{ds.meta_data.tags.instance.Name}}

Answer: As mentioned in a previous answer by tgoodhart AWS has enabled the ability to get tags from the meta data store on an EC2 instance. However in order to have access to this, you will have to launch the EC2 instances with "InstanceMetadataTags" metadata option enabled. Otherwise the EC2 instance will not publish the tags to its meta data store and cloud init will not be able to read the tags.  This link gives more information on how to enable this metadata option.  https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#work-with-tags-in-IMDS


Converting worlds making no progress

Question: I recently booted up Terraria Xbox One edition for the first time in quite a while, only to be met with a loading screen. This first said "converting characters", but is now "converting worlds".
The progress bar has been at 50% for over an hour now, and no more progress has been made. I'm afraid to restart the Xbox, in case data is corrupted, but I don't know what else I could do in this situation.
So why has it been stuck without progress for so long? And will it eventually complete, or is it probable that something's gone wrong and it will never finish converting the worlds without restarting? Will restarting now corrupt my save data?
Answer: Apparently this happens when your account didn't have a world save pre- patch 1.3. So basically the game is trying to convert an older save to a new save but there's no old save for it to convert it from.
There is a way that you might be able to fix this, but you need another controller and another account that has either never played the game or an account that has had a save pre 1.3.
Steps are as follow (only do this if your save is uploaded to the cloud otherwise you'll lose the progress)

Manage game (press start on Terraria)
Go down to Saved Data -> Delete all, this will delete the local save
Log out of the primary account, log in to the new account, launch the game and create a character + world
Load into the world, press A on the other controller and pick your primary account
You should load into the game, once fully loaded press save & exit.
Close the game, sign out of secondary account and go back to your primary and hopefully everything's fixed.

If you can't try this then I have a feeling you need to completely restart.
Comment: Because you're unable to even get to the main menu you will probably need to reinstall the game. Normally when you start the game there's an option to select a character (you can have multiple) and a world (you can have multiple).
Comment: Thank you, I won't be able to do this unfortunately. How do I reset the game? Do I just understand uninstall and the reinstall it?

Converting worlds making no progress


DynamoDB DocumentClient query with SGIs

Question: I am trying to create an AWS lambda to query a very basic table that looks like the following
Primary Key = "DEVICE_ID"
Secondary Global Index : "USER_ID-index" Partition Key : USER_ID
Secondary Global Index : "USER_EMAIL-index" Partition Key : USER_EMAIL
I am using the Javascript SDK examples and the code below, but I am getting this error:

ValidationException: Query condition missed key schema element: DEVICE_ID

I cannot get any working example code and their documentation is very fragmented.
my code:
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region:'us-east-1'});  //new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {

    var params = {
        TableName: "DEVICE_ID_OWNER",
        KeyConditionExpression: "#user = :user",
        ExpressionAttributeNames: {"#user": "USER_ID"},  // , "#device" : "DEVICE_ID"},
        ExpressionAttributeValues: {":user":event.user_name},
    };

    docClient.query(params, (err, data) => {
        console.log(data);
        if(err){console.log(err);}
        else{console.log(data);}
    });
};

Edit:
This should not be this difficult.  I've tried suing from examples the
  code below... but am getting an authentication error...

is not authorized to perform: dynamodb:Query on resource:

I've looked at the IAM Role Policy and the command is included...
I've never seen anything so poorly documented.
my alternate code (sorry, i've recreated the table names):

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region:'us-east-1'});  //new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {

    var params = {
        TableName: "DEVICE_ATTRIBUTES",
        //Key: {"DEVICE_ID":"098765432109876543214321"},
        IndexName: "USER_ID_INDEX",
        KeyConditionExpression: "USER_ID = :userid",
        ExpressionAttributeValues: {":userid": "BulldogLowell"},
        //ProjectionExpression: "DEVICE_ID, userid"
    };

    docClient.query(params, (err, data) => {
        if(err){console.log(err);}
        else{console.log(data);}
    }), callback();
};

Answer: ANSWER:
In order to query via Global Secondary Index, one must return to IAM and add a new Role Policy for the Index.  My difficulty was that I could "Put" and perform other DB functions, but I finally realized that the error was correct:

is not authorized to perform: dynamodb:Query on resource:

was telling me that the Index was outside the permissions of the original Role Policy.
Is there any way to indicate a path for all the "children" of a particular table?
Comment: Yes:  `/index/*`

DynamoDB DocumentClient query with SGIs


How to call a method inside onStatus() in Spring Webclient

Question: Currently, I just throw an exception in onStatus() when the response code is 4XX or 5XX. However, I want to call another service ( a compensating transaction to undo the changes) and then throw an Exception.
webclient
            .post()
            .uri(url, chargeSeqId)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .acceptCharset(Charset.forName("UTF-8"))
            .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
            .body(BodyInserters.fromValue(pojos))
            .retrieve()
            .onStatus(HttpStatus::is4xxClientError,
                    res -> res.bodyToMono(String.class)
                            .flatMap(error -> Mono.error(new DataValidationException(error))))
            .onStatus(HttpStatus::is5xxServerError,
                    res -> res.bodyToMono(String.class).flatMap(error -> Mono.error(new SystemException(error))))
            .bodyToMono(MyPojos[].class)
            .block();

I want to call the following method when the response code is either 4XX or 5XX before throwing either DataValidationException() or SystemException().
    private String deleteTransaction(Integer transactionID) {
        Mono<String> result = webclient.delete()
                .uri(uriBuilder -> uriBuilder
                        .path(url + "/" + transactionID + "/delete").build())
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + clientProfile.getJwt().getTokenValue()).retrieve()
                .bodyToMono(String.class);
        String ack = result.block();
        return ack;
}

Answer: Instead of calling block inside another block you can make deleteTransaction method return mono.
private Mono<String> deleteTransaction(Integer transactionID) {
        return webclient.delete()
                .uri(uriBuilder -> uriBuilder
                        .path(url + "/" + transactionID + "/delete").build())
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + clientProfile.getJwt().getTokenValue()).retrieve()
                .bodyToMono(String.class);
}

Then you can call this method in the required places in non blocking way. Also as I donot know what you actually want to pass to deleteTransaction method, I have passed chargeSeqId to it.

     .onStatus(HttpStatus::is4xxClientError,
             res -> {
                    var ackMono = deleteTransaction(chargeSeqId); // replace with required input
                    var resBodyMono = res.bodyToMono(String.class);
                    return Mono.zip(ackMono, resBodyMono, (ack,resBody)->Mono.error(new DataValidationException(resBody)));
                    })

This can be done for is5xxServerError as well.
Comment: Aniket, Thank you for the solution. However, I get the compilation error in the return statement - "The method zip(Mono, Mono, BiFunction) in the type Mono is not applicable for the arguments (String, Mono, ( ack,  resBody) -> {})"
Comment: Seems like you have not updated your deleteTransaction method. According to the updated method,  ackMono variable will be a Mono and not String.


Can I turn off blood effects in Goldeneye 007 for Wii?

Question: Can I turn off blood effects in Goldeneye 007 for Wii?  If so, how?
Comment: If you can't find it anywhere in the game's settings menus, then I don't think there would be an easy way to do it, on a Wii.
Answer: There is no option to disable blood in Goldeneye 007 on the Wii. (the blood is fairly minimal as it is)
The only restrictions you can put in place are through the Wii's built-in parental control:
http://www.nintendo.co.uk/NOE/en_GB/faq_for_parents_959_967.html?id=8215
Note that putting this restriction in place will prevent the game from being played in it's entirety unless the passcode is entered.


VS Code does not warn for possible undefined object

Question: I'm creating this React hook, which exposes a user object. Inside the hook I'm defining the type as either 'CognitoUserInterface | undefined'. Since the object will be undefined during initialization.
When I use this hook inside a component, VS code does not warn me that the object will possibly be undefined. I've created an example in CodeSandbox which does however warn. Both use the same code, and same version of TypeScript.
Is this some bug in VS Code? I already tried restarting the TypeScript server. What else could be going on?
My VS Code (not underlining the console.log function on the right)

CodeSandbox (does underline the console.log function, although being on same TypeScript version)

CodeSandbox
Comment: what does your local tsconfig.json looks like ?
Comment: Thanks, had not thought of that yet @MohammadFaisal, it fixed my issue by enabling strict mode which I had forgotten.
Comment: Great Whatever works man! :)
Answer: Based on the comment by Mohammad I saw 'strict' mode was false in my VSCode environment. Enabling this fixed my issue :)