text:
Q: Subsonic linq using activerecord very slow compared to simplerepository Anyone know anything about why linq queries are about 6 times slower when querying using active record vs simplerepository?
The below code runs 6 times slower than when i query the data using a simple repository. This code is executed 1000 times in a loop
Thanks in advance
        string ret = "";
//      if (plan == null)
        {
           plan =VOUCHER_PLAN.SingleOrDefault(x => x.TENDER_TYPE == tenderType);
        }
        if (plan == null)
           throw new InvalidOperationException("voucher type does not exist." + tenderType);

        seq = plan.VOUCHER_SEQUENCES.First();
        int i = seq.CURRENT_NUMBER;
        seq.CURRENT_NUMBER += seq.STEP;
        seq.Save();

A: We did some profiling on this and found SubSonic's record.SingleOrDefault(x=>x.id=someval) to be up to 20x slower than the same query done through CodingHorror. Logged it here: https://github.com/subsonic/SubSonic-3.0/issues/258.
The profiler pointed at this in ExecutionBuilder.cs:
// this sucks, but since we don't track true SQL types through the query, and ADO throws exception if you
// call the wrong accessor, the best we can do is call GetValue and Convert.ChangeType
Expression value = Expression.Convert(
    Expression.Call(typeof (Convert), "ChangeType", null,
                    Expression.Call(reader, "GetValue", null, Expression.Constant(iOrdinal)),
                    Expression.Constant(TypeHelper.GetNonNullableType(column.Type), typeof(Type))
        ),
    column.Type
    );

Disappointing because I really like SubSonic/Linq.
In the end we gave up and I wrote this - http://www.toptensoftware.com/petapoco.  After porting, our load test showed requests per second went up and CPU load dropped from about 80% to 5%.

A: I was able to make a HUGE difference in performance by caching the database instance it creates in the constructor/init procedures.  What I am seeing now is ~2-3x speed up, depending on the situation and the run.
1) The method of just replacing _db with a static instance works fine if you only call the default constructor, and has all the same speed benefits.
// MyProject.MyDB _db;
// replace with a static instance, and remove the "this." from other lines
static MyProject.MyDB _db = new MyDB();

public MyClass() {
    //_db=new MyProject.MyDB();
    Init();
}

2) I have written a little caching class for the DB entries and am calling that from my ActiveRecord.tt file in all the old places where "new()" was used.
// REPLACE "MyDB" with the name of your DB.  Alternately, include this
// class in Context.tt and have it generate the correct name.

class ContextDatabaseCache {

    public static MyDB GetMyDB()
    {
        return GetInstance("~~default~~", () => new MyDB());
    }

    public static MyDB GetMyDB(string connectionString) {
        return GetInstance(connectionString, () => new MyDB(connectionString));
    }

    public static MyDB GetMyDB(string connectionString, string providerName)
    {
        return GetInstance(connectionString + providerName, () => new MyDB(connectionString, providerName));
    }

    private static Dictionary<string, MyDB> _dict = new Dictionary<string, MyDB>();
    private static MyDB GetInstance(string key, Func<MyDB> createInstance)
    {
        if (!_dict.ContainsKey(key)) {
            lock (_dict) {
                if (!_dict.ContainsKey(key)) {
                    _dict.Add(key, createInstance());
                }
            }
        }
        return _dict[key];
    }

    ///<summary>Call this when the "DefaultConnection" string changes in the
    ///         App.exe.config file so that a new db instance will be created
    ///         and pick up the changed value. </summary>
    public static void Clear() {
         _dict.Clear();
    }

}

This is the type of replacement that was made in the ActiveRecord.tt file:
public <#=tbl.ClassName#>(){
    _db=new <#=Namespace#>.<#=DatabaseName#>DB();
    Init();
}

    // becomes this:
public <#=tbl.ClassName#>(){
    _db= <#=Namespace#>.ContextDatabaseCache.Get<#=DatabaseName#>DB();
    Init();
}

A: Apparently this "isn't an issue" with subsonic, though they know it is there.  It will NOT be fixed.  You have to use a crappy batch query syntax to get this, which no one will.
The thing I don't understand about that is that this is the 90% case.  Get a list of records from a table.  It should BE the fast one, not the slow one.  Everyone does it, everywhere, all the time.
So many problems with subsonic.  I had to write caching for the DB field => object field lookups, since they were so damn slow too.


text:
Q: How do I write a Clojure macro to create a regular expression from a String? I'm creating a convenience macro. Part of the convenience is that a regular expression can be specified with just a String, rather than the #"re" notation.
The one part I can't figure out is how to get the macro to take the String and rewrite it as a Clojure regex (e.g., produce the #"re" notation). I think it's a syntax / escaping problem.
My first naive attempt (pretending I only want the String-to-regex part):
(defmacro mymac [mystr] `#~mystr)

Is it even possible to do what I'm trying to do? Or, is there an actual function to take a String and produce a regex, instead of using the # reader macro?
Or should I just drop into Java and use java.util.regex.Pattern?

A: To explain a bit more:
#"" is a reader macro. It is resolved at read time by the reader. So there is no way to create a macro which expands into a reader macro, because the read phase is long gone. A macro returns the actual data structure representing the expanded code, not a string which is parsed again like eg. #define works in C.
j-g-faustus' answer is the Right Way(tm) to go.

A: There is a function for it: re-pattern
user=> (re-pattern "\\d+")
#"\d+"

A: I may be misunderstanding the question, but doesn't this do what you want?
user=> (. java.util.regex.Pattern compile "mystr")
#"mystr"

A: To match a string verbatim, ignoring special characters:
(defn to-regex [some-string]
  (re-pattern (java.util.regex.Pattern/quote some-string)))

Then ... will only match ..., not aaa or any other three letter combination.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Iterating through array - java I was wondering if it was better to have a method for this and pass the Array to that method or to write it out every time I want to check if a number is in the array.
For example:
public static boolean inArray(int[] array, int check) {

    for (int i = 0; i < array.length; i++) {
        if (array[i] == check)
            return true;
    }

    return false;
}

Thanks for the help in advance!

A: If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array.  Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.
If this is something that is invoked repeatedly, place it in a function:
private boolean inArray(int[] array, int value)
{
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value)
        {
            return true;
        }
     }
    return false;
}

A: You can import the lib org.apache.commons.lang.ArrayUtils
There is a static method where you can pass in an int array and a value to check for.
contains(int[] array, int valueToFind)
          Checks if the value is in the given array.
ArrayUtils.contains(intArray, valueToFind);

ArrayUtils API

A: Since atleast Java 1.5.0 (Java 5) the code can be cleaned up a bit. Arrays and anything that implements Iterator (e.g. Collections) can be looped as such:
public static boolean inArray(int[] array, int check) {
   for (int o : array){
      if (o == check) {
         return true;
      }
   }
   return false;
}

In Java 8 you can also do something like:
// import java.util.stream.IntStream;

public static boolean inArray(int[] array, int check) {
   return IntStream.of(array).anyMatch(val -> val == check);
}

Although converting to a stream for this is probably overkill.

A: You should definitely encapsulate this logic into a method.
There is no benefit to repeating identical code multiple times.
Also, if you place the logic in a method and it changes, you only need to modify your code in one place.
Whether or not you want to use a 3rd party library is an entirely different decision.

A: Using java 8 Stream API could simplify your job.
public static boolean inArray(int[] array, int check) {
    return Stream.of(array).anyMatch(i -> i == check);
}

It's just you have the overhead of creating a new Stream from Array, but this gives exposure to use other Stream API. In your case you may not want to create new method for one-line operation, unless you wish to use this as utility.
Hope this helps!


text:
Q: Get children with tagname as  only in javascript I have a HTML as:

 <svg>......</svg>
 ....

 hello

 hello

I m a grand child

 hello

I want to get all the children with tags as "div" of the parent element with id = xyz in a javascript variable.
Such that my output should be:
"
 hello

 hello

I m a grand child

 hello
"

A: If you want only the immediate children of xyz, you can call
var childrendivs = document.querySelectorAll('#xyz > div');

or calculate them yourself, if you use an older browser without document.querySelectorAll-Support
var childrendivs = [],
    children = document.getElementById('xyz').children;
for(var i = 0; i < children.length; i++){
    if (children[i].tagName == "DIV") {
        childrendivs.push(children[i]);
    }
}

A: Unless I misunderstood, this is exactly what getElementsByTagName does.

A: You can simply get the #xyz div first, then find all div children:
var childDivs = document.getElementById('xyz').getElementsByTagName('div')
//                        ^ Get #xyz element;         ^ find it's `div` children.

The advantage of this method over Document.querySelectorAll is that these selectors work in pretty much every browser, as opposed to IE 8/9+ for the queryselector.

A: You can use querySelectorAll:
var childDivs = document.querySelectorAll('#xyz div')

A method to transform the divs to a string (to store or to alert) could be:
var divsHtml = function () {
    var divhtml = [],
        i = -1,
        divs = document.querySelectorAll('#xyz div');
    while (i++ < divs.length) {
        divs[i] && divhtml.push(divs[i].outerHTML);
    }
    return divhtml.join('');
}();

If you need compatibility for older browsers (i.c. IE<8) use @Cerbrus' method to retrieve the divs, or use a shim.
To avoid double listing of (nested) divs, you may want to use
var divsHtml = function () {
    var divhtml = [],
        i = -1,
        divs = document.querySelector('#xyz').childNodes;
    while (i++ < divs.length) {
        divs[i] &&
        /div/i.test(divs[i].tagName) &&
        divhtml.push(divs[i].outerHTML);
        /* ^ this can also be written as:
          if(divs[i] && /div/i.test(divs[i].tagName) {
              divhtml.push(divs[i].outerHTML)
          }
        */
    }
    return divhtml.join('');
}();

[edit 2021] Seven years old, this answer. See this snippet for another approach.

A: To get only the direct children of a specific element tag:

// All `div` children of document (body) (including nested)
document.querySelectorAll('div')
  .forEach(elm => elm.classList.add('querySelectorAll'))

// only direct children of document (body) which matches a `div` selector
const directDivs = [...document.body.children]
  .filter(elm => elm.matches('div'))
  // style only the `div`
  .forEach(elm => elm.classList.add('direct-div-children'))
*:not(body):not(html) {
  margin: 5px;
  padding: 5px;
  border: 3px solid black;
}

.querySelectorAll {
  background: lightyellow;
}

.direct-div-children {
  border: 3px solid red;
}

  A

A1

A2

not a div

B

C


text:
Q: All closed subsets of the image of $\mathbb C^n$ under rational mapping Let $p_1,\dots,$ $p_{n}$, $q_1,\dots,q_{n}$ be polynomials in the variables $z_1,\dots,z_m$ and
$$
Y:=\{(z_1,\dots,z_m):\ q_1(z_1,\dots,z_m)\ne 0,\dots,  q_{n}(z_1,\dots,z_m)\ne 0\}\subset \mathbb C^m.
$$
We define the set $Z\subset\mathbb C^n$ as the image of $Y$ under the mapping
\begin{equation*}
%\begin{split}
\phi:\ (z_1,\dots,z_m)\in Y\mapsto\left(\frac{p_1(z_1,\dots,z_m)}{q_1(z_1,\dots,z_m)},\dots,\frac{p_{n}(z_1,\dots,z_m)}{q_{n}(z_1,\dots,z_m)}\right)\in Z,
%\end{split}
\end{equation*}
that is, $Z=\phi(Y)$. We define the varity $V$ as closure of $Z$ (we use the Zariski topology).
It is clear that if $Y_1$ is a closed subset of $Y$, then the closure of $\phi(Y_1)$ is
a closed subset of $V$.
Question: Is it true that every closed subset of $V$ can be obtained in this way?


text:
Q: cplusplus.com says that the past-the-end of an std::string "shall not be dereferenced" I would like it if you could clear up some confusion for me. I was writing a function that removes duplicate characters in a string, e.g. "AB --> "AAABB".
void remove_dups(std::string& str) {
    std::string::iterator it = str.begin();
    while (it != str.end()) {
        if (*(it+1) == *it) {
            str.erase(it+1);
        } else {
            ++it;
        }
    }
}

It seems to work when I test it. However, I was wondering, shouldn't there be a fencepost issue? When 'it' is the end of the string, the if statement looks at the non-existent next character. According to cplusplus.com,
The past-the-end character is a theoretical character that would follow the last character in the string. It shall not be dereferenced. (http://www.cplusplus.com/reference/string/string/end/)
So I'm wondering why my function seems to pass the tests and how I can rewrite the whole thing in an elegant way to get around the fencepost issue. (Go easy on me, guys. I'm a n00b.)
Rewriting it like
void remove_dups(std::string& str) {
    std::string::iterator it = str.begin();
    while (it != str.end()) {
        if ((it+1) != str.end() && *(it+1) == *it) {
            str.erase(it+1);
        } else {
            ++it;
        }
    }
}

seems inelegant.

A:
So I'm wondering why my function seems to pass the tests

Undefined behaviour doesn't mean it won't do what you want. It may do exactly what you want, just for the wrong reasons. I'm guessing that the undefined behaviour manifests itself as getting you the \0 character, which is not likely to compare equal to other characters in your string.

and how I can rewrite the whole thing in an elegant way to get around the fencepost issue

There are a lot of options, but my personal preference would be something like
if (it != str.end()) {
  ++it;
  while (it != str.end()) {
    /* compare *it and *(it-1) */
  }
}

But beware that erase has to move elements. Suppose you delete 20 characters in total. You will move the remainder of the string one character back, 20 times. You don't need to do that, if you slightly modify your algorithm:
void remove_dups(std::string& str) {
  std::string::iterator src = str.begin();
  std::string::iterator dst = str.begin();
  if (src != str.end()) {
    ++src;
    ++dst;
    while (src != str.end()) {
      if (*src != *(src-1)) {
        *dst = *src;
        ++dst;
      }
      ++src;
    }
    str.resize(dst - str.begin());
  }
}

This approach also has the benefit that it works even if erase moves the string around in memory, which may cause your iterator to break.

A: Standard allows to compare with one past last array element, you are not allowed to dereference it. So you can compare its address, to verify if loop should end but you are not allowed to read contents. Since iterators are mostly pointers, then this rule also applies to string, vector, ...
Also, note that non sequence version of string::erase returns iterator to character that occupies removed element, you might use it as new loop iterator.

A: I think that the cleanest solution is to stop at the end of the string (the last character of the string), since at that point, no further actions are performed anyway.
Therefore while (it != str.end()) should be while (it != str.end() && it != (str.end() - 1)).


text:
Q: How can I squeeze singleton dimension after getting a SubArray? I have a two dimensional array 'v' representing a list of vectors
And I have a three dimensional array 'a' that represents a list of matrices
ILArray v = counter(2, 3);
ILArray a = counter(2, 3, 3);

Now I want to take a subarray of both and do a matrix multiply:
ILArray av = multiply(a[1,full,full], v[1,full]);

It will complain that the dimensions do not match and this is because the dimensions of a[1,full,full] is (1,3,3) and of v[1,full] is (1,3). In other words, the subarrays contain a singleton dimension. In matlab I can remove these singleton dimensions with squeeze(). But how can I do that in ILNumerics?

I just discovered that if the singleton dimension are trailing, then they are automagically removed by ILNumerics, so this works:
ILArray v = counter(3, 2);
ILArray a = counter(3, 3, 2);
ILArray av = multiply(a[full,full, 1], v[full, 1]);

Also, a[full,full,1] has dimension (3,3)  and not (3,3,1).
Does that mean that ILNumerics does not support non-trailing singleton dimensions? In other words, does not support strided arrays in calculations but only contiguous ones? That would be rather restrictive to say the least.
Thanks,
Luc

A: Shouldn't a simple reshape do the trick?
ILArray<int> I = ILMath.counter<int>(1,1,ILMath.size(5,4,3));

I
<Int32> [5,4,3]
    [0]: (:,:,0)
    [1]:          1          6         11         16
    [2]:          2          7         12         17
    [3]:          3          8         13         18
    [4]:          4          9         14         19
    [5]:          5         10         15         20
    [6]: (:,:,1)
    [7]:         21         26         31         36
    [8]:         22         27         32         37
    [9]:         23         28         33         38
    [10]:         24         29         34         39
    [11]:         25         30         35         40
    [12]: (:,:,2)
    [13]:         41         46         51         56
    [14]:         42         47         52         57
    [15]:         43         48         53         58
    [16]:         44         49         54         59
    [17]:         45         50         55         60

I["0;:;:"]
<Int32> [1,4,3]
    [0]: (:,:,0)
    [1]:          1          6         11         16
    [2]: (:,:,1)
    [3]:         21         26         31         36
    [4]: (:,:,2)
    [5]:         41         46         51         56

ILMath.reshape(I["0;:;:"],4,3)
<Int32> [4,3]
    [0]:          1         21         41
    [1]:          6         26         46
    [2]:         11         31         51
    [3]:         16         36         56

Having a squeeze function would be more convenient. You may open a feature request on the bugtracker in order to have it implemented in one of the next releases: http://ilnumerics.net/mantis


text:
Q: Passing Dynamic Array between Sub-Routines I'm trying to pass a dynamic array DArrayRight() between different subroutines, from DefineArrayRight (that will create the Array ) to CellRightMarked ( that will perform the action to the worksheets). Unfortunately I tried without success.
Any suggestions?
Many thanks
Sub DefineArrayRight()
Dim DArrayRight() As Variant ' dynamic array
Dim xrow As Long, i As Long
i = 0
xrow = 2

ReDim DArrayRight(0) ' resize the array to hold 1 string

 Do Until ThisWorkbook.Sheets("Sheet1").Cells(xrow, 2).Value = ""
  If ThisWorkbook.Sheets("Sheet1").Cells(xrow, 3).Value = "Right" Then
    DArrayRight(i) = ThisWorkbook.Sheets("Sheet1").Cells(xrow, 2).Value 'add the value in the array
    i = i + 1 ' increase the upper bound of the array
    ReDim Preserve DArrayRight(i) ' preserve the array
  End If
  xrow = xrow + 1
 Loop
ReDim Preserve DArrayRight(i - 1) ' delete the empty array
End Sub

and pass to this sub routine:
Sub CellRightMarked()
Dim DArrayRight() As Variant
Dim rcell As Range, rrow As Range
Dim r As Integer, i As Long

 For Each sht In ActiveWorkbook.Worksheets
   With sht
     Set rrow = .UsedRange
       For r = LBound(DArrayRight) To UBound(DArrayRight)
        For Each rcell In rrow
            If rcell.Value = DArrayRight(r) Then
                .Range(rcell.Offset(0, 1), rcell.Offset(0, 1)).Font.Color = 255
            End If
        Next rcell
     Next r
   End With
  Next sht
 End Sub

A: VBA has provided the Function for the kind of thing you want to do with a sub. Here is the function you need. It is based on your sub, suggestions for improvement commented.
Function ArrayRight() As Variant

    Dim Fun() As Variant                    ' function return value
    Dim Ws As Worksheet                     ' easier to refer to
    Dim R As Long, Rl As Long               ' row, last row
    Dim i As Long

    ' i = 0                                 ' i is already zero
    ' R = 2                                 ' defined in the For .. Next loop
    ' ReDim DArrayRight(0) ' resize the array to hold 1 string
    ' Not a good idea because the array will have to be completely
    ' re-written each time you expand it: very slow!

    Set Ws = ThisWorkbook.Sheets("Sheet1")
    Rl = Ws.Cells(Ws.Rows.Count, "B").End(xlUp).Row     ' find the last used row in column B
    ReDim Fun(Rl)                           ' maximum to be possibly required

    For R = 2 To Rl
        If Ws.Cells(R, 3).Value = "Right" Then
            Fun(i) = Ws.Cells(R, 2).Value   'add the value in the array
            i = i + 1                       ' next empty array element
            ' ReDim Preserve DArrayRight(i) ' no need to re-write the array
        End If
    ' R = R + 1                             ' Next is doing the counting
    ' Loop                                  ' Next is doing the looping

    If i Then                               ' skip if no match was found
        ReDim Preserve Fun(i - 1)           ' delete the unused part of array
        ArrayRight = Fun
    End If
End Function

The sub below shows how to use the function.
Sub TryArrayRight()

    Dim Arr As Variant

    ' This is the function call.
    ' simply assign its return value to a variable
    Arr = ArrayRight

    ' now test the return
    If IsEmpty(Arr) Then
        MsgBox "The array is empty"
    Else
        MsgBox "The array has " & UBound(Arr) & " elements."

        ' pass the value to another procedure
        CellRightMarked Arr
    End If
End Sub

An here the variable obtained from the function is passed as a parameter to another routine. I commented out your code because I didn't check it. The object is to show the passing of the variable.
Sub CellRightMarked(DArrayRight As Variant)

'    Dim rcell As Range, rrow As Range
'    Dim R As Integer, i As Long
'
'    For Each sht In ActiveWorkbook.Worksheets
'       With sht
'         Set rrow = .UsedRange
'           For R = LBound(DArrayRight) To UBound(DArrayRight)
'            For Each rcell In rrow
'                If rcell.Value = DArrayRight(R) Then
'                    .Range(rcell.Offset(0, 1), rcell.Offset(0, 1)).Font.Color = 255
'                End If
'            Next rcell
'         Next R
'       End With
'    Next sht
 End Sub

Of course, in this particular case it would be easier to call the function from within CellRightMarked as you have suggested yourself.

A: I've solved the issue following your suggestions
Many thanks, this is my solution
Sub DefineArrayRight()
...
Call CellRightMarked(darrayright)
End Sub

and
Sub CellRightMarked(ByRef darrayright As Variant)
...


text:
Q: How to use split on a string and then convert it to object in Javascript I have an array:
let arr = ["a=1", "b=22", "c=11"];

And I want to split the string inside array so it becomes an object later, which will look like:
{a: 1, b: 22, c: 11}

Can I somehow do that

A: You could split the string an map new objects. Later assign all objects to a single object.

var array = ["a=1", "b=22", "c=11"],
    object = Object.assign(
        ...array.map(s => ((k, v) => ({ [k]: +v }))(...s.split('=')))
    );

console.log(object);

A: you can use array.forEach, so you wont be creating an array instead you will iterate through the array, and you can take each item and split so it will create an array
like item = ["a", "1"], you can assign the key as a to the object which is the first index and value is second index,The value is string so you can convert to number and return it.

let arr = ["a=1", "b=22", "c=11"];

var obj = {}
arr.forEach(o => {
 var item = o.split("=");
 return obj[item[0]] = Number(item[1])
})

console.log("required obj", obj)

A: You can use array#map with Object.assign() to create your object. string#split each word on = and generate the object.

let arr = ["a=1", "b=22", "c=11"],
    result = Object.assign(...arr.map(word => {
      let [key,value] = word.split('=');
      return {[key] : +value};
    }));
console.log(result);

You can also use array#reduce.

let arr = ["a=1", "b=22", "c=11"],
    result = arr.reduce((r,word) => {
      let [key,value] = word.split('=');
      r[key] = +value;
      return r;
    }, {});
console.log(result);

A: Here, try this

let arr = ["a=1", "b=22", "c=11"];

const obj = {}

arr.forEach(i => {
   const splitted = i.split('=')
   obj[splitted[0]] = splitted[1]
} )

console.log(obj)


text:
Q: Intended change in behaviour with cypher in Neo4j 1.9.M02-M05? Is that a known issue, and/or intended behaviour in Neo4j 1.9.M02-M05 that you cannot delete nodes and relationships from cypher queries outside a transaction anymore?
The following example code does work in 1.8.2, but not in 1.9.M02-M05:
ExecutionEngine engine = new ExecutionEngine(graphDb);
ExecutionResult result = engine.execute("start n = node(*) match (n)<-[r:SOME_TYPE]-() return r");

final Iterator<Relationship> rels = result.columnAs("r");
assertTrue(rels.hasNext());
Transaction tx = graphDb.beginTx();
try {
    rels.next().delete();
    tx.success();
} finally {
    tx.finish();
}

Stack trace:
org.neo4j.graphdb.TransactionFailureException: Failed to mark transaction as rollback only.
at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:94)
at org.neo4j.kernel.PlaceboTransaction.finish(PlaceboTransaction.java:48)
Caused by: java.lang.NullPointerException
at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:90)

If you move the cypher query into the transaction, it works as before, and as expected:
Transaction tx = graphDb.beginTx();

try {
    ExecutionResult result = engine.execute("start n = node(*) match (n)<-[r:ONE_TO_ONE]-() return r");
    final Iterator<Relationship> rels = result.columnAs("r");
    assertTrue(rels.hasNext());

    rels.next().delete();
    tx.success();
} finally {
    tx.finish();
}

Same with nodes btw.
If you don't use cypher to get the relationship, like f.e. use node.getRelationship() or do an index lookup outside the tx, you can delete the rel.
I've written some tests [1] for structr which all pass with Neo4j 1.8.2, but the two commented out fail with 1.9.M02-1.9.M05 (couldn't test M01 due to dependency problems).
Cheers
Axel
[1] https://github.com/structr/structr/blob/develop/structr-core/src/test/java/org/structr/common/CypherNotInTransactionTest.java
Update: Seems to be related to lazy evaluation. The following code does not throw the exception:
Relationship r = rels.next();

Transaction tx = graphDb.beginTx();

try {

    r.delete();
    tx.success();

    [...]


text:
Q: react says Error: Invalid hook call when I try to use material makestyles I'm new to react and I'm trying to using makestyles and this is how :
in Header.jsx :
import React from "react";
import UseStyles from "./Header_style";
function Header() {
  const classes =UseStyles();
  return (

test

  );
};

export default Header;

and style.js :
import {makeStyles} from '@material-ui/styles';
const UseStyles = makeStyles(theme=>({
    test: {
        backgroundColor: '#BDC3C7',
        color :'red !important',
        widtH : '18%'
    },

    }));
export default UseStyles;

but I'm getting folwing error:
×
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

*edit:
This is how I'm using Header :
import React, { Component } from 'react'
import Header from './component/heder/Header.jsx';

class App extends Component {
    constructor() {
        super();

        this.state = {
            monsters: [],
            searchField: ''
        };
    }
    render() {
        return (

        );
      }
}

export default App;

and another thing, I'm getting following error too :

A: When you place your Header component in the return or render of a parent component make sure you use  and not {Header}
additionally if that's not the problem you can check this link which is the official react thread on that error.
Also posting how you render the component that is throwing the error would be very helpful.
Edit* Additionally you don't need to call makeStyles with a function. Since you are not using the theme, you can just call makeStyles with an object like this
const useStyles = makeStyles({
   test: {
     background: 'white',
     width: '100%'
   }
});

EDIT and additional answers:
Here's a snippet from MUI's official page on styles:

The way you import makeStyles:
import { makeStyles } from '@material-ui/styles
If you import this way you have to have applied the @material-ui/styles module.
If instead in your package.json you use '@material-ui/core and haven't installed @material-ui/styles you could be getting that error because you don't have the module @material-ui/styles.
If you just have @material-ui/core you can still import makeStyles without installing the standalone @material-ui/styles it is all included in @material-ui/core.
Simply import it like this instead:
import { makeStyles } from '@material-ui/core/styles'

A: everybody, I've found the solution!
have to use withStyles.


text:
Q: How to get the date from user input in Java? I need to print a calendar from the input date given by the user. HOWEVER, I AM NOT ALLOWED TO USE ANY PREDEFINED DATE CLASS.
Currently, I am able to print the month and the year, however, I can't seem to figure out how to print day in which that date falls on in the particular month + year. I am very new to Java so any help would be greatly appreciated!
Here is an example of the desired output:
24/05/2020 is a Sunday and locates in the fourth week of May 2020

The calendar of May 2020 is:

MON TUE WED THU FRI SAT SUN
                1   2   3
4   5   6   7   8   9   10
11  12  13  14  15  16  17
18  19  20  21  22  23  24
25  26  27  28  29  30  31

Here is my output so far:
22/5/2020 is a null and located in May

Here is the calendar for May:

         May 2020
-----------------------------
 Sun Mon Tue Wed Thu Fri Sat
                       1   2
   3   4   5   6   7   8   9
  10  11  12  13  14  15  16
  17  18  19  20  21  22  23
  24  25  26  27  28  29  30
  31

Here is what I have tried so far:
import java.util.Scanner;

public class PrintCalendar {

/** Main method */

public static void main(String[] args) {

// Prompt the user to enter year
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter year
System.out.print("Enter year (e.g.1999): ");

int year = scanner.nextInt();

// Prompt the user to enter month
System.out.print("Enter month (1-12): ");

int month = scanner.nextInt();

System.out.println("Enter the day (1-7): ");

int theDay = scanner.nextInt();

// Print calendar for the month of the year
printMonth(year, month, theDay);

}

/** Print the calendar for a month in a year */

static void printMonth(int year, int month, int day) {

// Print the headings of the calendar
printMonthTitle(year, month, day);

// Print the body of the calendar
printMonthBody(year, month);

}

/** Print the month title, e.g., May, 1999 */

static void printMonthTitle(int year, int month, int day) {

System.out.println(day + "/"+  month + "/" + year + " is a " + getDayOfWeek(day) + " and located in " + getMonthName(month));

System.out.println();

System.out.println("Here is the calendar for " + getMonthName(month) + ": ");

System.out.println();

System.out.println("         " + getMonthName(month)

  + " " + year);

System.out.println("-----------------------------");

System.out.println(" Sun Mon Tue Wed Thu Fri Sat");

}

/** Get the English name for the month */

static String getMonthName(int month) {

String monthName = null;

switch (month) {

  case 1: monthName = "January"; break;

  case 2: monthName = "February"; break;

  case 3: monthName = "March"; break;

  case 4: monthName = "April"; break;

  case 5: monthName = "May"; break;

  case 6: monthName = "June"; break;

  case 7: monthName = "July"; break;

  case 8: monthName = "August"; break;

  case 9: monthName = "September"; break;

  case 10: monthName = "October"; break;

  case 11: monthName = "November"; break;

  case 12: monthName = "December";

}

return monthName;

}

public static String getDayOfWeek(int day) {

  String dayName = null;

  switch (day) {

  case 1: dayName = "Sunday"; break;

  case 2: dayName = "Monday"; break;

  case 3: dayName = "Tuesday"; break;

  case 4: dayName = "Wednesday"; break;

  case 5: dayName = "Thursday"; break;

  case 6: dayName = "Friday"; break;

  case 7: dayName = "Saturday";

  }

  return dayName;

}

/** Print month body */

static void printMonthBody(int year, int month) {

// Get start day of the week for the first date in the month
int startDay = getStartDay(year, month);

// Get number of days in the month
int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);

// Pad space before the first day of the month
int i = 0;

for (i = 0; i < startDay; i++)

  System.out.print("    ");

for (i = 1; i <= numberOfDaysInMonth; i++) {

  if (i < 10)

    System.out.print("   " + i);

  else

    System.out.print("  " + i);

  if ((i + startDay) % 7 == 0)

    System.out.println();

}

System.out.println();

}

/** Get the start day of the first day in a month */

static int getStartDay(int year, int month) {

// Get total number of days since 1/1/1800
int startDay1800 = 3;

int totalNumberOfDays = getTotalNumberOfDays(year, month);

// Return the start day
return (totalNumberOfDays + startDay1800) % 7;

}

/** Get the total number of days since January 1, 1800 */

static int getTotalNumberOfDays(int year, int month) {

int total = 0;

// Get the total days from 1800 to year - 1
for (int i = 1800; i < year; i++)

if (isLeapYear(i))

  total = total + 366;

else

  total = total + 365;

// Add days from Jan to the month prior to the calendar month
for (int i = 1; i < month; i++)

  total = total + getNumberOfDaysInMonth(year, i);

return total;

}

/** Get the number of days in a month */

static int getNumberOfDaysInMonth(int year, int month) {

if (month == 1 || month == 3 || month == 5 || month == 7 ||

  month == 8 || month == 10 || month == 12)

  return 31;

if (month == 4 || month == 6 || month == 9 || month == 11)

  return 30;

if (month == 2) return isLeapYear(year) ? 29 : 28;

return 0; // If month is incorrect
}

/** Determine if it is a leap year */

static boolean isLeapYear(int year) {

return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);

  }

}

A: To get day of week you can use your getStartDay() function which will return you the start day of the month using this we can do (day + startDay) % 7 which will give us the day for the current date.
Here are some changes you need to make :
Print statement :
 System.out.println(day + "/" + month + "/" + year + " is a " + getDayOfWeek(day, year, month) + " and located in " + getMonthName(month));

Your Function :
 //pass year and month as well
    public static String getDayOfWeek(int day, int year, int month) {
      String dayName = null;
      //getting start day of month
      int startDay = getStartDay(year, month);//call function
      int days = (day + startDay) % 7;
      //if days will be 0 means start month from monday and leap year
      if (days == 0) {
       //add 1 to day
       days = day + 1;
      } else {
       //use same days
       days = days;

      }
      switch (days) {

       case 1:
        dayName = "Sunday";
        break;

       case 2:
        dayName = "Monday";
        break;

       case 3:
        dayName = "Tuesday";
        break;

       case 4:
        dayName = "Wednesday";
        break;

       case 5:
        dayName = "Thursday";
        break;

       case 6:
        dayName = "Friday";
        break;

       case 7:
        dayName = "Saturday";

      }

      return dayName;
    }

Output :

A: if you use LocalDate, you can find the day name like this
import java.time.LocalDate;

 public static String getDay(int month, int day, int year) {

    return LocalDate.of(year, month, day).getDayOfWeek().name();

    }


text:
Q: curl with chunked Transfer-Encoding I'm using curl to get a web page with chunked Transfer-Encoding header.
When I execute the command on linux bash (CentOS) I receive the pid of the process and I get back the shell, it seems curl is executed in background and after some minutes on the shell itself it appears the output html, I'm assuming it is having this behavior because of the chuncked transfer encoding.
How can I prevent this curl behavior? Is there any way to force a sync connection to wait for the output?

A: Generally, this happens when you try to pass GET params via the command line. The & symbol used to differentiate parameters is also used by the shell to send jobs to the background. The curl command is still running, but the passed arguments are shorter than you expect. They have to be quoted.
For instance, you will get this behaviour with the following command:
curl http://127.0.0.1:8081/streamhtml?nblocks=4&block_size=1600

(In this example, streamhtml creates 4 blocks of size 1600).
The correct call has the URL quoted:
curl 'http://127.0.0.1:8081/streamhtml?nblocks=4&block_size=1600'

As @axelrose mentioned in the comments, it is difficult to be sure without an example command line and output.


text:
Q: turn based game in Java Socket I'm working in a game for college and I'm stuck in how to stop to sent messages to all sockets.  The idea is sent the field to all players.
Then sent the avaible moves to a specific player and the other player waits.
And still doing it until the game ends.
My actual state is that sending the actual state to all players in loop.
Here's my server
import java.net.*;
import java.util.ArrayList;
import java.io.*;

public class Server {

    private static ServerSocket serverSocket;
    private int numJogadores;
    private String color;
    private String nome;
    private ArrayList players = new ArrayList<>();

    public Server() {
        System.out.println("Servidor Reversi");
        numJogadores = 0;
        try {
            serverSocket = new ServerSocket(50001);

        } catch (IOException e) {
            System.out.println("Erro no construtor do servidor!!");
        }
    }

    public ArrayList acceptConnections() {
        try {
            System.out.println("Aguardando jogadores...");
            while (numJogadores < 2) {
                Socket clientSocket = serverSocket.accept();
                numJogadores++;
                if (numJogadores == 1) {
                    color = "white";
                } else {
                    color = "black";
                }
                byte[] line = new byte[100];
                InputStream input = clientSocket.getInputStream();
                OutputStream output = clientSocket.getOutputStream();
                output.write(line);
                input.read(line);
                nome = new String(line);
                Player p = new Player(clientSocket, color, nome);
                players.add(p);
                System.out.println("Jogador #" + numJogadores + " conectou.");
            }
            System.out.println("Dois jogadores conectados. Iniciando jogo...");

        } catch (Exception e) {
            System.out.println("Erro ao aceitar conexões...");
        }
        return players;
    }

    public void closeServer() {
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {

        Server server = new Server();
        ArrayList players = server.acceptConnections();
        System.out.println(players.toString());

        Game game = new Game(players, server);
        game.startGame();

    }

}

Here's my client
import java.net.*;
import java.io.*;

public class Cliente {
    private Socket clienteSocket;
    private DataInputStream input;
    private DataOutputStream output;
    private String mensagemRecebida;
    private String mensagemEnviada;

    public void connect(){
        try{
            clienteSocket = new Socket("localhost", 50001);
            input = new DataInputStream(clienteSocket.getInputStream());
            output = new DataOutputStream(clienteSocket.getOutputStream());
            String nome=null;
            byte [] line = new byte[100];
            while (nome == null){
                System.out.println("Digite seu nome");
                System.in.read(line);
                output.write(line);
                input.read(line);
                nome = new String(line);
            }
        }
        catch (Exception err){
            System.err.println(err);
        }
    }

    public void jogar() {
        try {

            while(true){
                mensagemRecebida = input.readUTF();
                System.out.println(mensagemRecebida);
            }

        } catch (Exception err) {
            System.err.println(err);
        }
    }

    public static void main(String[] args) {
        Cliente cliente = new Cliente();
        cliente.connect();
        cliente.jogar();
    }

}

I sucessfull to send messages to clients. Now im trying to sent the avaible moves to a specific player and the other player waits. And still doing it until the game ends.


text:
Q: How does QuantLib forwardRate function work? I'm looking to find the expected interest rates for some period in the future based on the term structure of government bonds in python.
I'm trying to use this code as a base: http://gouthamanbalaraman.com/blog/quantlib-term-structure-bootstrap-yield-curve.html
I was hoping that this is what the forwardRate() function would do. But if I call:
yieldcurve.forwardRate(d, d+ ql.Period("1Y"), day_count, compounding, freq).rate()
The resulting rate is unreasonably high - above the rates anytime in that one year period.
An I misunderstanding what forwardRate is supposed to do / doing something wrong here / is there another way to get this value easily?

A: Based on that code it sounds like you're looking to calculate the 1Y forward rate for a particular date d. The forwardRate() method you mentioned should do just that, but check that the daycount and compounding are consistent with your yield curve definition since those can cause forward rates to look odd.
Otherwise if the yield curve is upward sloping, it shouldn't be surprising that some forward rates are higher than any of the spot or par rates. That's just a consequence of the term structure.


text:
Q: How to edit Java class for WSDL provided I am working on a java program to call a Oracle Webservice in loop to create some data. But I have been told to use different XML tags that the ones that are provided on the WSDL.
So far, I have found no problems with this, since I learnt to "import" the WSDL url and create the java classes from it.
But now, I face a problem that I don't know how to
So far, I have found no problems with this, since I learnt to "import" the WSDL url and create the java classes from it.
But now, I face a problem that I don't know how to create this new tags on the Java classes, or even of this will work.
     <com:StandardReceiptFLEXVA>
           <!--Optional:-->
           <stan:CashReceiptId>?</stan:CashReceiptId>
           <!--Optional:-->
           <stan:__FLEX_Context>?</stan:__FLEX_Context>
           <!--Optional:-->
           <stan:__FLEX_Context_DisplayValue>?
           </stan:__FLEX_Context_DisplayValue>
           <!--Optional:-->
           <stan:_FLEX_NumOfSegments>?</stan:_FLEX_NumOfSegments>
        </com:StandardReceiptFLEXVA>

This is the standard code that SOAPUI generates when I give the WSDL url. But Oracle support team (which I have contacted previously) have told me that I need to use this:
<com:StandardReceiptFLEXVA xsi:type="stan:Fianzas"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

           <stan:__FLEX_Context>FEE</stan:__FLEX_Context>
       <stan:modalidad>Provisional</stan:modalidad>
       <stan:tipoFianza>CASH</stan:tipoFianza>
       <stan:actividadConApbc>Test</stan:actividadConApbc>
           <stan:numReferenciaMigracion>99</stan:numReferenciaMigracion>

        </com:StandardReceiptFLEXVA>

That Works on SOAPUI, but when I go to my Java class, the are no set/get but the "standard" ones.. So I thought I should edit the java class and add these. But I don't know how to specify the xsi:type="stan:Fianzas" attribute on Java. I hope I managed to explained myself correctly, since I am not an English speaker.
Thank you in advance.

A: Since your new WSDL file is working fine in SoapUI, then now you new to (re-generate) the java client code from the new updated WSDL file.
You can achieve that in SoapUI itself by following the instructions given in below links. It basically shows you how you can use different code generation tools like Axis 1.X, Axis 2, CXF 2.X, and .NET 2.0 to generate client code.
SOAP Code Generation
Generating Client JAVA code for WSDL using SOAP UI


text:
Q: Identical VMs behave differently I have 2 Centos 6.7 OpenVZ VPS'.
I have copied the entire disk image from the first one (server1) to the second one (server2).
Now I have a couple of issues with server1 that I don't have with server2 (one would think that it would be the other way round).
On server1 rsyslogd stop working after a minute or so of running (to log something I have to spam the restart command for rsyslogd) however on server2 all is fine. I tried reinstalling rsyslogd but it didn't yield any good results.
Another issue I have is mail not getting through to outlook.com. However if I send it from server2 all is fine. They both have the same config files none of them are blacklisted.
Could these be caused by the OpenVZ host machine?
This is all a bit bizarre.


text:
Q: Count the number of pages in a PDF in only PHP I need a way to count the number of pages of a PDF in PHP.  I've done a bit of Googling and the only things I've found either utilize shell/bash scripts, perl, or other languages, but I need something in native PHP.  Are there any libraries or examples of how to do this?

A: You could try fpdi (see here), as you can see when setting the sourcefile you get back the page numbers.

A: Try this :
<?php
if (!$fp = @fopen($_REQUEST['file'],"r")) {
        echo 'failed opening file '.$_REQUEST['file'];
}
else {
        $max=0;
        while(!feof($fp)) {
                $line = fgets($fp,255);
                if (preg_match('/\/Count [0-9]+/', $line, $matches)){
                        preg_match('/[0-9]+/',$matches[0], $matches2);
                        if ($max<$matches2[0]) $max=$matches2[0];
                }
        }
        fclose($fp);
echo 'There '.($max<2?'is ':'are ').$max.' page'.($max<2?'':'s').' in '. $_REQUEST['file'].'.';
}
?>

The Count tag shows the number of pages in the different nodes. The parent node has the sum of the others in its Count tag, so this script just looks for the max (that is the number of pages).

A: If using Linux, this is much faster than using identify to get the page count (especially with a high number of pages):
exec('/usr/bin/pdfinfo '.$tmpfname.' | awk \'/Pages/ {print $2}\'', $output);

You do need pdfinfo installed.

A: this one does not use imagick:
function getNumPagesInPDF($file)
{
    //http://www.hotscripts.com/forums/php/23533-how-now-get-number-pages-one-document-pdf.html
    if(!file_exists($file))return null;
    if (!$fp = @fopen($file,"r"))return null;
    $max=0;
    while(!feof($fp)) {
            $line = fgets($fp,255);
            if (preg_match('/\/Count [0-9]+/', $line, $matches)){
                    preg_match('/[0-9]+/',$matches[0], $matches2);
                    if ($max<$matches2[0]) $max=$matches2[0];
            }
    }
    fclose($fp);
    return (int)$max;

}

A: function getNumPagesPdf($filepath) {
    $fp = @fopen(preg_replace("/\[(.*?)\]/i", "", $filepath), "r");
    $max = 0;
    if (!$fp) {
        return "Could not open file: $filepath";
    } else {
        while (!@feof($fp)) {
            $line = @fgets($fp, 255);
            if (preg_match('/\/Count [0-9]+/', $line, $matches)) {
                preg_match('/[0-9]+/', $matches[0], $matches2);
                if ($max < $matches2[0]) {
                    $max = trim($matches2[0]);
                    break;
                }
            }
        }
        @fclose($fp);
    }

    return $max;
}

This does exactly what i want:
I just worked out this method of getting pdf page numbers...
after getting the pdf page count i just add break to the while so that it does not go in infinite loop here....

A: I know this is pretty old... but if it's relevant to me now, it can be relevant to others too.
I just worked out this method of getting page numbers, as the methods listed here are inefficient and extremely slow for large PDFs.
$im = new Imagick();
$im->pingImage('name_of_pdf_file.pdf');
echo $im->getNumberImages();

Seems to be working great for me!

A: You can use the ImageMagick extension for PHP.  ImageMagick understands PDF's, and you can use the identify command to extract the number of pages.  The PHP function is Imagick::identifyImage().

A: I actually went with a combined approach. Since I have exec disabled on my server I wanted to stick with a PHP based solution, so ended up with this:
Code:
function getNumPagesPdf($filepath){
    $fp = @fopen(preg_replace("/\[(.*?)\]/i", "",$filepath),"r");
    $max=0;
    while(!feof($fp)) {
            $line = fgets($fp,255);
            if (preg_match('/\/Count [0-9]+/', $line, $matches)){
                    preg_match('/[0-9]+/',$matches[0], $matches2);
                    if ($max<$matches2[0]) $max=$matches2[0];
            }
    }
    fclose($fp);
    if($max==0){
        $im = new imagick($filepath);
        $max=$im->getNumberImages();
    }

    return $max;
}

If it can't figure things out because there are no Count tags, then it uses the imagick php extension. The reason I do a two-fold approach is because the latter is quite slow.

A: On *nix environment you can use:
exec('pdftops ' . $filename . ' - | grep showpage | wc -l', $output);

Where pdftops should be installed as default.
Or as Xethron suggested:
pdfinfo filename.pdf | grep Pages: | awk '{print $2}'

A: $pdftext = file_get_contents($caminho1);

 $num_pag = preg_match_all("/\/Page\W/", $pdftext,$dummy);

A: Using only PHP can result in installing complicated libraries, restarting Apache etc. and many pure PHP-ways (like opening streams and using regex) are inaccurate.
The included answer is the only fast and reliable way I can think of. It uses a single executable though that doesn't have to be installed (either *nix or Windows) and a simple PHP script extracts the output. The best thing is that I haven't seen a wrong pagecount yet!
It can be found here, including why the other approaches "don't work":
Get the number of pages in a PDF document


text:
Q: Convert data frame into set using python I have multiple data frames and need to convert that into sets. I have converted that for single data frame but now need to do it in loop so if I get any no of data frame then will get converted into set using loop. Need individual set for individual data frame. I have used
all_elems = list(set().union(*set_names))

but not works as per my requirement. I want to convert these data frame into set to plot that union set values for visualization.

A: Since you want to convert the values in the columns to set, you can use series.agg and pass set as the aggregate:
file1 = df['INSTANCE_ID'].agg(set)

It will get you the values in the column as a set. You can do the same for all the dataframes
SAMPLE RUN
>>> df =  pd.DataFrame({'INSTANCE_ID': [random.randint(0,3) for _ in range(5)]})
>>> df
   INSTANCE_ID
0            0
1            1
2            0
3            1
4            0

>>> df['INSTANCE_ID'].agg(set)
{0, 1}

Since you want the union of all the sets, better option will be just to concatenate all the dataframe column values, then create the set:
result = pd.concat([df1['INSTANCE_ID'], df2['INSTANCE_ID'], ...., dfn['INSTANCE_ID']]).agg(set)


text:
Q: How do I mock externally injected libraries that use import (ES6 typescript) exported in a node module for unit testing In my main app, I am bringing in the node package "ibm_db" using:
import * as ibmdb from "ibm_db";
In my unit tests I want to be able to override this, then I:
import * as ibmdb from "ibm_db";
in my unit test and then:
beforeEach(() => {
   ibmdb.open = jasmine.createSpy("open");
});

I get error:
Cannot assign to 'open' because it is a readOnly property.

I need to know with typescript (being compiled into js using tsc, then tested using jasmine command), the right way to mock these functions so I can tell if there being called, I don't want the calls to actually fire.

A: For ES6 imports use:
import * as name from "library_name"

and in the unit tests use:
const name = require("library_name");

Requires will let you overwrite parts of the library where imports will not


text:
Q: If I use a class more than once in an application, will it be compiled just once into the exe? I'm evaluating the many possibilities for a trial protection system and came up with the following question:
If I use my "trial check" class more than once (scattered several times over the application), will it be compiled just once into the exe?
The reason why I'm asking is that if it's only compiled once into the exe, then patching this single class will invalidate all places where it is used.
If it's compiled just once, are there any viable alternatives to prevent this?
Thanks!
EDIT: I'm actually not trying to roll my own protection system, I'm looking at several existing solutions like OnGuard, mxProtector and TRegWare. It was while looking at the various solutions source-code, that I came up with this question.

A: If you use the inline keyword for functions and methods where possible, the executable code will be "multi-plicated".  There are some limitations to the use of inlining, though (see the linked doc).
I agree with Ain and Marco that spending effort on protection schemes may be more bother than benefit, and that it makes more sense to use existing solutions than to roll your own.

A: Yes. The standard workaround is to put the code in an .inc and include that in multiple units.
But that makes less sense in a security setting. Since if sb has learned to search for a pattern, he can simply repeat the search to find the other occurrences, making it a minor nuisance at best.
This is one of the reasons why DIY protection is often a waste of time, and I agree fully with Ain. (both the onguard thing, and the fact that if functionality IS in the exe, it will be unlocked sooner or later, giving sufficient motivation)

A: Just for the principle: There is actually a possibility to have the "same" class compiled multiple times. If you declare the class with a generic type and later have several instances with different instance types, the class code is compiled for each type. The generic class don't even have to make use of the generic type. If you spread the generic instances over different units, the code will be separated, too.
type
  TDummy<T> = class
  public
    procedure Dummy1;
  end;

procedure TDummy<T>.Dummy1;
begin
  ...
end;

var
  FDummy1: TDummy<Integer>;
  FDummy2: TDummy<Byte>;
  FDummy3: TDummy<TButton>;
  FDummy4: TDummy<TLabel>;

A: Yes, even if you create several instances of the class in different places there is only one copy of the methods (implementation), so if hacker patches the class all instances will be patched.
Do you really want to roll your own protection system? It ain't easy to come up with good system and there are several ready to use solutions around, if youre on budget then perhaps TurboPower OnGuard (which is open source now) will do.
BTW the general wisdom is that if they want to crack your app they will do it, no matter what, so one shouldn't waste too much resources on protection schemes. The only foolproof way is to exclude some of the (key) functionality from trial version, ie
{$IFDEF trial_version}
  ShowMessage('Sorry, this function is not available in trial version');
{$ELSE}
  // do the thing
{$END}

but of course, if full version gets into wild then it will be cracked...


text:
Q: Set a converter for ModelMapper only once I have the follwoing code for converting an object of class User to its DTO of type GetUserDto:
public GetUserDto convertToDto(User user) {
    Converter<User, GetUserDto> converter = context -> {
        User source = context.getSource();
        GetUserDto target = new GetUserDto();
        target.setDescription(source.getDescription());
        target.setId(source.getId());
        target.setName(source.getName());
        target.setImageId(source.getImageId());
        return target;
    };
    modelMapper.createTypeMap(User.class, GetUserDto.class).setConverter(converter);
    return modelMapper.map(user, GetUserDto.class);
}

It works fine for the first time, but the subsequent calls to convertToDto throws:
java.lang.IllegalStateException: A TypeMap already exists for class com.boot.cut_costs.model.User and class com.boot.cut_costs.dto.user.ExtendedGetUserDto
I found some other posts regarding this, one suggested to null check TypeMap for modelMapper and not to create it again if it wasn't null. This is not a good solution as if you have thousands of calls to this method it adds unnecessary overhead to it.
Any good solution ?

A:
I found some other posts regarding this, one suggested to null check
  TypeMap for modelMapper and not to create it again if it wasn't null.
  This is not a good solution as if you have thousands of calls to this
  method it adds unnecessary overhead to it.

If you look into the code of org.modelmapper.ModelMapper.getTypeMap()
and  org.modelmapper.ModelMapper.createTypeMap(), you will see that
creating a TypeMap that is a higher overhead as simply invoking a method to retrieve a TypeMap.
Returning the object from a map if it exists is straight:
  public <S, D> TypeMap<S, D> getTypeMap(Class<S> sourceType, Class<D> destinationType) {
    Assert.notNull(sourceType, "sourceType");
    Assert.notNull(destinationType, "destinationType");
    return config.typeMapStore.<S, D>get(sourceType, destinationType, null);
  }

While the adding performs much more things.
It creates a proxy type, does a synchronized task and does some checks before  creating a TypeMap instance and at last it puts it in the map :
  private <S, D> TypeMap<S, D> createTypeMapInternal(S source, Class<S> sourceType,
      Class<D> destinationType, String typeMapName, Configuration configuration) {
    if (source != null)
      sourceType = Types.<S>deProxy(source.getClass());
    Assert.state(config.typeMapStore.get(sourceType, destinationType, typeMapName) == null,
        String.format("A TypeMap already exists for %s and %s", sourceType, destinationType));
    return config.typeMapStore.create(source, sourceType, destinationType, typeMapName,
        (InheritingConfiguration) configuration, engine);
  }

that invokes also :
  public <S, D> TypeMap<S, D> create(S source, Class<S> sourceType, Class<D> destinationType,
      String typeMapName, InheritingConfiguration configuration, MappingEngineImpl engine) {
    synchronized (lock) {
      TypeMapImpl<S, D> typeMap = new TypeMapImpl<S, D>(sourceType, destinationType, typeMapName,
          configuration, engine);
      if (configuration.isImplicitMappingEnabled()
          && ImplicitMappingBuilder.isMatchable(typeMap.getSourceType())
          && ImplicitMappingBuilder.isMatchable(typeMap.getDestinationType()))
        new ImplicitMappingBuilder<S, D>(source, typeMap, config.typeMapStore,
            config.converterStore).build();
      typeMaps.put(TypePair.of(sourceType, destinationType, typeMapName), typeMap);
      return typeMap;
    }
  }

So do the check if a more efficient solution  :
if (modelMapper.getTypeMap(User.class,GetUserDto.class) == null){
    modelMapper.createTypeMap(User.class, GetUserDto.class).setConverter(converter);
}
return modelMapper.map(user, GetUserDto.class);

Now, if you want really avoid unnecessary processing, you could create the TypeMap and set all converter associated to in a specific class once.
public void initTypeMaps(){
        modelMapper.createTypeMap(User.class, GetUserDto.class).setConverter(converterUserAndUserDto);
        modelMapper.createTypeMap(Other.class, GetOtherDto.class).setConverter(converterOtherAndOtherDto);
 ...
}

At last, if you have thousands of calls to this method in a short time and  you want to reduce to the maximum the overhead, don't use ModelMapper and a converter but do the mapping between two classes at hand.


text:
Q: mysql_query inject - replace returned field im trying to learn and understand mysql inject, i have created demo case.
SELECT ret_variable FROM data WHERE name = '".$name."' AND age = ".$age;

then if(ret_variable == 2){something} but query originally returns 1 and i need to force it to output 2
How to modify $age variable to set custom output field for ret_variable(only in response) ?
I have tried few ways with OR but didn't wroked.

A: I see no practical application other than learning. I assume since you know the code , you have permission to test this out. So let's give it a go!
You can only return a 2 for the ret_variable when there is a row in the database with a value of 2 as the ret_variable and you know the name value of that row. You can for instance enter that name and the following to bypass the correct value for the age.

age AND ret_value = 2

That would create the following query:
SELECT ret_variable FROM data WHERE name = 'John' AND age = age AND ret_value = 2;

The principle of mysql injection is this sort of manipulation of the query. But you can not force a value which is returned unless there is a row in the database with this value for ret_variable and you can somehow select this row.
When you don't know the name (or there is no record of your known name with a ret_variable of 2) it is not possible.
Since the AND operator has precedence over the OR operator you cannot manipulate the query to give a 2 as ret_variable. This is because the name = '?' part will always fail.


text:
Q: How can i fix json search I have an android program that reads the existing text and converts it into text
The program searches the text via the json link
ِAt first the calling function
new JsonTask().execute("https://api.myjson.com/bins/gx1ck");

My code of Class JsonTask
But my problem is that the program stops working at the beginning of the search link


text:
Q: Embedded Form Mailchimp não redireciona para página de destino Segue o código do Form que estou trabalhando, o problema é o seguinte, utilizando ele como está, não está redirecionando para o link do e-book que eu gostaria, tentei colocar > onClick=this.form.action='https://www.pmextech.com/wp-content/uploads/2018/04/e-BOOK_GUIA_BASICO_INOVACAO_.pdf';this.form.submit(); < no botão, mas ai não consigo fazer com que só direcione após os campos serem preenchidos.

<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

<form action="https://pmextech.us18.list-manage.com/subscribe/post?u=7f006475c853db80b170d5153&id=24f0ae88ad" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Informe os seus dados para acessar o guia de Criatividade e Inovação

_______________________________

*indicates required

 Email*

 <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

 Nome*

 <input type="text" value="" name="FNAME" class="required" id="mce-FNAME">

 Telefone
 <input type="text" name="PHONE" class="" value="" id="mce-PHONE">

 Cargo*

 <input type="text" value="" name="CARGO" class="required" id="mce-CARGO">

 Sobre seu Projeto*

 <select name="SPROJETO" class="required" id="mce-SPROJETO" style='text-transform:lowercase'>
 <option value="none" selected hidden disabled>Selecione uma opção</option>
 <option value="Sou inventor / Desenvolvedor">Sou inventor / Desenvolvedor</option>
    <option value="Estou Empreendendo">Estou Empreendendo</option>
    <option value="A Inovação / Projeto será realizada dentro da minha empresa">A Inovação / Projeto será realizada dentro da minha empresa</option>

 </select>

 Qual a fase de seu projeto
 <select name="group[2925]" class="REQ_CSS" id="mce-GQPROJETO" style='text-transform:lowercase'>
 <option value="none" selected hidden disabled>Selecione uma opção</option>
 <option value="1">Tenho a ideia mas não sei como avançar</option>
<option value="2">Tenho o projeto estruturado mas não sei se minha inovação será viável</option>
<option value="4">Tenho o projeto estruturado mas não sei como executar</option>

 </select>

<input type="text" name="b_7f006475c853db80b170d5153_24f0ae88ad" tabindex="-1" value="">

<input type="submit" value="Receber Material" name="subscribe" id="receber_e-book" class="button" style="padding: 30px 20px; line-height:1px;" >

        Não fazemos spam.
  Seus dados estão seguros.

</form>

A: Encontrei uma maneira de resolver meu problema utilizando jQuery


text:
Q: how to obtain general solution for Laplace PDE in spherical coordinates using DSolve? Can DSolve given a general solution to Laplace PDE in spherical coordinates without given boundary conditions? I tried, but not able to get a solution. Do I need some other assumptions? This is what I tried
ClearAll[u,r]
pde= D[(r^2 D[u[r,θ,ϕ],r]),r]+ 1/Sin[θ] D[(Sin[θ]  D[u[r,θ,ϕ],θ]),θ]+
        1/Sin[θ]^2 D[u[r,θ,ϕ],{ϕ,2}]==0

sol=DSolve[pde,u[r,θ,ϕ],{r,θ,ϕ},Assumptions->{0<= θ<= Pi}]

With and without assumptions, it returns unevaluated. Used the definition of Laplacian from https://en.wikipedia.org/wiki/Laplace_operator

I did not need the 1/r^2 in the above example I wrote, since RHS is zero.
And just in case, there might be different definitions for this operator, I let Mathematica give the operator
ClearAll[u,r,θ,ϕ]
lap=Laplacian[f[r,θ,ϕ],{r,θ,ϕ},"Spherical"];
DSolve[lap==0,f[r,θ,ϕ],{r,θ,ϕ}]

Adding assumptions such as Assumptions->{r>0,0<= θ<= Pi} did not help.
Maple gives the following solution, without boundary condition specified.
PDE := Diff(r^2*diff(F(r,theta,phi),r),r)
+ 1/sin(theta)*Diff(sin(theta)*diff(F(r,theta,phi),theta),theta)
+ 1/sin(theta)^2*diff(F(r,theta,phi),phi,phi) = 0;

ans := pdsolve(PDE):
pdetest(ans,PDE);

(* 0 *) (*i.e. verified*)

sol:=PDEtools:-build(ans) assuming 0 <= theta, theta <= Pi:
sol:=simplify(sol,size);

Is it possible to obtain the above solution (assuming it is correct) using Mathematica's DSolve? Is there an example anywhere that solves Laplace PDE in spherical coordinates using DSolve I could look at? I googled and did find anything so far.
I am using 11.3 on windows 7.

A:
Can DSolve given a general solution to Laplace PDE in spherical
coordinates without given boundary conditions?

In Version 12.3 it can
ClearAll[u, r, θ, ϕ, f]
lap = Laplacian[f[r, θ, ϕ], {r, θ, ϕ}, "Spherical"];
DSolve[lap == 0, f[r, θ, ϕ], {r, θ, ϕ}, Assumptions -> {0 <= θ <= Pi}]

Gives


text:
Q: All business logic in stored procedure My project's using N-Tier architecture and common framework as:

*

*Presentation Layer: JSF 2.0 + Primefaces

*Business Logic Layer: Spring for management transaction

*Data access Layer: Spring Data + JPA

*Spring security for security and user management

*Spring integration for integration with external system

For almost all business logic, we're using Java code and reside in Business Layer, but my client requires that we move all business logic into the database and use stored procedures (database is Oracle).
I tried to convince my client and give some disadvantage and advantage if move business logic to database as below:
Disadvantages:

*

*Stored procedure is not programming language, it should use for manage data and not for write logic code

*Stored procedure make logic become complex. One logic maybe difficult to implement with stored procedure but very easy if use programming language as Java

*Difficult to debug or unit test

*Diffucult to handler exception

*Difficult for maintenance, update

*Stored procedure can't integrate with external system

*Take much effort to write CRUD for each table when ORM Framework's really good for CRUD

*Difficult to make clear design document

*More bugs

*Slow down development process

*Database server will become overloaded

*Database should use for handling data not for process logic

*Difficult and expensive to upgrade or add new database server, but easier and cheaper with application server

*Break N-Tier architecture and ORM framework

When using stored procedures:

*

*Performance: Process batch data or long time process with database (as report...)

My client also said: they want use store to fix project without redeploy. And I explain that when change business logic maybe we need change input, output and user interface, then we still have to redeploy, and we should bring business logic out of database. But they rejected.

A: If you using ORACLE DB then never try to underestimate the power of Stored Procedure.I worked in many very heavy application and yes which had JAVA layer but processing huge data with business logic was not possible at all in JAVA layer. So we moved most of the data processing logic in stored procedure and it rocks like anything.
For an example you want to show a logical report at front end and you are sure it will be only few Kbs and you know to generate this report you calling DB and fetching records in MB and doing business logic in JAVA, will it be fast??
I am java guy but still supports stored procedure as you can do a lot even you can write useful business logic in it.
As well stored procedure works in DB layer so its always fast compare to JAVA.as per my opinion the complex DB related queries which you have in JAVA business layer just move to stored procedure and retrieve the required output by using java and display the same at frontend.
In Addition I want to put best Pros of stored procedure.

*

*Its Faster because multiple SQL queries and such can be performed in one "round trip" to the database

*Trivial to make use of the stored procedures from multiple applications

*One place is easier to maintain than multiple

*Databases are fast and optimized and can be scaled well.

*The same procedures can be called from mutiple, different frameworks and languages.

*The logic is decoupled from the implementation in particular applications.

*Rework may be reduced for changing applications when the database stays the same.


text:
Q: Strange permission issue for SpamAssassin in LXC container My mailserver set-up is quite old, but did its job for many years. With the last major update from Debian 9 to 10, SpamAssassin stopped working. Today I took the time to search for reasons, and I do not understand what I found.
Running spamassassin --lint as debian-spamd  fails to load all modules with lines like:
Nov  4 13:00:50.573 [5216] warn: plugin: failed to parse plugin (from @INC): Can't locate Mail/SpamAssassin/Plugin/AskDNS.pm: lib/Mail/SpamAssassin/Plugin/AskDNS.pm: Keine Berechtigung at (eval 115) line 1.

Using strace I see:
stat("lib/Mail/SpamAssassin/Plugin/AskDNS.pmc", 0x7ffc01e14860) = -1 EACCES (Keine Berechtigung)
stat("lib/Mail/SpamAssassin/Plugin/AskDNS.pm", 0x7ffc01e14860) = -1 EACCES (Keine Berechtigung)

Running spamassassin --lint as root reports no issues except a missing Bayes database, which is to be expected. But the actual issue is that it does neither use any of the files denied for debian-spamd, which simply do not exist:
stat("lib/Mail/SpamAssassin/Plugin/AskDNS.pmc", 0x7ffdafdc1aa0) = -1 ENOENT (Datei oder Verzeichnis nicht gefunden)
stat("lib/Mail/SpamAssassin/Plugin/AskDNS.pm", 0x7ffdafdc1aa0) = -1 ENOENT (Datei oder Verzeichnis nicht gefunden)
stat("/usr/share/perl5/Mail/SpamAssassin/Plugin/AskDNS.pmc", 0x7ffdafdc1aa0) = -1 ENOENT (Datei oder Verzeichnis nicht gefunden)
stat("/usr/share/perl5/Mail/SpamAssassin/Plugin/AskDNS.pm", {st_mode=S_IFREG|0644, st_size=29190, ...}) = 0
openat(AT_FDCWD, "/usr/share/perl5/Mail/SpamAssassin/Plugin/AskDNS.pm", O_RDONLY|O_CLOEXEC) = 4

namei -om /usr/share/perl5/Mail/SpamAssassin/Plugin/AskDNS.pm reveals that this file is accessible by anyone. And in fact, I can e.g. cat it as debian-spamd. But it is apparently not even tried.
On the other hand I did find / -type d -name 'lib' -exec namei -om {} \; and there is neither any ´lib´ folder, which would be inaccessible, nor does find / -type d | grep lib/Mail list any matching folders, which might be denied.
The server is a LXC container running current Debian 10.6 as does the host.
Any ideas to further pin down the issue are appreciated.

A: The issue seems to be that SpamAssassin first checks ./lib/... before it checks standard paths. I did my test from /root, which is inaccessible for other users, i.e. . failed already with EPERM. Apparently, this causes SpamAssassin to give up immediately.
Starting SpamAssassin from the home directory of debian-spamd succeeded.


text:
Q: SplitMenuButton in FXML I'd like to create a SplitMenuButton using FXML. I can find documentation on how to do it in java, but not in the xml file. How can I do this?
Additionally, if there's a good source for FXML documentation, please point me to it.

A: You can do
<SplitMenuButton fx:id="smButton" text="Text">
    <items>
        <MenuItem text="Choice 1" onAction="#action1" />
        <MenuItem text="Choice 2" onAction="#action2" />
    </items>
</SplitMenuButton>

There is an "Introduction to FXML" document that describes how FXML works in general. However, for use cases such as this, you really just need the Javadocs. Elements beginning with a capital correspond to class names, i.e. they are an instruction to instantiate that class. Attributes correspond to properties, so
<SplitMenuButton fx:id="smButton" text="Text"/>

essentially means
SplitMenuButton smButton = new SplitMenuButton();
smButton.setText("Text");

The only tricky thing here is the <items> element, which is a Read Only List Property as described in the afore-mentioned Introduction to FXML.


text:
Q: Not reloading website on form submission, yet send an email via php? I have a contact form on my website. And I sent its contents to me via email via php:
<?php
if(isset($_POST['submit'])){
    $to = "myemail@gmail.com";
    $from = $_POST['email'];
    $first_name = $_POST['firstname'];
    $subject = "Form submission";

    $message = $first_name . " wrote the following:" . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    mail($to,$subject,$message,$headers);
    }
?>

This works. However, I don't want my page to be reloaded etc., so before I had the php code in there, I just coded the UI with javascript: It clears the fields, and it shows a notification saying Thanks for your message, etc. :
$("#contact_form").submit(function(e) {
    e.preventDefault();

    iziToast.success({
        title: 'Thank you',
        message: 'Thanks for your message',
    });

    this.reset(); //clear form input fields
  });

HOWEVER:
The two don't seem to work together. I am doing prevent.default because I want to avoid a page reload, and I am doing a this.reset in order to reset the form and empty everything out again.
How could I make these two work together? That is, i want to send the email via php, but I also want to javascript to display the notification, clear the input fields, and not reload the page.
PS: The php is in the same file as the HTML. The javascript file is referenced via a script tag. Just in case that's important.


text:
Q: Свайп в jquery, библиотека jquery.mobile В общем дело такое, мне надо отследить свайп, я решил использовать jquery.mobile. Вот пример кода:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>

<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

Вот код
viewport.swipe({
swipeLeft:function(event, direction, distance, duration, fingerCount) {
   alert('swipe left');
},
swipeRight:function(event, direction, distance, duration, fingerCount) {
   alert('swipe right');
}
});

В viewportсодержится
$('.indexReviewsVie_fu');

И сама ошибка
jquery.min.js:3 Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function
at HTMLDivElement.dispatch (jquery.min.js:3)
at HTMLDivElement.r.handle (jquery.min.js:3)
at Object.trigger (jquery.min.js:3)
at e (jquery.mobile-1.4.5.js:3847)
at Object.handleSwipe (jquery.mobile-1.4.5.js:4022)
at HTMLDocument.e.move (jquery.mobile-1.4.5.js:4069)
at HTMLDocument.dispatch (jquery.min.js:3)
at HTMLDocument.r.handle (jquery.min.js:3)

И по итогу выдаёт ошибку, можете подсказать из-за чего ошибка?

A: Ошибка заключалась в том, что я сделал через переменную, в переменной была уже не строка а сам объект.


text:
Q: Get error Uncaught TypeError: Cannot call method 'getProxy' of undefined? i have problem with web app i building useing extjs.
i have this code:
The Code
ok the error i get is this:
Uncaught TypeError: Cannot call method 'getProxy' of undefined
this the stacktrace:
Uncaught TypeError: Cannot call method 'getProxy' of undefined
Ext.define.constructorext-all-debug.js:44348
Base.callParentext-all-debug.js:2891
Ext.define.constructorext-all-debug.js:44877
Ext.Class.newClassext-all-debug.js:3188
(anonymous function)
Ext.ClassManager.instantiateext-all-debug.js:3948
Ext.ClassManager.instantiateByAliasext-all-debug.js:3898
(anonymous function)ext-all-debug.js:1555
Ext.define.statics.createext-all-debug.js:44241
Ext.define.lookupext-all-debug.js:26969
Ext.define.bindStoreext-all-debug.js:70975
Ext.define.initComponentext-all-debug.js:70756
Ext.define.constructorext-all-debug.js:15614
Base.callParentext-all-debug.js:2891
Ext.define.constructorext-all-debug.js:27103
Ext.Class.newClassext-all-debug.js:3188
(anonymous function)
Ext.ClassManager.instantiateext-all-debug.js:3948
(anonymous function)ext-all-debug.js:1555
(anonymous function)PageList.js:35

A: storge is a function, it needs to be executed to return a store.
Try store: storge(),

A: In your snippet, if you delete the entirety of line 1, 17 and 18, then change line 34 to:
store : store,
your code will work fine.


text:
Q: sorting table in place using stl sort I have a HUGE table (about 50Gb) in (i,j,k) format (from a sparse matrix) stored as
uint32_t * idx1, * idx2;
float * vals;
uint32_t tablesize;

and I'd like to sort it in place with a given comparison function that's a function of idx1 and idx2. Can this be done using std::sort?
Specifically, each nonzero entry (i,j) with value v in the sparse matrix is stored by placing i in idx1, j in idx2, and v in the corresponding entry in vals. I'd like to then sort these entries according to (i1, j1, v1) <= (i2, j2, v2) if
(i1 < i2) || (i1==i2 && j1 <= j2)

The examples I've been able to scrounge up of using std::sort on nonstandard datatypes assume that each item being compared is a single instance of a class; here each item is represented by three values in different arrays.

A: It is unfortunately quite difficult to convince std::sort, or any of the standard library, to work with striped data. It is designed to assume that data can be copied via a single =, moved via one move or swapped via one swap.
Your best bet is to use boost::iterator_facade to write a custom iterator class which wraps the data, and hides the striped data format from std::sort. I've wanted to do something similar in the past but my workspace does not allow us to use boost. EDIT: when your facade is dereferenced, it will probably need to create some sort of proxy object that can be assigned/moved/swapped and will do the right thing to each of the stripe arrays. It's not trivial.
The next best bet is to make an array of ints from zero to N, each one representing an index into your striped data array. Write a custom functor to std::sort which sorts this array to match your criteria. It's obviously far from ideal when you have such a large data set.

A: If you have to keep using your existing data structure, which is essentially a std::tuple of three std::vectors, using boost::zip_iterator would seem to be the way to go. A zip_iterator treats three iterators (two to indices and one to a value) as a single tuple, and you can use a custom comparison function object to sort your data in-place. Alas, boost::zip_iterator can't be used with std::sort, as explained in this Q&A, because it can't be written into.
This means that you would have to write your own zip_iterator class that can be used with std::sort. Note that it is not a trivial exercise, see this Q&A and/or this paper.
It is a lot easier to sort a std::vector of a std::tuple. My attempt below uses a std::tuple of two indices and a value, and stores those entries into a std::vector. For the sorting, I use a C++14 generic lambda that forwards the two indices into a smaller tuple and compares those lexicographically (i.e. first on row-index, then on column-index) using the library operator< of std::tuple.
#include <algorithm>
#include <iostream>
#include <tuple>
#include <vector>

using index = uint32_t;
using value = float;
using sparse_entry = std::tuple<index, index, value>;
using sparse_matrix = std::vector<sparse_entry>;

int main()
{
    // sparse 3x3 matrix
    auto m = sparse_matrix {
        std::make_tuple( 1, 1, -2.2),
        std::make_tuple( 1, 0, 42  ),
        std::make_tuple( 0, 2,  3.4),
        std::make_tuple( 0, 1,  1.7)
    };

    // sort by row-index, then column-index
    std::sort(begin(m), end(m), [](auto const& L, auto const& R) {
        return
            std::forward_as_tuple(std::get<0>(L), std::get<1>(L)) <
            std::forward_as_tuple(std::get<0>(R), std::get<1>(R))
        ;
    });

    for (auto const& elem : m)
        std::cout << "{ " << std::get<0>(elem) << ", " << std::get<1>(elem) << ", " << std::get<2>(elem) << "}, \n";
}

Live Example.
If your application can use this transformed data layout (and there maybe cache-performance reasons why it can't), then the above code will do the sorting as you want it.
NOTE: as @Casey mentions, you can also use std::tie instead of std::forward_as_tuple, but that can bite you when you change sparse_entry into a full-fledged user-defined class with getters returning by-value.


text:
Q: Array as private member of class I am trying to create a class which has a private member that is an array. I do not know the size of the array and will not until the value is passed into the constructor. What is the best way to go about defining the class constructor as well as the definition in the .h file to allow for this variable size of the array?

A: Using a std::vector is the best option.
If you ever need to pass it to a function that expects a pointer to an array (like the GSL often does), you can still pass &vec[0]...

A: If you want a "real" C-style array, you have to add a pointer private member to your class, and allocate dynamically the memory for it in the constructor (with new). Obviously you must not forget to free it in the destructor.
class YourClass
{
  private:
    int * array;
    size_t size;

    // Private copy constructor operator to block copying of the object, see later
    // C++03:
    YourClass(const YourClass &); // no definition
    // C++11:
    YourClass(const YourClass&) = delete;

  public:
    YourClass(size_t Size) : array(new int[Size]), size(Size)
    {
        // do extra init stuff here
    };

    ~YourClass()
    {
        delete [] array;
    }
};

To make this work easier, you may consider to use a smart pointer (for example, a boost::scoped_array in C++03, or plain std::unique_ptr in C++11), that you may initialize using the initializer list before the constructor or simply in the constructor.
class YourClass
{
  private:
    boost::scoped_array<int> array; // or in C++11 std::unique_ptr<int[]> array;
    size_t size;
  public:
    YourClass(size_t Size) : array(new int[Size]), size(Size)
    {
        // do extra init stuff here
    }

    // No need for a destructor, the scoped_array does the magic
};

Both these solutions produce noncopyable objects (you didn't specify if they had to be copyable and their copy semantic); if the class don't have to be copied (which happens most of times), these both are ok, and the compiler will generate an error if you try to copy/assign one class to another, in the first case because the default copy constructor has been overloaded with a private one (or plain deleted in C++11), in the second case because boost::scoped_array and std::unique_ptr are noncopyable.
If, instead, you want to have copyable objects, then you must decide if you want to create a copy that shares the array (so, just a pointer copy) or if you want to create a new, separate array for the other object.
In the first case, you must be very careful before freeing the allocated memory, since other objects may be using it; a reference-counter is the most common solution. You can be helped in this by boost::shared_array (or std::shared_ptr in C++11), which does all the tracking work automatically for you.
If instead you want to do a "deep copy", you'll have to allocate the new memory and copy all the objects of the source array to the target array. This is not completely trivial to do correctly, and is usually accomplished through the "copy and swap idiom".
Still, the simplest solution is to use a std::vector as a private member: it would handle all the allocation/deallocation stuff by itself, constructing/destroying itself correctly when the object of your class is constructed/destructed. Moreover, it implements the deep-copy semantic out of the box. If you need to make your callers access the vector read-only, then, you could write a getter that returns a const_iterator or a const reference to the vector object.


text:
Q: Unable to use Office.context.mailbox.item.addFileAttachmentAsync when signed into a shared mailbox on Outlook on the Web To reproduce the same, you will require an add-in which works in the MessageCompose interface. I was unable to install Script Lab in the Shared Mailbox environment; if you face the same problem, you may need to create a simple add-in that uses the Office.context.mailbox.item.addFileAttachmentAsync API.
Steps to reproduce:

*

*Login to Outlook on the Web.

*Click on your profile on the top-right corner of the screen.

*Choose Open another mailbox

*Type and select a shared mailbox which you have access to.

*Once you are loaded into the shared mailbox, compose a new message and open the add-in.

*The attachment upload progress bar gets stuck. As a result, even the callback provided to addFileAttachmentAsync will never be called.

A: "Open another Mailbox" add-in scenarios are not fully supported on Outlook Web and the support is currently in our backlog. The feature is currently in preview for Win32. ( link to document: https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/delegate-access?tabs=windows#shared-mailboxes-preview). We will update our documentation to reflect this state. Thanks for your patience


text:
Q: General error during conversion: Unsupported class file major version 62-IONIC emulate Android General error during conversion: Unsupported class file major version 62
java.lang.IllegalArgumentException: Unsupported class file major version 62
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Version JDK 18.0.2
Version Gradle: 7.5.1

A: JDK 18 is unsupported. You will need to downgrade, you can try version 16, 17 or 11.


text:
Q: Measure theory; proving an infinite partition exists from a sigma-algebra. I'm really new to measure theory and have trouble with interpreting a question.
We have a space $A$ with $\mathbb{A}$ a $\sigma$-algebra with infinitely many elements. Now I need to show an infinite partition exists.
Of course we first need to define what an infinite partition is. It is a countable infinite sequence of non-empty and disjoint sets which union is $A.$
So we know there are infinite elements in the $\sigma$-algebra. I would argue we need to rearrange the elements of $\mathbb{A}$ to make them countable and then introduce a 'left-overs' subset that contains all elements that are outside of our countable division. I know this is probably very wrong but I would appreciate any steering in the right direction...

A: Your idea is correct.
If the space is finite then the sigma algebra if finite and your partition problem is easy enough.
If the sigma algebra  is infinite then it is uncountable.
Let $\Bbb{A}=\{A_i:i \in I\}$
Then you can take a countable sequence $\{A_n:n\in \Bbb{N}\} \subset \Bbb{A}$
Now define $B_n=A_n \setminus \bigcup_{k=1}^{n-1}A_k$ and $B_1=A_1$
Note that these sets are disjoint and belong to $\Bbb{A}$(since $\Bbb{A}$ is closed under set differences and unions)
Finally take $\Bbb{A}_n:=\{B_n\}$ and $\Bbb{A}_0=\Bbb{A} \setminus \{B_n: n \in \Bbb{N}\}$
So you  have a partition $\{ \Bbb{A}_n:n=0,1,2...\}$ of the sigma algebra.

A: Using @bof's argument from a related question:
Let $\mathcal B$ be an infinite $\sigma$-algebra on a set $\Omega$. Partition $\Omega$ into two disjoint nonempty sets $A_1,B_1\in\mathcal B$. At least one of $\mathcal B\cap\mathcal P(A_1)$ and $\mathcal B\cap\mathcal P(B_1)$ is infinite; otherwise, if $|\mathcal B\cap\mathcal P(A_1)|=m\lt\aleph_0$ and $|\mathcal B\cap\mathcal P(B_1)|=n\lt\aleph_0$, we would have $|\mathcal B|=mn\lt\aleph_0$. We may assume that $\mathcal B\cap\mathcal P(B_1)$ is infinite. Next, partition $B_1$ into two disjoint nonempty sets $A_2,B_2\in\mathcal B$ so that $\mathcal B\cap\mathcal P(B_2)$ is infinite. Continuing in this way, we get an infinite sequence $A_1,A_2,A_3,\dots$ of pairwise disjoint nonempty elements of $\mathcal B$. (Every infinite Boolean algebra contains such a sequence; we haven't used the $\sigma$ yet.) Since $\mathcal B$ is a $\sigma$-algebra, the union of each subsequence belongs to $\mathcal B$, showing that $|\mathcal B|\ge2^{\aleph_0}$.


text:
Q: dlopen /proc/self/auxv: Permission denied RHEL6 I have an executable that  need to load an .so file.
Everything is working on Ubunto and RHEL5 but on RHEL6 I'm getting this error on dlopen:
/proc/self/auxv: Permission denied
If I'm running the executable with root it is working without this error message.
void *handle = dlopen(file_path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
Red Hat Enterprise Linux Server release 6.7 (Santiago)
kernel: 2.6.32-573.26.1.el6.x86_64
gcc (GCC) 4.4.7
ldd (GNU libc) 2.12
What does this file stands for and is there any way to resolve this?