text:
Q: Spark: Intersection of Lists not working I have an RDD of the form:
t1-> (Long, List[Long])

and a list of the form
 t2-> List[Long]

I need to perform union and intersection of the lists. I am trying the following code:
val t1 = a.map(x => (x._1, (List(x._2)))).reduceByKey(_ ++ _)
val t2 = b.map(x => (x._1, (List(x._2)))).reduceByKey(_ ++ _).map(x => x._2).collect()
val t3intersect = t1.map(x => (x._1, (x._2.intersect(t2))))
val t3union = t1.map(x => (x._1, (x._2.union(t2))))

While union returns correct results, intersection is always an empty list. I am not able to identify the problem. Please help! Thanks!
Here's an example:
(1, List(1596, 1617, 1929, 2399, 2674))
(2, List(1702, 1785, 1933, 2054, 2583, 2913))
(3, List(1982, 2002, 2048, 2341, 2666))

and
List(2002, 2399)

This should return intersection:
(1, List(2399))
(2, List())
(3, List(2002))

and union:
(1, List(1596, 1617, 1929, 2399, 2674, 2002))
(2, List(1702, 1785, 1933, 2054, 2583, 2913, 2002, 2399))
(3, List(1982, 2002, 2048, 2341, 2666, 2399))

A: Your intersection code looks OK to me. It should work. Also try doing this for more clarity and maybe performance:
val t3intersect = t1.mapValues( _ intersect t2 )

EDIT: I don't know what is a and b, and what's the logic behind obtaining t1 and t2 from them, but if you initialize t1 and t2 in the Spark REPL as follows, for the sake of testing:
scala> val t1 = sc.parallelize( List(
     | (1, List(1596, 1617, 1929, 2399, 2674)),
     | (2, List(1702, 1785, 1933, 2054, 2583, 2913)),
     | (3, List(1982, 2002, 2048, 2341, 2666)) ), 2)
t1: org.apache.spark.rdd.RDD[(Int, List[Int])] = ParallelCollectionRDD[10] at parallelize at <console>:12

scala> val t2 = List(2002, 2399)
t2: List[Int] = List(2002, 2399)

Then you obtain the expected results:
scala> val tr = t1.mapValues( _ intersect t2 )
tr: org.apache.spark.rdd.RDD[(Int, List[Int])] = MappedValuesRDD[12] at mapValues at <console>:16

scala> tr.collect()
res13: Array[(Int, List[Int])] = Array((1,List(2399)), (2,List()), (3,List(2002)))

So, watch out somewhere else for the error.

A: I've reproduced your problematic case as follows:
object ItersectionList {

  def main(args: Array[String]) {
    val spConf = new SparkConf().setMaster("local[2]").setAppName("ItersectionList")
    val sc = new SparkContext(spConf)

    val a = Array(
      (1, List(1596, 1617, 1929, 2399, 2674)),
      (2, List(1702, 1785, 1933, 2054, 2583, 2913)),
      (3, List(1982, 2002, 2048, 2341, 2666))
    )

    val t2 = List(2002, 2399)

    val t1 = sc.makeRDD(a).map(x => (x._1, (List(x._2)))).reduceByKey(_ ++ _)
    val t3intersect = t1.map(x => (x._1, (x._2.intersect(t2))))
    val t3union = t1.map(x => (x._1, (x._2.union(t2))))

    t3intersect.foreach(println)
    t3union.foreach(println)

  }
}

And the result is as follows:
Intersection:
(2,List())
(1,List())
(3,List())

Union:
(2,List(List(1702, 1785, 1933, 2054, 2583, 2913), 2002, 2399))
(1,List(List(1596, 1617, 1929, 2399, 2674), 2002, 2399))
(3,List(List(1982, 2002, 2048, 2341, 2666), 2002, 2399))

I found it is the problem of List(x._2) in map(x => (x._1, (List(x._2)))).reduceByKey(_ ++ _), which changes the List(a, b, c) to List(List(a, b, c)). Since List(List(a, b, c)) does not match List(a, b, c), the intersection will be null. You can remove List() as follows, and the result will be correct.
 val t1 = sc.makeRDD(a).map(x => (x._1, x._2)).reduceByKey(_ ++ _)

or
 val t1 = sc.makeRDD(a).reduceByKey(_ ++ _)


text:
Q: Array function type syntex I was reviewing someones code and he have wrote a syntax which looks like this
export const actions = {
    [ACTIONS.SOMEACTION.ATTEMPT.name] ({ commit }, payload) {
        return new Promise((resolve, reject) => {

Can someone please explain me what the person is trying to do here? like if someone could explain this syntax?

A: This is either inside of an object or a class and declares a method.
[ACTIONS.SOMEACTION.ATTEMPT.name] is a
computed property name, the methods name will be whatever is stored inside ACTIONS.SOMEACTION.ATTEMPT.name.
({ commit }, payload) those are the two parameters the method takes, the first being an object that gets destructured, so the commit property gets taken out of it.
The method then creates and returns a Promise:
return new Promise((resolve, reject) => {

A: This is using computed property names with destructuring assignment.
Here,
[ACTIONS.SOMEACTION.ATTEMPT.name]

will be converted to the name of the function (due to computer property names). For instance, if ACTIONS.SOMEACTION.ATTEMPT.name was equal to "foo" your result will be somewhat equivlant to:
foo({commit}, payload) {
  // ... function body ...
}

which can later be called using .foo(arg1, arg2)
Note: as we are inside an object the function keyword can be omitted.
The {commit} is using destructuring assignment which can be used to "unpack" properties from an object. In this case, commit will be equal to the commit property from arg1. So if you used your function like so:
.foo({commit:10, id:1}, "bar")

Then your function will "unpack" 10 from your first argument object and make that equal to commit.

A: There are two thing in the code.
Computed Property Names:
[ACTIONS.SOMEACTION.ATTEMPT.name](... this is setting the method for the object whose name will be equal to the value ofACTIONS.SOMEACTION.ATTEMPT.name.
Unpacking fields from objects passed as function parameters
({ commit }, payload)

The line { commit } take out the property commit of the object passed as first parameter to this function.
Eaxample

let str = "func"

let obj = {
  [str]({commit},other){
    console.log(commit,other);
  }
}

obj.func({commit:"the value of commit"},"Other parameter");

A: I am trying to solve.
`let str = "func"

let obj = {
  [str]({commit},other){
    console.log(commit,other);
  }
}

obj.func({commit:"the value of commit"},"Other parameter");`

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cant satisfy constrains in TableViewCell I have TableViewCell with this prototype.
When user select "No" in segmented control, textView for comment should appear. I have created a QuestionTableViewCell class:
class QuestionTableViewCell: UITableViewCell {

    @IBOutlet weak var question: UILabel!
    @IBOutlet weak var answer: UISegmentedControl!
    @IBOutlet weak var comment: UITextView!
    // height constraint for comment textView
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    // spacing between segmentedControl bottom and comment textView top
    @IBOutlet weak var spacingConstraint: NSLayoutConstraint!
}

Then in cellForRowAtIndexPath i set this constrains to satisfy my needs:
if questionsAnswers[indexPath.row] == "" || questionsAnswers[indexPath.row] == "YES" {
    comments[indexPath.row] = ""
    cell.heightConstraint.constant = 0.0
    cell.spacingConstraint.constant = 0.0
} else {
    cell.spacingConstraint.constant = 8
    cell.heightConstraint.constant = 70.0
}

But when i click "No" in cell's textView i got these constrains collisions:
"<NSLayoutConstraint:0x7fa28311d030 V:[UITextView:0x7fa2818c1600'Add a note if necessary..'(70)]>",
"<NSLayoutConstraint:0x7fa283123930 UILabel:0x7fa283119f20'1. Question 1?'.top == UITableViewCellContentView:0x7fa283119de0.topMargin>",
"<NSLayoutConstraint:0x7fa283123a20 V:[UILabel:0x7fa283119f20'1. Question 1?']-(NSSpace(8))-[UISegmentedControl:0x7fa28311a8d0]>",
"<NSLayoutConstraint:0x7fa283123bd0 UITextView:0x7fa2818c1600'Add a note if necessary..'.bottom == UITableViewCellContentView:0x7fa283119de0.bottomMargin>",
"<NSLayoutConstraint:0x7fa283123c20 V:[UISegmentedControl:0x7fa28311a8d0]-(8)-[UITextView:0x7fa2818c1600'Add a note if necessary..']>",
"<NSLayoutConstraint:0x7fa280cb4e30 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7fa283119de0(73.5)]>"

I think this constraint is breaking the layout:
"<NSLayoutConstraint:0x7fa280cb4e30 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7fa283119de0(73.5)]>"

But i don't know how to fix this( Any ideas how it can be solved?


text:
Q: Why does Clang add extra FMA instructions? #include <immintrin.h>

__m256 mult(__m256 num) {
    return 278*num/(num+1400);
}

.LCPI0_0:
        .long   0x438b0000                      # float 278
.LCPI0_1:
        .long   0x44af0000                      # float 1400
mult(float __vector(8)):                           # @mult(float __vector(8))
        vbroadcastss    ymm1, dword ptr [rip + .LCPI0_0] # ymm1 = [2.78E+2,2.78E+2,2.78E+2,2.78E+2,2.78E+2,2.78E+2,2.78E+2,2.78E+2]
        vmulps  ymm1, ymm0, ymm1
        vbroadcastss    ymm2, dword ptr [rip + .LCPI0_1] # ymm2 = [1.4E+3,1.4E+3,1.4E+3,1.4E+3,1.4E+3,1.4E+3,1.4E+3,1.4E+3]
        vaddps  ymm0, ymm0, ymm2
        vrcpps  ymm2, ymm0
        vmulps  ymm3, ymm1, ymm2
        vfmsub213ps     ymm0, ymm3, ymm1        # ymm0 = (ymm3 * ymm0) - ymm1
        vfnmadd213ps    ymm0, ymm2, ymm3        # ymm0 = -(ymm2 * ymm0) + ymm3
        ret

Why does Clang add the two extra FMA instructions to the code? The result should already be computed with vmulps  ymm3, ymm1, ymm2. Don't the extra instructions increase the latency beyond just using vdivps like with -O3?
Godbolt

A: The extra FMAs compensate for the reduced precision of vrcpps. ymm3 is an estimate of the result, but at about half the usual precision.
For simplicity let's say the division was q = a / b.
The first FMA, vfmsub213ps, computes the difference (a * b⁻¹) * b - a, which is an estimate of how much the division was "off" by (in the original scale, before dividing by b). The second FMA approximately divides that difference by b (by multiplying by b⁻¹) so it becomes a difference in the scale of the q, and subtracts it from q to bring it closer to a / b.
If you're OK with reduced precision, you could explicitly use _mm256_rcp_ps and multiply by that, then there will not be extra FMAs to compensate.

Don't the extra instructions increase the latency beyond just using vdivps

Yes, this 4-instruction sequence would take 16 cycles on Ice Lake, while vdivps would take 11 cycles. However, throughput is approximately doubled compared to vdivps. Depending on the context, latency or throughput could be more important .. more often it's throughput. Compilers aren't necessarily very good at deciding which is more important, though in this case I can't blame it (there is no context).


text:
Q: result.batch.entityResults gives undefines error I'm making a nodejs app running on google app engine cloud datastore. The gcloud module is installed but when I type result.batch.entityResults it gives me an undefined error after query it gives an undefined error.
function signup(minHeight,maxHeight,callback) {

  var heightRangeQuery = {
    kinds: [{ name: 'Person' }],
    filter: {
      // Combine multiple filters by using a compositeFilter.
      compositeFilter: {
        operator: 'AND',
        filters: [{
          propertyFilter: {
            property: { name: 'height' },
            operator: 'GREATER_THAN_OR_EQUAL',
            value: { integerValue: minHeight }
          }
        }, {
          propertyFilter: {
            property: { name: 'height' },
            operator: 'LESS_THAN_OR_EQUAL',
            value: { integerValue: maxHeight }
          }
        }]
      },
    }
  };

  datastore.runQuery({
    query: heightRangeQuery
  }).execute(function(err, result) {
    // Iterate over the results.
    if (!err && result.batch.entityResults) {
      result.batch.entityResults.forEach(function(er) {
        var entity = er.entity;
        console.log(entity.properties.firstName.stringValue, ' ',
            entity.properties.lastName.stringValue, ', ',
            entity.properties.height.integerValue, ' inches tall');
      });
      if (result.batch.moreResults == 'NOT_FINISHED') {
        var endCursor = result.batch.endCursor;
        heightRangeQuery.startCursor = endCursor;
        // Reissue the query to get more results...
      }
    }
    callback(err);
  });
}


text:
Q: SetPixel() too slow to erase image background I'm working on window phone application. I want to erase background of an image. I'm using setpixel() method for it. But it erasing background very slow.Here is my code.
 private void Canvas_MouseMove_1(object sender, System.Windows.Input.MouseEventArgs e)
        {
            wrt = new WriteableBitmap(imag, null);
            try
            {
                System.Windows.Media.Color c = new System.Windows.Media.Color();
                c.A = 0;
                c.B = 0; c.R = 0; c.G = 0;
                currentPoint = e.GetPosition(this.imag);

            for (int degrees = 0; degrees <= 360; degrees++)
            {
                for (int distance = 0; distance <= erasersize; distance++)
                {
                    //double angle = Math.PI * degrees / 180.0;
                    double x = currentPoint.X + (distance * Math.Cos(degrees));
                    double y = currentPoint.Y + (distance * Math.Sin(degrees));
                    wrt.SetPixel(Convert.ToInt32(x), Convert.ToInt32(y) - offset, c);
                }
            }

        }

I've searched many articles in google , but noone worked for me. One of the method Bitmap.LockBits suggested to me. But the problem is we cannot add system.drawing into window phone app, because dll not supported.
Can anyone help me to solve this out.
Thanks in advance.

A: WriteableBitmap has nice property called Pixels. It's just an array of integers but it gives you much faster way to manipulate pixels.
First, you need fast color-to-int conventer:
public static int ColorToInt(Color color)
{
    return unchecked((int)((color.A << 24) | (color.R << 16) | (color.G << 8) | color.B));
}

Then you can change your code:
wrt = new WriteableBitmap(imag, null);
try
{
    System.Windows.Media.Color c = new System.Windows.Media.Color();
    c.A = 0;
    c.B = 0; c.R = 0; c.G = 0;
    currentPoint = e.GetPosition(this.imag);

    int width = wrt.PixelWidth;

    for (int degrees = 0; degrees <= 360; degrees++)
    {
        for (int distance = 0; distance <= erasersize; distance++)
        {
            //double angle = Math.PI * degrees / 180.0;
            double x = currentPoint.X + (distance * Math.Cos(degrees));
            double y = currentPoint.Y + (distance * Math.Sin(degrees));
            wrt.Pixels[(int)(y - offset) * width + (int)x] = ColorToInt(c);
        }
    }
}


text:
Q: Changing the size of individual element in flexbox How can I stretch the items inside a div to fill the area, and is it possible to have the items in different sizes without having to modify individually using :nth-child(x). For instance: first, third and fifth item to be twice as big as second and fourth item?

.my_class_a {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

a

b

c

d

e

I do apologize because I don't know how to format in fiddle way.

A: In general you can use flex-grow: 1; to allow flex items to become larger. (Note that i defined a width for the container, otherwise they won't grow)
Concerning your wish about the 2nd, 4th etc. item: You need to define * somewhere*  which items should grow and which not, so you you need at least some  kind of selector for them.

.my_class_a {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  align-items: center;
}

.item {
  border: 1px solid #333;
  flex-grow: 1;
  padding: 12px;
  text-align: center;
}

a

b

c
c

d

e

P.S.: To create a snippet (the "fiddle-line" code example, just click the 7th symbol in the toolbar of the answer window)

A:
How can I stretch the items inside a div to fill the area...

Use the flex-grow property.

and is it possible to have the items in different sizes without having to modify individually using :nth-child(x).

How is the browser supposed to know what you want if you don't define the behavior?

For instance: first, third and fifth item to be twice as big as second and fourth item?

In this case, you can use the even and odd functions of the nth-child() pseudo class.

.my_class_a {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.item:nth-child(odd) {
  flex-grow: 2;
  background-color: lightgreen; /* for demo only */
}

.item:nth-child(even) {
  flex-grow: 1;
  background-color: orange; /* for demo only */
}

/* for aligning item content */
.item {
  display: flex;
  align-items: center;
  justify-content: center;
}

a

b

c

d

e

A: You can use the flex style declaration - it's a shorthand for:
flex-grow | flex-shrink | flex-basis
where flex-basis is the initial width of the flexbox child and flex-grow and flex-shrink determine how quickly the flexbox child will grow or shrink relative to its siblings.
For instance:
an element with flex: 2 2 100px starts with a width of 100px and will grow or shrink twice as fast as flex: 1 1 50px which starts with a width of 50px.
Working Example:

.my_class_a {
display: flex;
width: 100%;
align-items: center;
}

.item {
color: rgb(255, 255, 255);
text-align: center;
font-weight: bold;
}

.item-a,
.item-c,
.item-e {
flex: 2 2 100px;
background-color: rgb(255, 0, 0);
}

.item-b,
.item-d {
flex: 1 1 50px;
background-color: rgb(0, 0, 0);
}

a

b

c

d

e


text:
Q: Automatic indentation on Eclipse PDT when copy-pasting This is a simple question :
Is there any automatic indentation alignment on Eclipse PDT when you do a copy-paste ?
Because it doesn't work on my installation (raw copy-paste), but maybe this is because I use tabs instead of spaces, so I want to know if it will work if I switch to spaces.
Thanks

A: I don't know specifically about PDT, but normally you can indent code with Ctrl + i, and format code with Ctrl + Shift + f (under Preferences -> Java -> Code Style -> Formatter you can specify how the formatter should work).
You can even select multiple files in the navigator and select Source -> Format to format several files then.

A: Tony Vermeiren had a suggestion that worked for me
(from https://bugs.eclipse.org/bugs/show_bug.cgi?id=351771#c17)
open workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.php.ui.prefs
add "smartPaste=false" at the end
save & restart eclipse

A: Actually, such a function exists now for eclipse CDT. In preferences : C++ -> Editor -> Typing, "when pasting", "adjust indentation".
Perhaps it is the same for PDT ?

A: A similar idea to Davids is the use of Save actions: in the Preferences selecting Java/Editor/Save actions you can define an action to format the java code files during saves. It would solve the paste format problems during the save.
If you manage codes with different coding standards, where this formatting might have problems, define multiple formats, on a per-project basis (using the Project properties window).

A: Ok then I guess the answer is : no, this functionnality doesn't exists yet. I've moved to PhpStorm and I'm more than happy.

A: TLDR: uncheck "C/C++->Editor->Typing->Adjust indentation"
Explanation:
When i copy paste the following:

And "C/C++->Editor->Typing->Adjust indentation" checked

The result is that the second line has unwanted indentation:

To fix this just uncheck "C/C++->Editor->Typing->Adjust indentation"


text:
Q: How to get the values inside an array? $playerId= array();
$playerId[] = intval($row['Id']);
$allrounders[] = array(
        'Weight'=>$fullTotal,
    'Id'=>$playerId
);
rsort($allrounders);
$sliceAr = array_slice($allrounders,0,5);
foreach($sliceAr as $allroundK){
         echo $allrounders[]['Id']."
";

}

Question:
In the above array how to get the values of the Id Key accordingly? It takes all the player scores and organizes that with his ID and sorts it descending order. It takes the 1st 5 results. I need the Ids of those.

A: Inside the foreach loop, $allroundK is the item of your array. In this case, it's the array with weight and id. So:
foreach($sliceAr as $allroundK) {
    echo $allroundK['Id']."
";
}

A: Do
echo $allrounders[0]['Id'][0];

Since you have set the array in this manner
$allrounders[] = array(
    'Weight'=>$fullTotal,
    'Id'=>$playerId
);

Here $allrounders[] also means that an array so the elements Weight and Id will be added in the [0th] element of the array $allrounders
If you want to get rid of [0] just set the array like this
$allrounders = array(
    'Weight'=>$fullTotal,
    'Id'=>$playerId
);

And now you can access the Id like
echo $allrounders['Id'][0];

EDIT:
In your case it will work as
foreach($sliceAr as $allroundK){
    echo $allroundK['Id'][0]."
";
}

or
foreach($sliceAr as $allroundK){
    foreach($allroundK['Id'][0] as $allroundJ){
        echo $allroundJ."
";
    }
}


text:
Q: Specific rewrite in htaccess if there is a parameter I have a WordPress instalation with a different CMS on one folder.
Like this:
https://example.com/ => WordPress
https://example.com/en/ => Custom CMS.

My htaccess is:
RewriteEngine on
RewriteRule ^(en)($|/) - [L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

This works fine.
Now, I am moving all the content to the WordPress instalation. I need to preview the changes. I need this:
https://example.com/ => WordPress
https://example.com/en/ => Custom CMS
https://example.com/en/?preview_id=142&preview=true => WordPress

This is, I need to show the WordPress website when there is a "preview" parameter on the URL.
I tried with this:
RewriteEngine on

RewriteCond %{QUERY_STRING} !preview=true [NC]
RewriteRule . /index.php [L]

RewriteRule ^(en)($|/) - [L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

But It doesn't work. Any ideas?

A: As you said I need to show the WordPress website when there is a "preview" parameter on the URL and what you did , this RewriteCond %{QUERY_STRING} !preview=true [NC] will make it in an opposite way so, change it to :
RewriteCond %{QUERY_STRING} preview=true [NC]

and also ad ? at the end of target here RewriteRule . /index.php? to avoid appending query string and make looping .
Your rules shlould look like this :
RewriteCond %{QUERY_STRING} preview=true [NC]
RewriteRule . /index.php? [L]

A: Please just Delete the .htaccess file.
as soon you delete the file system will create new file auto that will work fine for you.


text:
Q: Convert Date with special format using R I have several variables that exist in the following format:
/Date(1353020400000+0100)/
I want to convert this format to ddmmyyyy.  I found this solution for the same problem using php, but I don't know anything about php, so I'm unable to convert that solution to what I need, which is a solution that I can use in R.
Any suggestions?
Thanks.

A: If the format is milliseconds since the epoch then anytime() or as.POSIXct() can help you:
R> anytime(1353020400000/1000)
[1] "2012-11-15 17:00:00 CST"
R> anytime(1353020400.000)
[1] "2012-11-15 17:00:00 CST"
R>

anytime() converts to local time, which is Chicago for me. You would have to deal with the UTC offset separately.
Base R can do it too, but you need the dreaded origin:
R> as.POSIXct(1353020400.000, origin="1970-01-01")
[1] "2012-11-15 17:00:00 CST"
R>

A: As far as I can tell from the linked question, this is milliseconds since the epoch:
x <- "/Date(1353020400000+0100)/"
spl <- strsplit(x, "[()+]")
as.POSIXct(as.numeric(sapply(spl,`[[`,2)) / 1000, origin="1970-01-01", tz="UTC")
#[1] "2012-11-15 23:00:00 UTC"

If you want to pick up the timezone difference as well, here's an attempt:
x <- "/Date(1353020400000+0100)/"
spl <- strsplit(x, "(?=[+-])|[()]", perl=TRUE)

tzo <- sapply(spl, function(x) paste(x[3:4],collapse="") )
dt  <- as.POSIXct(as.numeric(sapply(spl,`[[`,2)) / 1000, origin="1970-01-01", tz="UTC")

as.POSIXct(paste(format(dt), tzo), tz="UTC", format = '%F %T %z')
#[1] "2012-11-15 22:00:00 UTC"

A: The package lubridate can come to the rescue as follows:
as.Date("1970-01-01") + lubridate::milliseconds(1353020400000)

Read: Number of milliseconds since epoch (= 1. January 1970, UTC + 0)
A parsing function can now be made using regular expressions:
parse.myDate <- function(text) {
    num <- as.numeric(stringr::str_extract(text, "(?<=/Date\\()\\d+"))
    as.Date("1970-01-01") + lubridate::milliseconds(num)
}

finally, format the Date with
format(theDate, "%d/%m/%Y %H:%M")
If you also need the time zone information, you can use this instead:
parse.myDate <- function(text) {
    parts <- stringr::str_match(text, "^/Date\\((\\d+)([+-])(\\d{4})\\)/$")
    as.POSIXct(as.numeric(parts[,2])/1000, origin = "1970-01-01", tz = paste0("Etc/GMT", parts[,3], as.integer(parts[,4])/100))
}


text:
Q: Attempting to block "wordpress" useragent is overloading CPU I've had some DDoS issues - specifically the XML-RPC exploit (wordpress) wherein thousands on thousands of Wordpress instances attack my machine.
I have the following in my nginx server block:
    if ($http_user_agent ~ WordPress) { return 444; }
While it does terminate all of the wordpress connections, it still overloads the CPU.
Here are my server specs:
Ubuntu 16.04 LTS - E3-1230v5, 16G DDR4, and a SSD.
I would've assumed that it would be able to handle far more, but that doesn't appear to be the case.  I have attempted to block the wordpress useragent automatically using fail2ban, but all that appeared to do is create a few thousand iptables rules and no end in sight.
Is there a more performant way to block this attack?  Thanks.

A: Is Nginx overloading your CPU? Then you're being target of a sizeable DDoS attack. (Here's a nice explanation of the XML-RPC reflection attack with WordPress.)
I don't think you'll get a better result than what you've already done just with Nginx.
You can try using something like CloudFlare. Keep in mind, though, that you should change your IP to hide behind CloudFlare (if your attacker knows your IP, he/she can still circumvent CloudFlare by sending requests to your IP).


text:
Q: Implicit declarations I'm trying to create a grammar, using implicit declarations. After reading the a forum entry (http://www.eclipse.org/forums/index.php?t=msg&S=2e4a29d7fff0322e71b35e3a3aa63e3f&th=198813&goto=634090#msg_634090) I wrote my own LinkingService:
public class OntMLLinkingService extends DefaultLinkingService {
    private final Map<Rule, Resource> implicitVariables = new HashMap<>();

    public List<EObject> getLinkedObjects(EObject context, EReference ref, INode node) throws IllegalNodeException {
        List<EObject> linking = super.getLinkedObjects(context, ref, node);
        if (!linking.isEmpty())
            return linking;

        if (context instanceof VariableReference && ref.equals(OntMLPackage.eINSTANCE.getVariableReference_Variable())) {
            // Find the rule, the references is used in
            EObject container = context.eContainer();
            while (!(container instanceof Rule))
                container = container.eContainer();

            Rule rule = (Rule) container;

            // Check, if a resource was already created for the rule
            Resource res = implicitVariables.get(rule);
            if (res == null) {
                // Create and register new resource
                res =
                        rule.eResource().getResourceSet()
                                .createResource(URI.createURI("http://wwwcs.vs.hs-rm.de/OntML/Variable/" + UUID.randomUUID()));
                implicitVariables.put(rule, res);
            }

            // Get the cross ref string
            final String crossRefString = getCrossRefNodeAsString(node);
            if (crossRefString != null && !crossRefString.equals("")) {

                // Search for the variable in the resource
                Optional<Variable> existingVar =
                        res.getContents().stream().map(eobj -> (Variable) eobj).filter(var -> var.getName().equals(crossRefString))
                                .findAny();

                if (!existingVar.isPresent()) {
                    // Create and register new variable, if the variable does not exist yet
                    Variable newvar = OntMLFactory.eINSTANCE.createVariable();
                    newvar.setName(crossRefString);
                    res.getContents().add(newvar);
                }
            }

            // Add all contents of the resource to the linked objects
            linking.addAll(res.getContents());
        }

        return linking;
    }
}

I've debugged the "getLinkedObjects" method and everything seems to work fine, but my editor won't show errors anymore, even though I write invalid code and my compiler gets a null pointer, when invoking the "getName" method of any "Variable". I think it's a problem with the LazyLinker and EMF proxies.


text:
Q: Implementing search in MEAN stack application I am new to MEAN stack application domain & wondering how to implement search in my MEAN stack application. Though I have searched for it but the solutions do suggest using elastic search. Pls suggest if its a good idea to use elastic search engine or custom building one for my app

A: It completely depends how much data you expect in search? If its a huge amount of data then go with Elastic search, its light weight and faster. If you have very basic search functionality, you can implement normal search with onChange. If you have very least data, bring the data once and apply filter on Front end side directly.


text:
Q: How to scale video to 3.5:1 without quality lose on Ubuntu? I tried to use ffmpeg: ffmpeg -i <input_file> -vf scale=3.5:1 <output_file>, also tried 3,5 instead of 3.5. But it tells that there is invalid size. I would appreciate any application, Handbrake for example.

A: The syntax is
ffmpeg -i <input_file> -vf scale=3.5*iw:ih <output_file>

This command will apply the default encoding parameters, so specific settings will depend on output format.
You may wish to add setsar=1 after the scale, so that players don't resize the video during playback.


text:
Q: how to set busy indicator when switching pages? I have an SAPUI5 application with 2 pages. When I click on a button it grabs data from the backend and then it proceeds to the next page to display the data. This can take some time based on the amount of data so I want to add a busy indicator between the pages so it doesn't look like the first page is frozen. The problem is that the busy indicator doesn't show up until the second page has loaded which is not what I want.
This is a code sample of my first page controller where I call the busy indicator
onButtonPress: function(){
  //code to grab input data
  var errorsFound = this.checkData();
  if(errorsFound)
       //code to show errors here
  else{
    var BI = new sap.m.BusyDialog();
    BI.open();
    this.processData(); //call function to make ajax call to backend and get data
    this.getOwnerComponent().getRouter().navTo("page2");
    }
 },

checkData: function(){
  //check data for errors;

return errorsFound;

}

on my second page I have this
onInit: function(){
  var route = sap.ui.core.UIComponent.getRouterFor(this);
  route.getRoute("page2").attachMatched(this.initController, this);

}

initController: function(){
 //here I have code to grab the data that came back and I set model to display it

 //Dialog doesn't show up until the app hits comes around this point.

}

Not sure how to make this work, the busy indicator won't come up until the next page comes up. I even tried using the xml fragment like in this example and got the same result.
https://sapui5.hana.ondemand.com/#/sample/sap.m.sample.BusyDialogLight/preview
Any pointers on how to do this right would be appreciated.

A: I think you're doing it the wrong way around. First, navigate the second page and then load the data. This will simplify your app and the whole thing will feel much more natural.
I see you're using the router, if you're depending on a specific variable, you might want to change it to include a route parameter. If you set them in your manifest, it would looks something like:
manifest.json
"routes": [{
    "pattern": "/page2/{parameter}",
    "name": "page2",
    "target": "page2"
}]

And in your controller navigate like this:
page1.controller.js
this.getOwnerComponent().getRouter().navTo("page2", {
   parameter: "my-unique-id"
});

You'll find the parameter ready for you to use in data binding or anything else in the event on the pattern matched (note the change in function here)
page2.controller.js
route.getRoute("page2").attachPatternMatched(this.initController, this);

In which case the callback has your parameter:
page2.controller.js
initController: function(oEvent) {
    var myParameter = oEvent.getParameter("arguments").parameter

    // set the busy indicators and load your data here
}

The added bonus of this approach is that you can navigate directly to myapp#/page2/my-unique-id and it will just load everything without relying on the button on page1.

A: Try to bind busy property to your App control, and set it default as false and set true or false dynamically as per your requirement. Try to keep as simple (Should not use for specific page.)


text:
Q: VBScript Erroring on getelementbyid for an element that doesn't exist I have this block of code and when i = 9 it errors.  The object T_009 does not exist in the html form, but I don't understand why it would cause it to error out, isn't that what the not is nothing checks for?  I have several forms that use vbscript and don't have the time to convert them all so I'm stuck with what it is...
dim i, obj_src, obj_dest
for i = 2 to 720
    set obj_src = document.getelementbyid("T_" & lpad(i,"0",3))
    set obj_dest = document.getelementbyid("s" & lpad(i,"0",3))
    if not obj_src is nothing and not obj_dest is nothing then
        obj_dest.innerhtml = obj_src.value
    end if
    set obj_src = nothing
    set obj_dest = nothing
Next

A: I needed to enable compatibility mode
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">


text:
Q: Can I properly charge 9S battery pack without a BMS? I have a small problem with charging my battery pack.
The first problem is that I do not even know if it really is a battery pack. It's just eight 18650 cells connected in series in order to get +- 33,6V (one cell 4,2V on full charge.)
I'm used to charging one cell with some TP4056 Li-ion cell chargers, but I don't think that this same approach is fine even in this case. I can't just connect one TP4056 to the output of the battery pack, right?
Of course, I tried to google this and I found so called BMS circuits (although, I would like to avoid paying for one :-)).  Just to be clear, is this a 9S battery pack or not?
battery

A: Eight cells in series is an 8S battery pack (8 Series) not 9S.
The problem with charging cells in series is balancing them. You need to effectively charge each cell separately to get it to its own individual full capacity, otherwise you end up with cells being over-discharged which kills the cell.
A balancing charger will monitor the voltage of each and every cell and keep charging until all the cells are completely full. Getting a balancing charger for that kind of voltage and quantity of cells will be tricky and expensive. I would suggest, if you don't need "online" charging, that you should split your battery into two 4S segments and charge each segment separately using a cheaper and more readily available 4S balancing charger.
Either that or consider changing your battery arrangement to be 4S but with each "cell" actually two cells in parallel doubling the capacity and current ability of each cell. Then to get the higher voltage use a suitably rated boost converter to raise the voltage to the level you need.

A: Just open it up to see what kind wiring is going on there. Balancing is always required for Li-on / LiPo packs.


text:
Q: A property related to equidistribution of sequences One version of the equidistribution property raised 2 questions that I am trying to answer. Let a sequence $\{s_1,s_2,s_3,... \}$be equidistributed (ED) on an interval $[a,b]$ if for any subinterval $[c,d]$
$$\lim_{n\to\infty}\frac{\left|\{s_1,s_2,s_3,...\}\cap [c,d]      \right|  }{n} = \frac{c-d}{b-a}.$$
So for a sequence which is not equidistributed, there is at least one interval $[x,y]$ on which the property ED does not hold.
Let us say a sequence has the midpoint property (MP) if for any subinterval $[c,d]$ of $[a,b]$ the mean value of those elements of $s_n$ contained in $[c,d]$ as $n\to \infty$ is $(c+d)/2.$
Suppose a sequence does not have the midpoint property so that for some subinterval $[c,d]$ the limit of the mean of $s_n$ is $ \neq (c+d)/2. $ By expanding $[c,d]$ by equal lengths on either side we can say that any interval (created this way) containing $[c,d]$ also does not have the MP property. In fact $[a,b]$ cannot have the MP property since it contains an interval $[c,d]$ which does not have the property. (This is obviously not a proof.)
So I have two questions.

*

*Can we show: ED $\leftrightarrow$ MP?

*Is there an argument that if a sequence is not ED then it is not ED on any subinterval of $[a,b]?$

A: *

*I'm pretty sure ED and MP are equivalent. ED is equivalent to investigating $\sum_{k\le n} \chi_{[c,d]}(s_k)$, where $\chi_{[c,d]}$ is the indicator function of the interval $[c,d]$. On the other hand, MP is equivalent to investigating $\sum_{k\le n} s_k\cdot \chi_{[c,d]}(s_k)$ (think about why this is true). And both sums can be attacked using Fourier analysis (indeed, the classical Weyl's criterion shows this explicitly for ED).

*That proposed implication is false. Let $\{s_k\}$ be any sequence that is ED on $[0,1]$, and define a new sequence $\{t_k\}$ by
$$
t_k = \begin{cases}
s_{k/2}, &\text{if $k$ is even}, \\
3/2, &\text{if $k$ is odd}.
\end{cases}
$$
Then $\{t_k\}$ is not ED on $[0,2]$, but it does have the correct equidistribution on all subintervals of $[0,1]$.
(That's one interpretation of your question 2. The other interpretation is clearly false: the $\{s_k\}$ from above is not ED on $[0,2]$ but it is ED on the subinterval $[0,1]$ of $[0,2]$.)


text:
Q: C# (Convert DataSet to multiple CSV strings, preserving types, and convert back) I just ran into a problem. I was trying to serialize a DataSet into json and encrypt it using jose-jwt.
But it didn't work, I don't know the reason, but when trying to retrieve, the data was blank.
What I need is a way to convert the DataSet to List of CSVs and get it back, but preserving the Column Types.

A: Then I come with this Code that I want to share, and ask if someone have an easier way to do it. (I'm here to learn after all)
It has an option that add an extra column for each column and only in header it writes the DataColumn.DataType.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;

namespace Demo
{
    public static class Utilities
    {
        private static char separator = '|';

        public static List<string> ToCSV(this DataSet ds, bool withTypes = false)
        {
            List<string> lResult = new List<string>();

            foreach (DataTable dt in ds.Tables)
            {
                StringBuilder sb = new StringBuilder();
                IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                                  Select(column => (column.ColumnName + (withTypes ? separator + column.DataType.ToString() : "")));
                sb.AppendLine(string.Join(separator.ToString(), columnNames));

                foreach (DataRow row in dt.Rows)
                {
                    IEnumerable<string> fields = row.ItemArray.Select(field => $"{field.ToString().Replace("\"", "\"\"").Replace(Environment.NewLine, " ")}{(withTypes ? separator + "" : "") }");
                    sb.AppendLine(string.Join(separator.ToString(), fields));
                }

                lResult.Add(sb.ToString());
            }

            return lResult;
        }

        public static DataSet CSVtoDataSet(this List<string> collectionCSV, bool withTypes = false) //, char separator = '|')
        {
            var ds = new DataSet();

            foreach (var csv in collectionCSV)
            {
                var dt = new DataTable();

                var readHeader = false;
                var lines = csv.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

                foreach (var line in lines)
                {
                    if (!readHeader)
                    {
                        readHeader = true;
                        List<string> splited = line.Split(separator).ToList();

                        for (int i = 0; i < splited.Count; i++)
                        {
                            var columnName = splited[i];
                            var columnType = typeof(string);

                            if (withTypes && splited.Count > 1)
                            {
                                i++;
                                if (lines.Count() > 1)
                                {
                                    columnType = Type.GetType(splited[i]);
                                }
                            }

                            dt.Columns.Add(new DataColumn { ColumnName = columnName, DataType = columnType, AllowDBNull = true });
                        }
                    }
                    else
                    {
                        var splitedRow = line.Split(separator).ToList();

                        List<object> currentRow = new List<object>();

                        for (int i = 0; i < splitedRow.Count; i++)
                        {
                            if (withTypes && splitedRow.Count > 1)
                            {
                                var inputValue = splitedRow[i];
                                var t = dt.Columns[i / 2].DataType;

                                TypeConverter typeConverter = TypeDescriptor.GetConverter(t);
                                object propValue = string.IsNullOrEmpty(inputValue) ? null : typeConverter.ConvertFromString(inputValue);

                                currentRow.Add(propValue);
                                i++;//Next (0/2)
                            }
                            else
                            {
                                currentRow.Add(splitedRow[i]);
                            }
                        }

                        if (!currentRow.All(x => string.IsNullOrEmpty(x.ToString())))
                            dt.Rows.Add(currentRow.ToArray());
                    }
                }

                ds.Tables.Add(dt);
            }

            return ds;
        }
    }
}


text:
Q: Can the call log be closed programatically-android My app makes multiple calls programatically but to do that it needs to override / hide/ close the call log that is displayed at the end of one call. Is this possible? Can it be made to work using PhoneStateListener() type of functionalities ?

A: make a phone call in android and come back to Base activity when the call is ended
using PhoneCallListener

see my answer is here


text:
Q: Strange JSON serialization with FasterXML Jackson I don't understand why I get the serialized JSON for the given Class as shown below.
This is a generated class from WSDL, so I cannot change it:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Lawyer")
public class Lawyer extends Person {

    @XmlElementWrapper(required = true)
    @XmlElement(name = "lawyerOffice", namespace = "http://xxx/addressbook/external/v01/types")
    protected List<LawyerOffice> lawyerOffices;

    public List<LawyerOffice> getLawyerOffices() {
    if (lawyerOffices == null) {
        lawyerOffices = new ArrayList<LawyerOffice>();
    }
    return lawyerOffices;
    }

    public void setLawyerOffices(List<LawyerOffice> lawyerOffices) {
    this.lawyerOffices = lawyerOffices;
    }

}

When a class instance gets serialized with fasterxml.jackson, I get:
{
    "ID": "e0d62504-4dfb-4c92-b70b-0d411e8ed102",
    "lawyerOffice": [
         {
            ...
         }
     ]
}

So the name of the array is lawyerOffice. I expect lawyerOffices.
This is the implementation that I use:
    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.8.6</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

This is my ObjectMapper configuration (injected in CXF):
@Provider
@Consumes({ MediaType.APPLICATION_JSON, "text/json" })
@Produces({ MediaType.APPLICATION_JSON, "text/json" })
public class JsonProvider extends JacksonJsonProvider {

    public static ObjectMapper createMapper() {
    ObjectMapper mapper = new ObjectMapper();

    AnnotationIntrospector primary = new DPAJaxbAnnotationIntrospector(mapper.getTypeFactory());
    AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
    AnnotationIntrospector pair = AnnotationIntrospector.pair(primary, secondary);
    mapper.setAnnotationIntrospector(pair);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.disable(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
    mapper.disable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

    return mapper;

    }

    public JsonProvider() {
    super();

    this.setMapper(createMapper());

    }

}

How can I get the "correct" list name?

A: I found the solution. I enabled the USE_WRAPPER_NAME_AS_PROPERTY_NAME feature option in the objectMapper configuration:
    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector primary = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
    AnnotationIntrospector pair = AnnotationIntrospector.pair(primary, secondary);
    mapper.setAnnotationIntrospector(pair);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ...
    mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME); // <-----
    ...


text:
Q: How can I see who triggered an action in Delphi? When a TAction event fires, the "Sender" is always the action itself. Usually that's the most useful, but is it somehow possible to find out who triggered the action's OnExecute event?
Example
Let's say you have a form with the following:

*

*2 buttons, called Button1 and Button2

*1 TAction called actDoStuff
The same action is assigned to both buttons. Is it possible to show which button I clicked?
Example.dfm
object Form1: TForm1
  object Button1: TButton
    Action = actDoStuff
  end
  object Button2: TButton
    Action = actDoStuff
    Left = 100
  end
  object actDoStuff: TAction
    Caption = 'Do Stuff'
    OnExecute = actDoStuffExecute
  end
end

Example.pas
unit Example;
interface
uses Windows, Classes, Forms, Dialogs, Controls, ActnList, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    actDoStuff: TAction;
    procedure actDoStuffExecute(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation
{$R *.dfm}

procedure TForm1.actDoStuffExecute(Sender: TObject);
begin
  ShowMessage('Button X was clicked');
end;

end.

The only solution I see at the moment is to not use the action property of buttons, but having an eventhandler for each button, and calling actDoStuffExecute() from there, but that sort of defies the whole purpose of using actions in the first place.
I don't want to have a dedicated action for each separate control either. The example above is a simplified version of the problem that I'm facing. I have a menu with a variable number of menu items (file names), and each menu item basically has to do the same thing, except for loading another file. Having actions for each menu item would be a bit silly.

A: Try using the ActionComponent property:

Stores the client component that caused this action to execute.
Use ActionComponent to discern which client component caused this action to execute. For example, examine ActionComponent from an OnExecute event handler if you need to know what user action triggered this action.
When the user clicks a client control, that client sets ActionComponent before calling the action's Execute method. After the action executes, the action resets ActionComponent to nil.

For example:
  ShowMessage( (Sender as TAction).ActionComponent.Name );

Using this I get "Button1" and "Button2" when I click the first and second button respectively.

A: Instead of actions, just use a click event.  Set all buttons to use the same event handler.  Ideally, NOT named after the first button (you can rename it).
Here's the code:
Procedure TMyForm.DestinationButtonClickHandlerThing(Sender: TObject);
begin
  if Sender = Btn_ViewIt then
  begin
    // View It
  end
  else if Sender = Btn_FaxIt then
  begin
    // Fax It
  end
  else if Sender = Btn_ScrapIt then
  begin
    // Scrap It
  end
  else
    ....   // error
   ...
end;

A: Knowing what button triggered the action sort of goes against the point of using actions - an action may be triggered by a button click, or a menu click, or any number of other user activities.  Actions exist to unify the state management of enable/disabled and click handling between buttons and menus.
If you want to know which button fired the action because you want to perform a slightly different operation, or "flavor" the operation differently, then perhaps TAction isn't the right solution for what you want to do.

A: There are situations where the same action should apply to similar controls. The problem with
ShowMessage( (Sender as TAction).ActionComponent.Name );

is that when the action is invoked by a say popup menu, you get the popup menu's name. You could use:
procedure TMyForm.actMyActionExecute(Sender: TObject);
var
  LMyControl: TMyControl;
begin
  if Screen.ActiveControl.Name = 'MyControl1' then
    LMyControl = Sender as TMyControl
  else
    Exit;
  // Use the local variable for whatever needed
end;

A: I have a bunch of panels and I want to let the user right click any of those panels and perform a "delete file" action.
So, I have a single pop-up menu associated with all those panels.
This is how I find out which panel was right clicked:
(Note: I put lots of comments to clearly explain how it works. But if you don't like it, you can compactify the code to 2 lines (see the second procedure)).
So, if you have actions assigned to that pop-up menu:
procedure Tfrm.actDelExecute(Sender: TObject);
VAR
  PopMenu: TPopupMenu;
  MenuItem: TMenuItem;
  PopupComponent: TComponent;
begin
 { Find the menuitem associated to this action }
 MenuItem:= TAction(Sender).ActionComponent as TMenuItem;  { This will crash and burn if we call this from a pop-up menu, not from an action! But we always use actions, so.... }

 { Was this action called by keyboard shortcut? Note: in theory there should be no keyboard shortcuts for this action if the action can be applyed to multiple panels. We can call this action ONLY by selecting (right click) a panel! }
 if MenuItem = NIL then
  begin
   MsgError('This action should not be called by keyboard shortcuts!');
   EXIT;
  end;

 { Find to which pop-up menu this menuitem belongs to }
 PopMenu:= (MenuItem.GetParentMenu as TPopupMenu);

 { Find on which component the user right clicks }
 PopupComponent := PopMenu.PopupComponent;

 { Finally, access that component }
 (PopupComponent as TMonFrame).Delete(FALSE);
end;

If you only have a simple pop-up menu (no actions assigned):
procedure Tfrm.actDelHddExecute(Sender: TObject);
VAR PopupComponent: TComponent;
begin
 PopupComponent := ((Sender as TMenuItem).GetParentMenu as TPopupMenu).PopupComponent;
 (PopupComponent as TMonFrame).Delete(TRUE);
end;

You can put all that code in a single function that returns a TPanel and call it like this:
procedure Tfrm.actDelWallExecute(Sender: TObject);
begin
 if GetPanelFromPopUp(Sender) <> NIL
 then GetPanelFromPopUp(Sender).Delete(FALSE);
end;

A: Ok, in the meanwhile I think I found a workable solution..
I can have all controls use the same action; I just need to override their OnClick event handler, and I just need a single handler for all of them.
I'm still interested to know if it's possible to find out which control triggered the action, but for my current application I'm using a solution that's similar to the code below:
unit Example;

interface

uses
  Windows, Classes, Forms, Dialogs, Controls, ActnList, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    actDoStuff: TAction;
    procedure actDoStuffExecute(Sender: TObject);
    procedure ButtonClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.actDoStuffExecute(Sender: TObject);
begin
  ShowMessage('Button '+TControl(Sender).Name +' was clicked')
end;

procedure TForm1.ButtonClick(Sender: TObject);
begin
  actDoStuffExecute(Sender)
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Button1.OnClick := ButtonClick;
  Button2.OnClick := ButtonClick
end;

end.

A: set the Tag of the buttons as 1, 2, ... etc and then:
procedure TForm1.FormCreate(Sender: TObject);
begin
  Button1.OnClick := ButtonClick;
  Button2.OnClick := ButtonClick;
end;

procedure TForm1.ButtonClick(Sender: TObject);
begin
  if Sender is TButton then
  begin
    Caption := 'Button: ' + IntToStr(TButton(Sender).Tag);
  end;
end;


text:
Q: How do arbitrary floating point values compare to infinity? Basically i want to search for the smallest (positive) value from a bunch of values and need a default value to compare to the first one. The naïve assumption would be, they always compare "less than" (except NaNs, but let's not consider those) but I'm not quite sure.
I'm using the float type and I think it can safely be assumed that my target hardware implements a infinity value.
Here's some example code:
auto leastValue = std::numeric_limits<float>::infinity();
for (auto i = something.begin(), e = something.end(); i != e; ++i)
{
  auto value = (*i)->GetValue();
  if (value < leastValue)
  {
    leastValue = value;
  }
}

A: For IEEE 754 floats, except NaN and infinity, everything is less than infinity. Chances are you'll have those on your platform. If you're paranoid, check with numeric_limits<float>::is_iec559. If your platform happens to be not conforming, use numeric_limits<float>::max(); if your sequence is nonempty, it will not give you a wrong result.

A: I support Michael Madsen comment: You don't need an infinite value for this test,
Store the first value of your bunch in a variable and then start your testing with the second value of the bunch. (and it will even save you one test :P)

A: I think this depends on what behaviour you expect if the sequence is empty. If you want infinity your implementation is fine, otherwise you should use the first value.
auto i = something.begin();
auto e = semething.end();
if (i == e)
  throw std::exception("empty sequence");

auto leastValue = (*i)->GetValue();

for (++i; i != e; ++i)
{
  auto value = (*i)->GetValue();
  if (value < leastValue)
  {
    leastValue = value;
  }
}


text:
Q: Java: Use getter vs caching value I have a getter that returns a String and I am comparing it to some other String.  I check the returned value for null so my ifstatement looks like this (and I really do exit early if it is true)
if (someObject.getFoo() != null && someObject.getFoo().equals(someOtherString)) {
  return;
}

Performancewise, would it be better to store the returned String rather than calling the getter twice like this?  Does it even matter?
String foo = someObject.getFoo();
if (foo != null && foo.equals(someOtherString)) {
  return;
}

To answer questions from the comments, this check is not performed very often and the getter is fairly simple.  I am mostly curious how allocating a new local variable compares to executing the getter an additional time.

A: Use the second block.  The first block will most likely get optimized to the second anyway, and the second is more readable.  But the main reason is that, if someObject is ever accessed by other threads, and if the optimization somehow gets disabled, the first block will throw no end of NullPointerException exceptions.
Also:  even without multi-threading, if someObject is by any chance made volatile, the optimization will disappear.  (Bad for performance, and, of course, really bad with multiple threads.)  And lastly, the second block will make using a debugger easier (not that that would ever be necessary.)

A: It depends entirely on what the getter does. If it's a simple getter (retrieving a data member), then the JVM will be able to inline it on-the-fly if it determines that code is a hot spot for performance. This is actually why Oracle/Sun's JVM is called "HotSpot". :-) It will apply aggressive JIT optimization where it sees that it needs it (when it can). If the getter does something complex, though, naturally it could be slower to use it and have it repeat that work.
If the code isn't a hot spot, of course, you don't care whether there's a difference in performance.
Someone once told me that the inlined getter can sometimes be faster than the value cached to a local variable, but I've never proven that to myself and don't know the theory behind why it would be the case.

A: You can omit the first null check since equals does that for you:

The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

So the best solution is simply:
if(someOtherString.equals(someObject.getFoo())

A: They both look same,even Performance wise.Use the 1st block if you are sure you won't be using the returned value further,if not,use 2nd block.

A: I prefer the second code block because it assigns foo and then foo cannot change to null/notnull.
Null are often required and Java should solve this by using the 'Elvis' operator:
if (someObject.getFoo()?.equals(someOtherString)) {
  return;
}


text:
Q: How can I edit an iframe with proxy? I need to edit an iframe with jQuery but I'm unable to do it.
I tried with:
$(document).ready(function(){
    $("#iframe").on('load',function(){
        $(this).contents().find('body').html('a');
    });
});

This code doesn't work.
EDIT
The iframe is related to a different domain.

A: You just answered your own question. Your code doesn't work because of the Same Origin Policy.
You can use a PHP proxy to bypass this restriction.
<?php
    $url = "http://example.com";
    $domain = file_get_contents($url);
    echo $domain;
?>

And then use that information in your script.
This question has more details about this issue.
Hope this helps!


text:
Q: Connect to objects using one call (Partner in Java) I'm struggling with Java and need some help with 1-1 associations.
Sorry if I'm wording something wrong, I don't know how to word it properly in English.
I want to connect both partner1 and partner2 using one call. Before the call, partner1 and partner2 is not connected, but after, they are. I can't wrap my head around and have been stuck for hours.
Here is what I have so far:
public class Partner {

    private String name;
    private Partner partner;

    public String getName() {
        return this.name;
    }

    public Partner getPartner() {
        return this.partner;
    }

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

    public void setPartner(Partner person) {
        if (this == person) {
            throw new IllegalArgumentException("You can not marry yourself!");
        } else {
            this.partner = person;
        }

    }

    @Override
    public String toString() {
        return "Partner [name=" + name + ", partner=" + partner + "]";
    }

    public static void main(String[] args) {
        Partner p1 = new Partner("Mickey");
        Partner p2 = new Partner("Minnie");
        p1.setPartner(p2);
        System.out.println(p1.getPartner());
    }
}

A: You need to do the other association too, but don't use person.setPartner(this) because it would call it then the other and you'll go deep into recursion until a StackOverflowError
public void setPartner(Partner person) {
    if (this == person) {
        throw new IllegalArgumentException("You can not marry yourself!");
    } // else isn't mandatory as code execution whould stop if first branch taken
    this.partner = person;
    person.partner = this;
}

For the same reason, you may use partner.name. If you keep partner, it' would call it's toString which would call it's partner toString , then road to StackOverflowError
@Override
public String toString() {
    return "Partner [name=" + name + ", partner=" + partner.name + "]";
}


text:
Q: SAP HANA VORA and Hana CONNECTION I want to access a table which is already present in SAP HANA from the Spark-shell using SAP HANA Vora.
I created the table using this command:
sqlContext.sql( s"""
    CREATE TABLE ztemptest
    USING
      com.sap.spark.hana
    OPTIONS (
      path         "ztemptest",
      host         "${HANA_HOSTNAME}",
      dbschema     "${HANA_SCHEMA}",
      user         "${HANA_USERNAME}",
      passwd       "${HANA_PASSWORD}",
      instance     "${HANA_INSTANCE}"
    )
    """.stripMargin )

If I execute a show table command it's showing the table name, however when I execute sqlContext.sql("select * from ztemptest").show I get the error as seen in the below screenshot

A: You need to provide schema name as well .
Give the code as below:
%vora
CREATE TABLE TABLENAME
USING com.sap.spark.hana
OPTIONS (
   path "HANATABLENAME",
   dbschema "SCHEMANAME",
   host "HANA SYSTEM HOST NAME",
   instance " INSTANCENUMBER",
   user "USERNAME",
   passwd "PASSWORD"
)

A: With the HANA datasource (com.sap.spark.hana) you can either query existing tables in HANA or create new tables in HANA. If you want to query an existing table you can either provide the column+datatype information of the HANA table or not. If you do not provide it the schema metadata is queried from HANA automatically.
The error indicates that schema information was provided (maybe in an earlier execution), the table exists in HANA, and the schema information in Vora does not match the table definition in HANA.
Could you drop the existing table definition (show tables is empty) and recreate it with the command that you posted (that does not provide column information).


text:
Q: DropDownList in MVC5 How To Populate Data in the dropdownlist from a Database in c# MVC5 using Code First.
This is What I have Tried:
Model:
 public class EventBooking
{
    [Key]
    public int EventId { get; set; }
    [Required(ErrorMessage = "Enter your full name ")]
    public string FullName { get; set; }

    [Required(ErrorMessage = "Enter your phone number ")]
    [DataType(DataType.PhoneNumber)]
    public string PhoneNumber { get; set; }

    [Required(ErrorMessage = "Enter your email address ")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required(ErrorMessage = "Specify your event start date ")]
    [DataType(DataType.Date)]
    public DateTime StartDate { get; set; }

    [Required(ErrorMessage = "Specify your event end date ")]
    [DataType(DataType.Date)]
    public DateTime EndDate { get; set; }

    //[Required(ErrorMessage = "Select your event")]
    public string EventType { get; set; }

    public string EventDescription { get; set; }

    [Required(ErrorMessage = "Specify the number of your event attendees ")]
    public int NumberOfAttendes { get; set; }
}

Controller:
 public ActionResult Create([Bind(Include="EventId,FullName,PhoneNumber,Email,StartDate,EndDate,EventType,EventDescription,NumberOfAttendes")] EventBooking eventBooking)

    {
        if (ModelState.IsValid)
        {
            db.EventBooking.Add(eventBooking);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(eventBooking);
    }

View:

    @Html.LabelFor(model => model.EventType, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.EventType, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EventType, "", new { @class = "text-danger" })

I am unable to change the view Of Events type into a Drop Down. can anyone please help.

A: I've seen a couple of different ways of populating dropdowns with data, but the way I end up doing it usually revolves around getting your 'event types' into its own list, and sending that back to the view along with the model. The default scaffolded action uses the ViewBag, but you can create your own ViewModel or tack on a list with metadata..
I assume you mean the Get action rather than the Post?
Controller:
// GET: /Create
public ActionResult Create()
    {
        EventBookingViewModel eventBookingViewModel = new EventBookingViewModel
        {
            EventTypes = new SelectList(methodToReturnAListToHere(), "ValueColumn", "DisplayColumn")
        };
        return View(eventBookingViewModel);
    }

View:

     @Html.DropDownListFor(model => model.EventType, Model.EventTypes, new { @class = "form-control" })
     @Html.ValidationMessageFor(model => model.EventType)

In the DropDownListFor, the first parameter is the one you want to store the selected value in, and the second is the SelectList to which you wish to bind.

A: To bind DropDownList in MVC5 as follow :
View Code
@model DepenInjectionINMVC5App.Controllers.DemoController.EventBooking
    @{
        ViewBag.Title = "CreateDDL";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

CreateDDL

        @Html.LabelFor(Model => Model.Id, "Event", new { @class = "control-label" })
        @Html.DropDownListFor(Model => Model.Id, new SelectList(ViewBag.EventList, "Id", "Name"))

Controller Code
public class EventBooking
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public ActionResult CreateDDL()
{
    var eventList = new List<EventBooking>();
    EventBooking eventItem;
    var eventArr = new string[] { "Event-1", "Event-2", "Event-3", "Event-4", "Event-5", "Event-6", "Event-7" };
    for (int index = 0; index < eventArr.Length; index++)
    {
        eventItem = new EventBooking();
        eventItem.Id = index + 1;
        eventItem.Name = eventArr[index];
        eventList.Add(eventItem);
    }
    ViewBag.EventList = eventList;

    return View();
}

A: you want to populate a list of event? Try Something like these maybe it might work for you

            Event type

                <select @Html.EditorFor(model => model.EventType)>
                    <option>//enter you list of items you want to display here</option>
                </select>
                    @Html.ValidationMessageFor(model => model.EventType, "", new { @class = "text-danger" })


text:
Q: Magento 2: Checkout page error Failed to load the "ui/form/element/" template I am getting error on checkout, I have remove all extension and try if this is cause of extensions but no luck.
[ERROR] Failed to load the "ui/form/element/" template requested by "checkout.steps.shipping-step.shippingAddress.shipping-address-fieldset.depotid".

A: This depotid is not default in magento shipping. Looks like some custom extension has added it. Please deploy static content again and try again. Please check DB tables as well once to see if this field is somewhere in quote, sales tables.


text:
Q: Get users list from the table using SQLalchemy I have a model like this.
class Message(db.Model, CRUDMixin):
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    from_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
    to_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
    from_user = db.relationship('User', foreign_keys=[from_id], uselist=False)
    to_user = db.relationship('User', foreign_keys=[to_id],
                          uselist=False)
    date = db.Column(db.TIMESTAMP(), nullable=False)
    content = db.Column(db.String(500), nullable=False)
    room_id = db.Column(db.Integer, db.ForeignKey("room.id"), nullable=False)

What I want to achieve is, for given a user_id, I want to get the list of user to whom the user has messaged or from which users user has received messages from.
For ex:
consider there are 3 users with ids 1,2,3
Messages sent
1 -> 2

2 -> 1

1 -> 3

3 -> 2

Now for user id 1, I want to get the users list with id 2 and 3. and for user 2 ,i would 1 and 3.
How to achieve this?
Thanks in advance.

A: One way to achieve what you're after is to take the union of users that meet your criteria.
user_id = 1

messaged_to = User.query.\
    join(Message, Message.to_id == User.id).\
    filter(Message.from_id == user_id)

messages_from = User.query.\
    join(Message, Message.from_id == User.id).\
    filter(Message.to_id == user_id)

query = messaged_to.union(messages_from)

A: My answer is as below:
def get_users(user_id):
    messages = cls.query.filter(or_(cls.from_id == user_id, cls.to_id == user_id)).subquery()

    users = User.query.join(messages, or_(messages.c.to_id == User.id,
                           messages.c.from_id == User.id)).filter(User.id != user_id)

    return users


text:
Q: How do I make sure sftp server is VSFTPD? On a Wheezy server, I used: aptitude install vsftpd.
I edited the config file at /etc/vsftpd, disabled anonymous login, enabled local accounts, enabled FTP write, enabled the user vsftpduser, disabled ASCII mangling, activated umask 022 to avoid breaking Wordpress plugins (as per the doc)…
Then I used:
ssl_enable=YES
allow_anon_ssl=NO
force_local_data_ssl=YES
force_local_logins_ssl=YES
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO

I also added local_root=public_html (but I'd like to know why, I just followed a tutorial on this one).
With
openssl req -x509 -nodes -days 365 -newkey rsa:1024 \
 -keyout /etc/vsftpd/vsftpd.pem \
 -out /etc/vsftpd/vsftpd.pem

I created a certificate and added the path to the vsftpd.conf file.
Finally I also set up the vsftp client in /etc/ssh/sshd_config with Subsystem sftp internal-sftp instead of the standard.
I modified the banner too.
My issue: I don't see the banner when sftp-ing into the server. I do see it if I ftp into the server (though I get kicked because I enabled force_*_ssl).
I've rebooted the server to no avail.
It looks to me like SFTP still sends me to the openssh sftp server.
syslog and vsftpd.log aren't helping me this day. Where should I look now?

A: For completeness sake, as the issue was mostly linguistic and already resolved from my comment.
By configuring an SSL certificate in VSFTP you're setting up an SSL secured FTP server. That protocol is FTPS.
That protocol is often confused with the incompatible SSH File Transfer Protocol; SFTP. You obviously can't test the VSFTP configuration with an sftp client.
As a footnote, a good multi-purpose tool for transferring data that supports both protocols and more is curl.


text:
Q: Memory region flags in Linux: why both VM_WRITE and VM_MAYWRITE are needed? "Understanding the Linux Virtual Memory Manager" (2007) by Mel Gorman (here's a link to the book chapter) describes the flags of a memory region (vm_area_struct):

VM_WRITE - Pages may be written
VM_MAYWRITE   - Allow the VM_WRITE flag to be set

I don't understand why Linux needs these two flags, rather than just one of them. From the description above, it sounds like VM_MAYWRITE be set while VM_WRITE is not. In what situations? And how does the Linux kernel behave differently in these situations?
For example, the COW mechanism detects COW-protected pages according to their VM_MAYWRITE flag (see the source code). Doesn't the Linux kernel set the VM_WRITE flag when the VM_MAYWRITE is set? If yes, why not having a single flag and have it set from the beginning?

A: Memory protection levels can be changed and the kernel uses the VM_MAY% flags to determine if such changes are allowable.

From the description above, it sounds like VM_MAYWRITE be set while VM_WRITE is not. In what situations?

In the situation that memory is initially read-only and you want to make it writable.

For example, the COW mechanism detects COW-protected pages according to their VM_MAYWRITE flag (see the source code). Doesn't the Linux kernel set the VM_WRITE flag when the VM_MAYWRITE is set? If yes, why not having a single flag and have it set from the beginning?

No, it doesn't. is_cow_mapping() isn't checking that the memory is writable, it's checking that the memory can be made writable via mprotect(). If it can't, then it's clearly not a COW mapping!


text:
Q: LazyVGrid Section header does not stick (PinnedView) as expected within a horizontal scrollview I have a simple LazyVGrid embedded in a vertical and then a horizontal scrollviews. The problem I am having is that the section header is not sticking as it should with a horizontal scrollview. Removing the horizontal scrollview the section works as expected. What am I doing wrong?
Here is the code:
struct ContentView: View {
    var body: some View {
        let columns = Array(repeating: GridItem(.flexible(minimum: 100), spacing: 0), count: 6)
        GeometryReader { geo in
            ScrollView {
                ScrollView(.horizontal) { //removing this line works as expected
                    LazyVGrid(columns: columns, alignment: .leading, spacing: 30, pinnedViews: [.sectionHeaders]) {
                        Section(header: Text("Section 1").font(.title)) {
                            ForEach(0...1000, id:\.self) { index in
                                Text("\(index)")
                            }
                        }
                    }.frame(width: 600)
                }
            }
        }.padding()
    }
}


text:
Q: Reproducibly auto-layouting a BPMN workflow via command line? I am looking for an offline tool (ideally for command line in Linux) which layouts my BPMN diagram automatically and reproducibly, i.e. the same process should always end up in the same layout, i.e. the same coordinates for all activities and flows for each run.
The alternatives I am currently aware of are the following:

*

*Use the yBPMN layouter which comes along with the java application YEd.

*Somehow employ the API of a local Camunda installation, but here I am not sure how exactly that should work when I already have a BPMN-XML in hand where I want to adjust only the coordinates.

*Try to expand bpmn-auto-layout, a project in version 0.1 and a single release(as of Dec. 2019).

*Indirectly let graphviz do the job, e.g. by an algorithm suggested by Ingo Kitzmann, Christoph König, et. Al. on top of it.

*Implement the hierachical layouting  algorithm from scratch. (See e.g. M. Slade: Theses on A layout algorithm for hierarchical graphs with constraints, G. Sander: A fast heuristic for hierarchical Manhattan layout, S. Chitra, B. Kalpana: Hierarchical Directed Acyclic Graph (HDAG) Based Preprocessing Technique for Session Construction, ...)

Is there some other approach for arranging the layout of a BPMN diagram programatically and deterministically?
References

*

*How can I influence Graphviz/dot to make nicer control-flow graphs by removing snaking and better edge crossings?

*camunda api auto layout functionality?

*Merging two versions of bpmn (xml) files

*Graph Hierarchical Layout Algorithm

A: Just recently I became aware of Kroki, which seems to meet your requirements:

*

*can render many diagram types including BPMN based on textual input,

*can interpret coordinates for BPMN diagram elements (see examples),

*can be installed locally as a web service (see installation instructions).


text:
Q: WordPress Theme customization : remove top header from blu theme I'm working with BLU theme and I want to change the header and the menu appearance, if any one have worked with this theme can tell me how to remove those  sections:

A: It is not possible to give exact instructions, without knowing how the Theme has been put together; both structurally and from a coding perspective.
As a broad and general directive, you will need to first create a WordPress Child Theme.  Failure to implement a Child Theme, will result in your desired changes being lost, should you implement an Theme update by the Theme Author.
Once the Child Theme has been created, you will need to find the file responsible for the site's header.  This is typically header.php and is found within the following directory:
wp-content > themes > theme-name
Once found, you would then need to make a copy of this and place it within the root of your Child Theme.  You can then perform the relevant modifications, to the header.php file.
Issues
If you are still seeing the Top Bar/Header, then you will need to go through the header.php and 'read' the code, to see if said file is calling additional templates, responsible for the Top Bar/Header.  Furthermore, look for other files entitled header-[some file name].php.  This is where it will be impossible for someone to give clear instructions, due to not knowing the exact coding used or structural setup implemented.  With knowing such information, it is a fairly simple process.
Have you not thought about asking the Theme Author?

A: Add this to Additional CSS.
custom-header {
padding: 50px 0;
position: relative;
text-align: center;
z-index: 22;
display: none;
background: #181818;

}
Note:  display: none; is the attribute which makes custom Header hide.


text:
Q: Is there a 'complete' event on embedded facebook videos? I want to embed a facebook video in a webapp but do something when it's over.
Similarly to the YouTube API Player, is there any 'complete' event I can listen to on embedded FB videos?

A: One solution/workaround a friend reminded me of is embedding the mp4 in jwplayer and hooking into the player's events API.
Sounds like it might work, but I would rather use a better solution is there is one.


text:
Q: Is this expression for bulk modulus of a fluid incorrect? Equation (6) of Lagrangian and Eulerian Representations of Fluid Flow:Kinematics and the Equations of Motion [PDF], by James F. Price is this:

A convenient measure of the stiffness or inverse compressibility of the material is
$$B=\frac{S_{zz}}{\delta h/h}=-V_{0}\frac{\delta P}{\delta V}=\rho_{0}\frac{\delta P}{\delta\rho}$$
called the bulk modulus.

The $z$ component of stress is $S_{zz},$ and $h$ is measured in the $z$ direction.
I see no way that Equation (6) can be correct for a fluid, which is the primary type of material under discussion.  In order for it to give a finite result, $S_{zz}$ would have to go to zero with $\delta h$. But that would require the fluid to have zero pressure when $\delta h=0$  As far as I am aware, that cannot happen with a fluid.
The left-most equivalence is plausible for a solid.  For a fluid I propose the following modification of Equation (6):
$$B=\frac{\delta S_{zz}}{\delta h/h}=-V_{0}\frac{\delta P}{\delta V}=\rho_{0}\frac{\delta P}{\delta\rho}$$
which means $B$ is dependent on $h$ , and the expression is only valid near $\delta h=0.$  Is this reasonable?

A: Your representation is much more appropriate, and the original version is definitely invalid. But it should also be mentioned that, in general, the bulk modulus refers to an isotropic state of loading, and the implication of using h and Szz is that the loading is not isotropic.


text:
Q: Akka Cluster behind firewall I've configured an Akka cluster (2 nodes) and can run it on free instances of Oracle Cloud. However, I have to keep all TCP ports open. According to netstat -ano -p tcp, other than ports I have in the seed nodes, two other ports are used and their value is not fixed.
If I only keep the two seed ports open, then cluster nodes cannot find each other.
Any idea where these random ports are coming from?
(I am using Akka stream and HTTP, but I doubt that they are related to Akka cluster connecting to seed nodes).
EDIT:
Below you can see my configurations and the main file.
I do use Akka HTTP and Akka Stream and connect to WebSocket (through HTTP). But as I already said, I don't think these are related to Akka cluster nodes not being able to find each other.
akka {

  log-dead-letters = off

  http.client.websocket.periodic-keep-alive-max-idle = 2 seconds

  actor {
    serialize-messages = off
    allow-java-serialization = off
    warn-about-java-serializer-usage = on

    provider = cluster
    serializers {
      proto = "akka.remote.serialization.ProtobufSerializer"
      myown = "myown.Serializer"
    }
    serialization-bindings {
      "com.google.protobuf.Message" = proto
      "myown.Serializee" = myown
    }
  }

  remote {
    artery {
      transport = tcp
      canonical.hostname = ${akka.clustering.public.ip}
      canonical.port     = ${akka.clustering.port}
      bind.hostname      = ${akka.clustering.private.ip}
      bind.port          = ${akka.clustering.port} # Yes, I use the same port
    }
  }

  cluster {
    seed-nodes = [
      "akka://MySystem@123.124.125.126:33221",
      "akka://MySystem@234.123.125.126:22334"]
    downing-provider-class = "akka.cluster.sbr.SplitBrainResolverProvider"
  }

  clustering {
    public.ip  = 127.0.0.1
    private.ip = 127.0.0.1
    port       = 10000
    # Node 1:
    # AKKA_PUBLIC_IP : 123.124.125.126
    # AKKA_PRIVATE_IP: 10.0.0.100
    # AKKA_PORT      : 33221
    # Node 2:
    # AKKA_PUBLIC_IP : 234.123.125.126
    # AKKA_PRIVATE_IP: 10.0.0.200
    # AKKA_PORT      : 22334
    public.ip  = ${?AKKA_PUBLIC_IP}
    private.ip = ${?AKKA_PRIVATE_IP}
    port       = ${?AKKA_PORT}
  }
}

@main
def main(): Unit =

  def behavior = Behaviors.setup[Nothing] { ctx =>
    // Actor1 and Actor2 are two simple actors
    ctx.spawn(Actor1(/*config-object*/), "Actor1.id")
    ctx.spawn(Actor2(/*config-object*/), "Actor2.id")
    Behaviors.empty
  }

  // I do not manipulate configuration
  ActorSystem[Nothing](behavior, "MySystem", ConfigFactory.load())

sudo ufw status gives me Status: inactive. I am using Ingress/Egress rules that can be defined for Virtual Cloud Networks on Oracle instances. If I restrict either one of the Source Port Range or Destination Port Range, nodes won't find each other.

A: It's hard to know without seeing your config. But I'll take some guesses. If these don't work, post your config file and the code you use to initialize the actor system. (Because it would help to know if you are using bootstrap, for example.)
First of all, there really isn't a "seed port". There is a port that Akka remoting listens on (by default 25220, although it's often overridden). That remoting port is the only one that needs to be open in order for cluster formation to happen. (As I mention below, there are some management and monitoring ports you may wish to open, but those aren't needed for cluster formation.) "Seed nodes" are one way of doing discovery and basically is a list of known nodes (both host and port). The point being that there is no special port for seeding/discovery: it uses the same remoting port. The hosts/port you specify in the seed node list are the places you are connecting to, not the ones you are listening on.
The fact that the ports you are seeing are not fixed makes me suspect that you might be running some of the akka cluster samples. In order to demonstrate clustering on a single machine, these samples often start several JVMs that all listen on random ports. It does this so that the nodes don't conflict with each other. An example of this is here where a port of 0 is specified, which results in a random port being chosen. But that's just for demo purposes, and under normal production configs there shouldn't be any non-fixed ports listening.
Again, the entire Akka remoting system (upon which Clustering is an additional layer) runs on a single specified port. This value is specified under remote.artery.canonical.port (presuming you are using the default Artery networking). If you are seeing multiple ports getting opened, especially with non-fixed values, look at what you have specified in your config for that value, as well as potentially places you are overriding that in your code. (Such as here: where the sample code I mentioned overrides the random port with values specified on the command line.)
However, even though I say that Akka remoting runs on a single port, there are a couple of other subsystems that could be opening ports. One is cluster HTTP management.  Another is Telemetry (aka Insights, aka Cinnamon). Neither of these would open random ports, however, and neither would prevent cluster formation.

A: It turned out that the configuration is correct.
All I needed was

*

*sudo iptables -F to clear the IP Tables

*Make the IP Tables persistent so they would not reset back to something else after every reboot.

Clearing IP Tables sounds like a giant security risk, but I already have my rules defined through Oracle's Virtual Cloud Network. Still, I don't know about the security risks that what I did involves.
As for arbitrary port numbers in the output of netstat -ano -p tcp, I think I was interpreting that incorrectly.

*

*First, I think in Akka config I cannot control client port numbers, only the server ones (client/server at the socket level).

*Second, in the output of netstat -ano -p tcp, on every line for my java process, exactly one of the ports in Local Address and Foreign Address columns are what I have in the configuration. So I guess that is how I can figure out client/servers at the socket level in each of those lines (port numbers that I did put in the configuration are client side).