text:
Q: Finding Determinant of NxN matrix I tried to solve a matrix question for hours, I made lots of calculations for finding determinant of it. However, I could not solve the problem. Here is that matrix;
$$A =\begin{bmatrix}x+a_1 & a_2 & a_3 & ... & a_n\\ a_1& x+a_2 &a_3&...&a_n\\ a_1& a_2 &x+a_3&...&a_n\\...& ... &...&...&...\\a_1& a_2 &a_3&...&x+a_n\end{bmatrix}$$
Find $|A|$ = ?


text:
Q: Bash script command line argument to upper case If I can do this in my bash shell:
$ STRING="A String"
$ echo ${STRING^^}
A STRING

How can I change my command line argument to upper case?
I tried:
GUARD=${1^^}

This line produces Bad substitution error for that line.

A: Let's start with this test script:
$ cat script.sh
GUARD=${1^^}
echo $GUARD

This works:
$ bash script.sh abc
ABC

This does not work:
$ sh script.sh abc
script.sh: 1: script.sh: Bad substitution

This is because, on my system, like most debian-like systems, the default shell, /bin/sh, is not bash.  To get bash features, one needs to explicitly invoke bash.
The default shell on debian-like systems is dash.  It was chosen not because of features but because of speed.  It does not support ^^. To see what it supports, read man dash.

A: With tr command:
Script:
#!/bin/bash

echo $@ | tr '[a-z]' '[A-Z]'

Check:
$ bash myscript.sh abc 123 abc
ABC 123 ABC

A: typeset -u VAR=VALUE works too

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python writing to port with arduino I'm trying to send a python script to my Arduino Nano, but it only works when in IDLE. I'm only starting to learn python so my understanding is limited on how to execute scripts.
Here's the python script
import serial
ser1 = serial.Serial('COM5', 9600)
ser1.write('s'.encode())

I already have pyscript installed. When I type in the above code one line at a time in IDLE, CMD or PowerShell it works flawlessly. when I try to make it a file in pycharm I get the error "No module named 'serial'"
Here's my Arduino code
void setup() {
   pinMode(LED_BUILTIN, OUTPUT);
   digitalWrite(LED_BUILTIN,
   Serial.begin(9600);
}

void loop() {
  if(Serial.available() > 0)
  {
    if(Serial.read() == 's')
    {
      digitalWrite(LED_BUILTIN,HIGH);
      delay(2000);
    }
  }
  else
  {
    digitalWrite(LED_BUILTIN, LOW);
  }
}

A: PyCharm like to have you configure a separate virtual enviroment for each python project. You can either redo "pip install pyserial --user" inside PyCharm or fiddle with the project settings.


text:
Q: Is it possible to use google-play-services 7.0 with eclipse? Latest changes to Google Play Services for Android results in > 65k methods problem in Eclipse. It is possible to include parts of Google Play Services but in Android Studio Only. What about Eclipse? I saw and tried to use some split scripts that split google-play-services.jar but this is not official Google recomendation.
Do they want us to finally migrate to Android Studio?


text:
Q: What scenario causes a php foreach loop to terminate? I have an array with the values of nearly 11000 values.
array=(1,2,3..............................., 11000)

when i try iterate the array using foreach, it terminates execution on 9749th item and remaining not executed. Kindly let me know what is the issue to stop the execution inside the loop?.
Note:
I didn't use any break or die inside the loop.

A: Firstly, you should enable displaying PHP errors because PHP will tell you what the issue is. The 3 most common reasons for your execution halting are:

*

*max_execution_time - This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser (default: 30 seconds).

*memory_limit - This sets the maximum amount of memory in bytes that a script is allowed to allocate. If you hit this limit, execution will halt.

*xdebug.max_nesting_level - If you have xdebug enabled, and are using recursive functions, execution will halt when you hit the nested functions limit (default: 256).


text:
Q: Find the index by current sort order of an array in ruby If there is an array
array A = ["a","b","c","d"] #Index is [0,1,2,3]

And it's sorted to.
array A = ["d","c","b","a"]

I need an array that returns me the updated index based on the sorted order
[3,2,1,0]

I'm trying to find a solution to this ruby
UPDATE to the question
If a is sorted to
array A = ["d","b","c","a"] #not a pure reverse

Then the returned index array should be
[3,1,2,0]

A: You need to create a mapping table that preserves the original order, then use that order to un-map the re-ordered version:
orig = %w[ a b c d ]
orig_order = orig.each_with_index.to_h

revised = %w[ d c b a ]

revised.map { |e| orig_order[e] }
# => [3, 2, 1, 0]

So long as your elements are unique this will be able to track any shift in order.

A: You can use the map and index methods.
arr = ["a","b","c","d"]

sort_arr = ["d","c","b","a"]

sort_arr.map{|s| arr.index(s)}
# => [3, 2, 1, 0]

A: Here is one way to do this:
original_array = ["a","b","c","d"]
jumbled_array = original_array.shuffle

jumbled_array.map {|i| original_array.index(i)}
#=> [1, 3, 0, 2]

Note:

*

*In this sample, output will change for every run as we are using shuffle to demonstrate the solution.

*The solution will work only as long as array has no duplicate values.

If you do wish to solution to work with arrays with duplicate values, then, one possibility is to look at object_id of array members while figuring out the index.
jumbled_array.map {|i| original_array.map(&:object_id).index(i.object_id)}

This solution will work as long as jumbled_array contains element from original_array and no elements were recreated using dup or something that results in change in object_id values


text:
Q: Updating row values with numpy array I have the following function:
def invert_blackwhite(x):

for riga in x:

    for idx_colonna in range(len(riga)):

        if (riga[idx_colonna] == 0):

            riga[idx_colonna] = 1

        else:

            riga[idx_colonna] = 0
    print(riga)
return x

If I call this function like this:
x = np.array([[0,1,0],[1,1,1],[0,1,0],[0,1,0]])
invert_blackwhite(x)

The output would be this:
[1 0 1]
[0 0 0]
[1 0 1]
[1 0 1]

In the function, I am iterating over rows and changing the content of the rows based on a condition. I am not really sure why the code is also updating the variable "x" since I am just calling the riga object. To summarize, I can not understand why if I update the riga object that automatically updates also x. I hope that my doubt is clear


text:
Q: How to defer index of for loop till all promises are reslved I have a for loop inside which I have $q.all which makes calls to services. The calls are pushed to array as follow. The output that I am getting is values being assigned only to the last device.

 for(device in self.listOfDevices){
                    var count =0;
                    var individualFixletCountPromise = [];
                    self.listOfDevices[device].count=0;
                    console.log("device level one"+device);
                    for(site in self.listOfDevices[device].sites){
                        individualFixletCountPromise.push(Bigfix.getPerSiteFixletCount(self.listOfDevices[device].sites[site].answer[0]));
                    }
                    $q.all(individualFixletCountPromise).then(function(response){
                        for(res in response){
                            var temp = response[res].data.data.replace(/type="integer"/g, '');
                            temp = temp.replace(/ >/g, '>');
                            var jsonObject = ngXml2json.parser(temp);
                            console.log(jsonObject.besapi.query.result.answer);
                            count=count+jsonObject.besapi.query.result.answer;
                        }
                        console.log("device level two"+device);
                        self.listOfDevices[device].count=count;
                        console.log("assigned to self.ListOf devices:"+self.listOfDevices[device].count);
                    })

                }


text:
Q: Nil data is passed from tableview detail disclosure with prepareForSegue I need to pass a string with prepareForSegue from a tableView disclosure link. Here is the prepareForSegue code I use. This is the code I found in several cases when other users needed to do the same thing, but in my case it doesn't work. Problem is with indexPathForSelectedRow() that is nil:
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "alertsDetail" {

        let detailAlertViewController = segue.destinationViewController as DetailAlertViewController
        println(alertTable.indexPathForSelectedRow()) // NIL
        if let indexPath = alertTable.indexPathForSelectedRow() {
            let entryToPass = unpublishedPhotosObjectId[indexPath.row]
            detailAlertViewController.entryId = entryToPass
        }
    }
}

I named the tableView "alertTable" and not self because the tableview is not a view controller, just a view.
In case needed, here is tableview code:
 @IBOutlet weak var alertTable: UITableView!
  /////////////TableView - START
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return unpublishedPhotos.count
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 170
}

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    tableView.separatorColor = UIColor.clearColor()
    let cell = tableView.dequeueReusableCellWithIdentifier("adminAlertsCell") as? adminAlertsCell

    var data = unpublishedPhotos[indexPath.row].getData()
    let image = UIImage(data: data)
    cell!.myImageInCell.image = image
    return cell

}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    // Add access to cell
    let cell = tableView.cellForRowAtIndexPath(indexPath) as? adminAlertsCell

        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        println(cell!.banSwitch.on)

    }
}

/////////////TableView - END

A: You should make the segue from the controller instead of directly from the detail disclosure button. Implement the method,
tableView:accessoryButtonTappedForRowWithIndexPath: and call performSegueWithIdentifier:sender: from inside that method. Pass the in-depth as the sender argument so you have access to that in prepareForSegue,
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    let indexPath = sender as NSIndexPath
    if segue.identifier == "alertsDetail" {

        let detailAlertViewController = segue.destinationViewController as DetailAlertViewController
        let entryToPass = unpublishedPhotosObjectId[indexPath.row]
        detailAlertViewController.entryId = entryToPass
    }
}

A: Your issue is stated in the comments to your question, and there are several solutions.  Perhaps the quickest since you only have one section,  is to assign the indexPath.row to the tag of the cell.  Then in your prepare for segue, the sender will be your cell.  You can get the value out of it.  So in your cellForRow method before your return your cell:
cell!.tag = indexPath.row

Then in your prepareForSegue:
let cell = sender as? adminAlertsCell
println(cell!.tag)

Here I am just printing it, but you can use it to pass the row.


text:
Q: How to determine the character set of a Firebird database I've read the following thread and I was able to make a conversion script (based on C#) that converts all my charset=NONE databases to charset=UTF8 and most of it works great (I still have a few special cases where characters are converted to weird symbols, but that's marginal).
My issue is that I have lots of backup database files (*.fbk) for which I don't know for sure if this is UTF8 or NONE. In the ideal world, my code would handle the conversion once the database is restored from file depending on the fbk file's format, so I only convert when necessary and after restore.
Is this at all possible? Or is there a way to define charset when restoring the database (either via gback of via ADO.NET provider)?

A: In general, a Firebird database does not have a single character set. Each and every column can have its own character set. So the only thing you can do is try and use heuristics.

*

*Use the database default character set. To be clear, the database default character set is only used when creating a new column when no explicit character set is specified. It is entirely possible for a database to have default character set UTF8, while all columns have character set WIN1251!
You can find the database default character set with the following query:
select RDB$CHARACTER_SET_NAME from RDB$DATABASE

NOTE: If the result is NULL, then that means the default character set is NONE.

*Count the different character sets of CHAR, VARCHAR and BLOB SUB_TYPE TEXT columns to see which occurs most:
select
  coalesce(cs.RDB$CHARACTER_SET_NAME, 'NONE') as CHARSET,
  count(*) as CHARSET_COUNT
from RDB$RELATIONS r
inner join RDB$RELATION_FIELDS rf
  on rf.RDB$RELATION_NAME = r.RDB$RELATION_NAME
inner join RDB$FIELDS f
  on f.RDB$FIELD_NAME = rf.RDB$FIELD_SOURCE
left join RDB$CHARACTER_SETS cs
  on cs.RDB$CHARACTER_SET_ID = f.RDB$CHARACTER_SET_ID
where coalesce(r.RDB$SYSTEM_FLAG, 0) = 0
and r.RDB$VIEW_BLR is null
and (f.RDB$FIELD_TYPE in (14, 37) or f.RDB$FIELD_TYPE = 261 and f.RDB$FIELD_SUB_TYPE = 1)
group by 1
order by 2 desc

As an aside, be aware that if clients have used connection character set NONE, then it is entirely possible that the actual character set of contents of a column may not match the defined character set of that column.


text: Q: How do i import .tmx assets from Tiled into Monogame using XTiled How do i import .tmx assets frome Tiled into Monogame using XTiled? I am trying to get the Content pipeline to use a custom processor for the .tmx files provided by XTiled. I looked at Monogame's documentation on their content pipeline but i don't think that the section has been updated in a while.


text:
Q: Ограничить вводимые данные. SQL Пытался уже решить этот вопрос, но никак не получаеться решить проблему.
Вопрос был у меня такой:
Хочу задать условия («Чтобы нельзя было указывать в таблица "Расписание" одновременно перебывание в разных аудитория на одном уроке (моего учителя в табл нагрузка»)
Я, создал уникальный индекс и у меня получаеться решить проблему дублирования вводимых данных. Одноко, когда я задаю,что мой учитель преподает к примеру ( на 1 уроке,в аудитории 111 и в понедельник) , а потом снова задаю ( на 1 уроке,в аудитории 112 и в понедельник) Тут Допускаеться ввод данных в обоих случаях, а у меня как бы учитель не может вести одновременно в разных аудиториях свой предмет... Как можно ограничить это ?

A: Сложные проверки можно делать в хранимых  процедурах. Просто делайте запрос в хранимой процедуре есть ли пересечения по аудитории,  времени,  учителям.  Если есть - возвращайтесь ексепшен, код или текст ошибки - в зависимости от того как удобнее


text:
Q: Points of Intersection for $\sec^2(x) = 4\cos^2(x)$ I need the Points of Intersection for $\sec^2(x) = 4\cos^2(x)$. I know that $\sec^2(x)/4$ is equal to $1/4\cos^2(x)$ and that $4\cos^2(x)$ is equal to $4[1 + \cos(2x)]/2$. I am trying to eventually factor out the cosines with a $t=$. That would allow me (I'm thinking) to then use the quadratic formula via "completing the square" and then plug t back into the equation. I'm stuck and any help would be appreciated!
Thanks

A: Actually, just let $u=\cos^2(x)$ so that we have
$$\frac1u=4u$$
which occurs at $u=\pm1/2$.  Realizing that $u\ge0$, we simply have $u=1/2$.
Can you take it from here?
Bonus hint: It's a special right triangle.

A: $$\frac{1}{cos^2(x)}=4cos^2(x)$$
$$1 = 4cos^4(x)$$
$$\frac{1}{4} = (cos^2(x))^2$$
$$±\frac{1}{2}=cos^2(x)$$
Just take the positive value of this, because its not possible to further root the negative root.
$$cos(x) = ±\sqrt{\frac{1}{2}}$$
Good day.


text:
Q: Computing how many distinct digital products are below $10^n$ Given a number $n$, its digital product is the product of its digit. So the digital product of $15$ is $1\times 5=5$, and the digital product of $760$ is $0$, etc.
I recently saw a nice video on Numberphile where they discussed persistence, namely how many iterations of digital product do you need in order to reach a single digit (e.g. $75\to 35\to 15\to 5$ has persistence of $3$).
Playing a bit with the idea, it occurred to me that an efficient way of writing a code to check for this would include having a dictionary. This is because if I know that $35$ requires two steps, I don't need to iterate three steps from $75$, I can just notice that it's one more than $35$.
Of course, you don't want to store this information for every number, because then you'd be wasting a lot of memory when testing this with very large numbers.
So my first quest was to wonder what would be the maximal size of a dictionary we need. Well, If we test all the way to $10^n$, the largest digital product would be $10^n-1$, which is $9^n$. This is great, since $\frac{9^n}{10^n}\to 0$, so you're being relatively efficient. But in the real world, this is still a massive size of memory allocation on a personal computer.
The next step, therefore, is to ask, how many distinct values can we get from a digital product?
I tested this up to $10^8$, and the answer may surprise you. It turns out that there are only $2026$ values that you get from digital products below $10^8$. About half of those are actually $0$, since the longer the number the harder it is to avoid $0$, but we are still talking about $43000000$ numbers whose product is non-zero.
Here is a basic state of the results:
$$\begin{array}{c|l}
\text{Below} & \text{Distinct digital products}\\\hline
10^0 & 1\\
10^1 & 10\\
10^2 & 37\\
10^3 & 101\\
10^4 & 226\\
10^5 & 442\\
10^6 & 785\\
10^7 & 1297\\
10^8 & 2026
\end{array}$$
This is quite a slow growth rate, and again, it makes sense. The longer your numbers are, the more likely they are to have $0$ inside, and if not a $0$, then at least $1$ which can then be omitted and not change the value of the product.
Obviously, the first question is whether or not there are only finitely many digital products. Of course not. $10^n-1$ has a digital product of $9^{n-1}$, which would provide us with infinitely many distinct values.

Is there a relatively straightforward to recursively compute how many distinct digital products are there below $10^n$? Or at least a reasonable upper bound?

(Note that there is some intuition as to why this can be done recursively. For example, if $k$ has small digits ($1$ to $4$, then $10k+2$ has the same digital product as $2k$, so if $2$ appears in a number of length $n$, and all the digits are small, it does not add a new value. There are a lot of cases to test, and , which is why I hope someone more talented than me when it comes to finite combinatorics can see through them.)

A: This is basically OEIS sequence A154323 representing central coefficients of number triangle A113582. The OEIS page gives the following formula:

$$a_n = \frac{n^4 + 2n^3 + n^2 + 4}4=1+\binom{n+1}{2}^2$$

The is actually the formula provided by Empty2, just with a different starting index ($n$ instead of $n+1$).
Even without a closed form solution, you can count the number of distinct products with just a few lines of code. I have decided to choose Java because since Java8 it's very easy to employ all existing CPU cores in stream-based computations which shortens computation times significantly.
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Application {
    public static final int N = 100;

    static Set<BigInteger> getUniqueProducts(int generation) {
        Set<BigInteger> result = new HashSet<>();
        if(generation == 0) {
            result.add(BigInteger.ONE);
        }
        else {
            Set<BigInteger> products = getUniqueProducts(generation - 1);
            result = products.stream().parallel().flatMap(
                    product -> IntStream
                        .range(0, 10)
                        .mapToObj(String::valueOf)
                        .map(s -> new BigInteger(s))
                        .map(num -> num.multiply(product))
            ).collect(Collectors.toSet());
        }
        System.out.println("10^{" + generation + "} & " + result.size() + "\\\\");
        return result;
    }

    public static void main(String[] args) {
        System.out.println("\\begin{array}{c|l}");
        System.out.println("\\text{Below} & \\text{Distinct digital products}\\\\\\hline");
        getUniqueProducts(N);
        System.out.println("\\end{array}");
    }
}

Here are the results up to $n=80$:
$$\begin{array}{c|l}
\text{Below} & \text{Distinct digital products}\\\hline
10^{0} & 1\\
10^{1} & 10\\
10^{2} & 37\\
10^{3} & 101\\
10^{4} & 226\\
10^{5} & 442\\
10^{6} & 785\\
10^{7} & 1297\\
10^{8} & 2026\\
10^{9} & 3026\\
10^{10} & 4357\\
10^{11} & 6085\\
10^{12} & 8282\\
10^{13} & 11026\\
10^{14} & 14401\\
10^{15} & 18497\\
10^{16} & 23410\\
10^{17} & 29242\\
10^{18} & 36101\\
10^{19} & 44101\\
10^{20} & 53362\\
10^{21} & 64010\\
10^{22} & 76177\\
10^{23} & 90001\\
10^{24} & 105626\\
10^{25} & 123202\\
10^{26} & 142885\\
10^{27} & 164837\\
10^{28} & 189226\\
10^{29} & 216226\\
10^{30} & 246017\\
10^{31} & 278785\\
10^{32} & 314722\\
10^{33} & 354026\\
10^{34} & 396901\\
10^{35} & 443557\\
10^{36} & 494210\\
10^{37} & 549082\\
10^{38} & 608401\\
10^{39} & 672401\\
10^{40} & 741322\\
10^{41} & 815410\\
10^{42} & 894917\\
10^{43} & 980101\\
10^{44} & 1071226\\
10^{45} & 1168562\\
10^{46} & 1272385\\
10^{47} & 1382977\\
10^{48} & 1500626\\
10^{49} & 1625626\\
10^{50} & 1758277\\
10^{51} & 1898885\\
10^{52} & 2047762\\
10^{53} & 2205226\\
10^{54} & 2371601\\
10^{55} & 2547217\\
10^{56} & 2732410\\
10^{57} & 2927522\\
10^{58} & 3132901\\
10^{59} & 3348901\\
10^{60} & 3575882\\
10^{61} & 3814210\\
10^{62} & 4064257\\
10^{63} & 4326401\\
10^{64} & 4601026\\
10^{65} & 4888522\\
10^{66} & 5189285\\
10^{67} & 5503717\\
10^{68} & 5832226\\
10^{69} & 6175226\\
10^{70} & 6533137\\
10^{71} & 6906385\\
10^{72} & 7295402\\
10^{73} & 7700626\\
10^{74} & 8122501\\
10^{75} & 8561477\\
10^{76} & 9018010\\
10^{77} & 9492562\\
10^{78} & 9985601\\
10^{79} & 10497601\\
10^{80} & 11029042\\
\end{array}$$
...and a chart:

...also using logarithmic scaling:

A: The product is $2^a3^b5^c7^d$ where $a/3+b/2+c+d\le n$, with an adjustment for 6s, so what is the volume of a four-dimensional simplex?
Except for $n=0$, the numbers in @Oldboy's answer follow $$1+{n+2\choose 2}^2$$
I don't know why.

A: A loose upperbound (and possible approach for exact count?)
Lets say a number $< 10^n$ has $n$ digits, including possibly leading $0$s.  If any digit is $0$ then the DP is $0$.  Ignoring those, we have $n$ digits which are $1-9$.  The ordering of the digits don't matter, so we're really just interested in the multiset of digits (multiset because the number of times e.g. $5$ appears matters).
To count such multisets, we can throw $n$ balls into nine boxes.  The number of ways, by stars and bars method, is ${n+8 \choose 8}$.  So this is an upperbound.  E.g. for $n=4,5,6,7,8$ the upperbounds are $495, 1287, 3003,6435,12870$ respectively.
The reason this is not tight is because e.g. $2\times 3 = 1 \times 6$, etc.  If there is a way to account for all such equivalences then we'd have a formula for the exact count.


text:
Q: Circular dependency with Dependency walker due to forwarded functions? When checking a dll, dependency walker reports Error: A circular dependency was detected.
The documentation says

Detects circular dependency errors. This is a very rare error, but can occur with forwarded functions.

What does forwarded function mean in this context?
PS: The alternative Dependencies doesn't seem to give an error output.


text:
Q: different nav bar for different pages in react For my application, I have a nav bar which has different functionality for different pages. ie. 1 page has a map and the search will search for addresses and another page has a list and the search bar will filter the list. There are also different buttons on each page too.
What's the best way to implement something like this in react? I've thought about creating a different search bar component for every page and just rendering a different one for each route but I don't have enough experience in React to go ahead with that decision. Is there a more efficient alternative?

A: Create a new Navbar component named something like NavBarController. While calling the navbar controller component pass in the "Type" as prop. Type should be a state and should change depending on the page the user is on.
<NavBarController type={1}></NavBarController>

You would just create a few different NavBars and then NavBarController will handle whichever navbar you want to display out of your multiple navbars.
Your NavBarController will return something like this:
return (props.type===1?<NavBarHome/>
:props.type===2?<NavBarMap/>
:props.type===3?<NavBarList/>)


text:
Q: SoapUI testing with Android and byte arrays I am trying to do some SOAP testing and I can't find out how to pass a byte[].
I use SoapUI for the tests. I pasted the WSDL and I was able to see the available requests in the list.
The WSDL link is: http://54.243.147.122:8080/ASEServer/services/Android?wsdl

The android application that has been developed does various tasks that need connection to the Soap server. One of them is the log in procedure. An object is being created and then it gets transformed into a byte array (byte[]) that is being sent to the server.
I cannot really understand how to pass a byte array in the 'envelope' in order to get a response.
I need help desperately, so any suggestion are welcomed.

A: In order to send a byte array SOAP U you must first decode your byte array as BASE64. Than simply paste your base64 encoded string to the soap envelope. There are some online converter to convert hexadecimal strings to base64 string. But if you want to do it your self here is an example.
public class App {

private static final String TR_MESSAGE = "Hello!, öÖ çÇ ğĞ üÜ ıİ şŞ";

public static void main(String[] args) {
    byte[] trUTF16 = TR_MESSAGE.getBytes(Charset.forName("UTF-16"));
    String result = new BigInteger(1, trUTF16).toString(16).toUpperCase();
    System.out.println("Result: " + result);

    String rebuild = new String(trUTF16, Charset.forName("UTF-16"));
    System.out.println("Rebuild: " + rebuild);

    System.out.println("BASE64: " + new String(org.apache.commons.codec.binary.Base64.encodeBase64(trUTF16)));
}}


text:
Q: capistrano deploy_symlink fails This is my first deployment. I did a cap deploy:setup which worked fine.
Then, when I try to execute cap deploy:update I run into error messages. Something along the lines of
rm: cannot remove `/var/www/app_name/current': Is a directory

Here is my capfile and directory permissions.
http://pastie.org/1189919
In general, what is the best practice as far as deployment user and permissions are concerned? Should I use root or create a different user. If a different user what exact permissions does it need?
Thanks

A: Did you create the directories within /var/www/app_name, or were they created by capistrano?
Regardless, the issue you have is that /var/www/app_name/current should not be a directory - it should be a symlink to the current release within /var/www/app_name/releases/. The failure is caused when capistrano has finished creating the new release folder within /var/www/app_name/releases/, and is trying to symlink /var/www/app_name/current to it.
You might be able to fix your issues by renaming /var/www/app_name/current (so you have a backup if things go wrong), and creating a symlink from /var/www/app_name/current to the most recent release within /var/www/app_name/releases/, and then doing a cap deploy. (Delete your backup of current if this works).
As far as best practice goes whatever you do, do not use root. Instead, set up a user (or use an existing user) that has only permissions to the required directories (didn't read your scripts closely, but probably just /var/www/app_name.

A: To deploy a new release you should invoke cap deploy or cap deploy:migrations, not cap deploy:update.

A: I also have had such errors.  A totally normal task of updating source code and restarting the server always seems to have problems at various points of the simple script.
Sometimes it complains that a hash value at github doesn't match some expected value, sometimes it won't update a directory because it already exists, but mostly with it wanting to create things that exist.
Is there no way to force Capistrano and thus the shell commands to just DO IT ?  I would at least appreciate it asking me what it should do should it encounter this type of error instead of just failing and rolling back.  Especially when it's a simple file operation.
I end up having to delete things manually on the server so that the Capistrano script will run without failing.  This is obviously not the way forward.


text:
Q: The GTKMM isn't working with my CLion install (Windows 10). CMakeLists.txt - Could not find PkgConfig I have what's probably a beginner's question for you: I'm trying to get Gtk to run with CLion in a windows environment.
I've run through this: https://wiki.gnome.org/Projects/gtkmm/MSWindows a few times (to confirm I did it correctly), added a few things to my system PATH settings, as well as attempting to manipulate the CMakeLists.txt files in CLion and it doesn't seem to be able to find the library. I've been on stackoverflow posing my problem in different ways and trying a few solutions, but no luck as of yet.
Is using gtk headers in CLion possible?
I get the following error attempting to run a program with gtkmm headers: fatal error: gtkmm/application.h: No such file or directory
My CMakeLists.txt looks like the below:
cmake_minimum_required(VERSION 3.14)
project(Kmeans)

set(CMAKE_CXX_STANDARD 14)
set(PKG_CONFIG_EXECUTABLE "/usr/bin/pkg-config")
add_executable(Kmeans main.cpp)

find_package(PkgConfig)
pkg_check_modules(GTKMM gtkmm-3.0)

include_directories(${GTKMM_INCLUDE_DIRS})
link_directories(${GTKMM_LIBRARY_DIRS})

set(SOURCE_FILES main.cpp)
target_link_libraries(${CMAKE_PROJECT_NAME} ${GTKMM_LIBRARIES})

What generally occurs is that I receive an error reading as follows:

CMake Error at C:/Program Files/JetBrains/CLion
  2018.3.4/bin/cmake/win/share/cmake-3.14/Modules/FindPkgConfig.cmake:510 (message):
-- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE)    pkg-config tool not found

Edit to reflect comments and continued efforts:
I have run pacman -S pkg-config as the wiki page suggests, and I can see a pkg-config in my C:\msys64\var\lib\pacman\local folder. Within the toolchain in CLion, the environment is MinGW and CMake is designated to autodetect the compiler, which is in MINGW\mingw32\bin\g++.exe.
I've also confirmed that my executable is in usr/bin/pkg-config using Cygwin terminal and added set(PKG_CONFIG_EXECUTABLE "/usr/bin/pkg-config") to my cmake file after going through the answer provided by @Isuru Walpola here: https://askubuntu.com/questions/717302/cmake-could-not-find-pkgconfig-missing-pkg-config-executable
Unfortunately, I still receive the same error message.
Additionally, I tried a complete reinstall of CLion, as well as switching my environment to Cygwin, using its setup file to install any library/doc/development tools referencing gtk3 (and below) that I could find. CLion also pre-populates the names for this when I begin typing #include <> statements, however they're not found as soon as the full include statement is written.
I no longer receive the pkg-config not found error, but rather than CLion cannot locate these particular GTK libraries and header files.
My CMakeLists.txt now looks like the below. There is some duplication and unusable lines that I've included for testing as I don't really understand some of the commands.
cmake_minimum_required(VERSION 3.14)
project(ProjectKMeans)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(CMAKE_CXX_STANDARD 14)
set(PKG_CONFIG_PATH /usr/lib/pkgconfig)
set(PKG_CONFIG_EXECUTABLE /usr/bin/pkg-config.exe)
add_executable(ProjectKMeans main.cpp)

find_package(PkgConfig)

pkg_check_modules(GTKMM gtkmm-3.0)
pkg_check_modules(gtk gtkmm-3.0)
PKG_CHECK_MODULES(GTK GTK)
ADD_DEFINITIONS(${GTKMM_CFLAGS_OTHER})
include_directories(${GTKMM_INCLUDE_DIRS})
link_directories(${GTKMM_LIBRARY_DIRS})

set(SOURCE_FILES main.cpp)
target_link_libraries(${CMAKE_PROJECT_NAME} ${GTKMM_LIBRARIES})

I think the problem is that GTKMM is not recognized. I don't understand this naming convention. None of the libraries have this name that I'm aware of. What am I missing?


text:
Q: R error on condition filtering using a float value I'm having an issue where a boolean flag doesn't seem to be correctly evaluating a numeric data type in R. But everything is only to 1 decimal place, so I'm confused how it could be unstable?
Here's some code to reproduce:
library(ggplot2)

myfunction <- function(x,y){
  t1 = (x-1)^2
  t2 = (y-1)^2
  t1 + t2
}

input_vector_full <- seq(-1,1,0.1)
x_full <- input_vector_full
y_full <- input_vector_full
result_vector_full <- c()
x_vect <- c()
y_vect <- c()
for(i in x_full){
  for(j in y_full){
    temp <- myfunction(i,j)
    x_vect <- c(x_vect, i)
    y_vect <- c(y_vect,j)
    result_vector_full <- c(result_vector_full, temp)
  }
}
df <- data.frame("x" = x_vect, "y" = y_vect, "z" = result_vector_full)

#Creating a new dataframe here for clarity

df2 <- df
df2$sum_absolute <- abs(df2$x) + abs(df2$y)
df2$bool_flag <- df2$sum_absolute <= 1

If you run the above and go to where df2$x == 0.1 and df2$y == 0.9 then you'll see a value of 1.0 in the "sum_absolute" column.  But a false in the "bool_flag" column
Version info:
> version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          4
minor          0.3
year           2020
month          10
day            10
svn rev        79318
language       R
version.string R version 4.0.3 (2020-10-10)
nickname       Bunny-Wunnies Freak Out

Structure
'data.frame':   441 obs. of  5 variables:
 $ x           : num  -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ...
 $ y           : num  -1 -0.9 -0.8 -0.7 -0.6 -0.5 -0.4 -0.3 -0.2 -0.1 ...
 $ z           : num  8 7.61 7.24 6.89 6.56 6.25 5.96 5.69 5.44 5.21 ...
 $ sum_absolute: num  2 1.9 1.8 1.7 1.6 1.5 1.4 1.3 1.2 1.1 ...
 $ bool_flag   : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...

Even this doesn't work
library(dplyr)
df2 %>% filter(x == 0.1)

[1] x            y            z            sum_absolute bool_flag
<0 rows> (or 0-length row.names)


text:
Q: Add or Remove Row in Input Table I am trying to design a webpage with an input table where users can add or remove rows as they want. UI like this-

And here is my html code:

Welcome to dynamic input table with row adding option

  <form method="" action="">

                No
                Name
                Pnone Number
                Email
                Remove?

            1
            <input type="text" name="name-1">
            <input type="text" name="phone-1">
            <input type="text" name="Email-1">

            2
            <input type="text" name="name-2">
            <input type="text" name="phone-2">
            <input type="text" name="Email-2">

            3
            <input type="text" name="name-3">
            <input type="text" name="phone-3">
            <input type="text" name="Email-3">

            4
            <input type="text" name="name-4">
            <input type="text" name="phone-4">
            <input type="text" name="Email-4">

        <button class="btn btn-warning">Add row</button>
        <button class="btn btn-danger ml-3">Delete last row</button>
        <button type="Submit" class="btn btn-primary ml-auto">Submit</button>

  </form>

    <title></title>

    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Now my problem is how can I implement the functionality of Add row button, Delete last row button, and the remove. And all should work in such a way that I can use this for data sending in the backend also. I will prefer to use Django and MongoDB to implement my backend. Now please help me with the best way to implement this, If it can implement with js in the frontend with js it will be very helpful for me, or if it should implement in the backend with the dynamic approach it will work also.

A: Your question has many parts and should be broken down into several questions.  Here's a simple way to delete rows.  You'll want to make button to click on instead of what I've done here.  And, you'll also want to make an ajax call to delete the actual data in your database.  This is just front-end code to visually show the user a row has been deleted.

$('.my-5 tr').click(function(){
    $(this).remove();
    return false;
});

Welcome to dynamic input table with row adding option

  <form method="" action="">

                No
                Name
                Pnone Number
                Email
                Remove?

            1
            <input type="text" name="name-1">
            <input type="text" name="phone-1">
            <input type="text" name="Email-1">

            2
            <input type="text" name="name-2">
            <input type="text" name="phone-2">
            <input type="text" name="Email-2">

            3
            <input type="text" name="name-3">
            <input type="text" name="phone-3">
            <input type="text" name="Email-3">

            4
            <input type="text" name="name-4">
            <input type="text" name="phone-4">
            <input type="text" name="Email-4">

        <button class="btn btn-warning">Add row</button>
        <button class="btn btn-danger ml-3">Delete last row</button>
        <button type="Submit" class="btn btn-primary ml-auto">Submit</button>

  </form>

A: You can create your table dynamically, if you want to do operations like add and delete.
You can check out the demo here:
https://jsbin.com/pewexibole/edit?html,js,console,output
HTML:

    <title></title>

    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Welcome to dynamic input table with row adding option

                No
                Name
                Pnone Number
                Email
                Remove?

        <button class="btn btn-warning" onclick="addRow()">Add row</button>
        <button class="btn btn-danger ml-3">Delete last row</button>
        <button type="Submit" class="btn btn-primary ml-auto">Submit</button>

JS:
let i = 0;

function rowTemplate(i) {
  return `

      ${i}
      <input type="text" name="name-${i}">
      <input type="text" name="phone-${i}">
      <input type="text" name="Email-${i}">

`
}

for (i = 0; i < 4; i ++) {
  $('tbody').append(rowTemplate(i));
}

function removeRow(i) {
  $("tbody").find(`tr[data-index='${i}']`).remove();
}

function addRow() {
  $('tbody').append(rowTemplate(i));
  i++;
}


text:
Q: In the osx/ios world, what is a library and what is a framework? I am learning development on osx and ios. So far, coding is ok. The most difficult is to handle all the files, all the configuration issues (of xcode), and so on. I thought hearing from a guru about libraries/frameworks would help me a lot!
I would like to know more about libraries and frameworks.

*

*What is a library, what is a framework (and what's the difference between them)?

*Where can I find a list of all the frameworks (of all the libraries?)? Or: what are the most important frameworks?

*What can I do without any framework?

A: Your first question is very well explained here
Finding the right frameworks is half the fun coding with iOS. There are loads of lists out there and depending on what you are doing there are some frameworks that are very used. One great tool to look at is cocoapods. It can not only help you find frameworks but it also manages the frameworks in your project. Adding cocoapods in my opinion should be the fist thing you do in a project. All that said, my three favorite frameworks are:

*

*AFNetworking: To handle network requests.

*RestKit: To transform JSON into objects. (it's actually built on top of AFNetworking)

*SVProgressHUD: A lightweight progress HUD

Finally you can do everything without ever using an external framework but why would you recode something that is already coded and battle tested.

A: In addition to my comment, some informations about frameworks on OS X/iOS.
A framework on OS X/iOS is a bundle used to distribute shared resources, including library code, resource files, header files… For more details see
A list of system frameworks available on OS X here


text:
Q: PyQt4 QtCore.QObject.connect(..., QtCore.SIGNAL(...), ...) into PyQt5 I'm translating Yasin's Model View Video Tutorial Series from PyQt4 into PyQt5. I'm stuck with the following code block:
QtCore.QObject.connect(self.uiFilter, QtCore.SIGNAL("textChanged(QString)"), self._proxyModel.setFilterRegExp)

How shall it be written in PyQt5?
The complete code:
http://www.yasinuludag.com/PyQt/Tutorial05/Tutorial05_ProxyModel.py
The tutorial:
http://discourse.techart.online/t/pyqt-model-view-video-tutorial-series-part-01/1401
Thanks


text:
Q: How to show that: $(-1)^nn+2+\sum_{k=1}^{n}\frac{(-1)^k}{k+1}(2)_{k+1}S_{n}^{k+1}H_{k+1}=B_{n-1}$ I was observing these formulas concerning $B_n$, Bernoulli numbers
I was able  to conjecture this formula:
$$(-1)^nn+2+\sum_{k=1}^{n}\frac{(-1)^k}{k+1}(2)_{k+1}S_{n}^{k+1}H_{k+1}=B_{n-1}\tag1$$
Where $H_n$ is Harmonic numbers
$S_{n}^m$ is Stirling number of second kind
$(n)_m$ is Pochhammer
Does anyone know how to prove it?

A: We seek to prove the identity
$$B_n = \sum_{k=0}^{n} \frac{(-1)^k H_{k+1} (k+2)!
{n+1\brace k+1}}{k+1} + (-1)^{n+1} (n+1).$$
The sum is
$$(n+1)! [z^{n+1}]
\sum_{k=0}^{n} (-1)^k \left(1+\frac{1}{k+1}\right)
H_{k+1} (\exp(z)-1)^{k+1}.$$
With $\exp(z)-1 = z+\cdots$ the coefficient extractor enforces the upper
limit of the sum  and we get
$$(n+1)! [z^{n+1}]
\sum_{k\ge 0} (-1)^k \left(1+\frac{1}{k+1}\right)
(\exp(z)-1)^{k+1} [w^{k+1}] \frac{1}{1-w} \log\frac{1}{1-w}.$$
Note that the term in $w$ starts at $w$. We get for the first piece
$$-(n+1)! [z^{n+1}] \exp(-z) \log \exp(-z)
\\ = (n+1)! [z^n] \exp(-z) = (-1)^n (n+1).$$
We see that this cancels the extra term from the initial closed form.
Therefore the remaining term must give the Bernoulli numbers:
$$(n+1)! [z^{n+1}]
\sum_{k\ge 0} (-1)^k \frac{1}{k+1}
(\exp(z)-1)^{k+1} [w^{k+1}] \frac{1}{1-w} \log\frac{1}{1-w}.$$
Differentiate to get
$$n! [z^n] \exp(z)
\sum_{k\ge 0} (-1)^k
(\exp(z)-1)^{k} [w^{k+1}] \frac{1}{1-w} \log\frac{1}{1-w}
\\ = n! [z^n] \exp(z)
\sum_{k\ge 0} (-1)^k
(\exp(z)-1)^{k} [w^k] \frac{1}{w} \frac{1}{1-w} \log\frac{1}{1-w}.$$
This is
$$n! [z^n] \exp(z) \frac{1}{1-\exp(z)} \exp(-z) \log\exp(-z)
\\ = n! [z^n] \frac{z}{\exp(z)-1} = B_n$$
as claimed.


text:
Q: Cut half image in square shape Display with rounded corner in Android I have large size of images i need to cut 60% height and 60% width and display the resulted image with rounded corner.
I have applied this code
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = pixels;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);

    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

Its working fine, but i have to set approx 50 images like this. So its slow down the process, and i have to wait 4 second approx to open the Activity for this whole process.
I also tried
 android:adjustViewBounds="true"

but because of it my images are set but the problem is because large images will shrink in small area.its not looking good.
Do any one have any other way to do this job? Is it possible to do this whole job in xml so that on run time we can reduce some time in Activity opening.Please help..

A: These example are based on Image caching both memory caching as well as DiskLRU caching
Caching Bitmaps
LazyList
novoda Imageloader
Android-Universal-Image-Loader
Please read caching bitmaps thoroughly it will surely help you.

A: You need to do a lot of heavy computing on the handset. To achieve your goal I would recommend using Renderscript. A good place to start is http://developer.android.com/guide/topics/renderscript/compute.html
You could implement the heavy computing in a service to take off the load of the main thread. I'm not pretty sure how you do the display of the data but you could provide a default image for your placeholders and start updating them as the service goes doing the job. You can broadcast an intent to indicate the completion of every reduction of images.
You must also implement a cache for the "thumbnails" so you don't have to do all the computation every time the user starts your application.
Regards.


text:
Q: Rxjs with redux-observable. Repeat action I have an epic like this:
export const fetchCharacter = (id) =>
  ajax({ url: `https://swapi.co/api/people/${id}` })
    .map(response => fetchCharacterSuccess(response.body))
    .catch(error => Observable.of(fetchCharacterFailure(error.response.body)));

export const startFetchingCharacters = () => ({ type: START_FETCHING_CHARACTERS });

export const fetchUserEpic = (action$, store) =>
  action$.ofType(START_FETCHING_CHARACTERS)
    .delay(3000)
    .mergeMap(
      action => api.fetchCharacter(store.getState().nextCharacterId)
    );

Right now it only listens for START_FETCHING_CHARACTERS action and makes one request for the user.
Now I would like to keep fetching characters over and over(with delay) until some cancellation action. How can I achieve that?

A: Map an .interval() observable to the api fetch (or a .timer() depending on the exact pattern of delay you want).
Stop it with a takeUntil().
const delay = 3000
const fetchUserEpic = (action$, store) =>
  action$.ofType(START_FETCHING_CHARACTERS)
    .mergeMap( action =>
      Observable.interval(delay)
        .mergeMap(x => api.fetchCharacter(store.getState().nextCharacterId) )
        .takeUntil(action$.ofType(STOP_FETCHING_CHARACTERS))
    );

Footnote
Strictly speaking, the inner mergeMap() does not guarantee the order of character return. Since api.fetchCharacter() is asynchronous, it's possible for fetch's to return out of order (although a long delay of 3s helps avoid that).
Using concatMap() on the inner observable makes sure emits happen in strict nextCharacterId() order.
Observable.interval(delay)
  .concatMap(x => api.fetchCharacter(store.getState().nextCharacterId) )


text:
Q: Show that the integral of a bounded function satisfies certain inequality Consider the following problem:

If $f(x)$ is Riemann integrable in $[a,b]$ and $0\leq m\leq f(x)\leq M$.  $m\leq\left(\frac{1}{b-a}\int_{a}^{b}f^2(x)dx\right)^{\frac{1}{2}}\leq M$.

I have managed to show that if $f(x)\leq g(x)$ for all $x\in[a,b]$ then $$\int_{a}^{b}f(x)dx\leq\int_{a}^{b}g(x)dx.$$
Using the previous result, I have also managed to prove that if $f(x)$ is Riemann integrable and $m\leq f(x)\leq M$ for all $x\in[a,b]$ then $$m\leq\left(\frac{1}{b-a}\int_{a}^{b}f(x)dx\right)\leq M.$$
However, I haven't been able to solve the desired problem. Maybe one of the results I proved will be helpful. Any help is welcome.


text:
Q: USB Solarpanel read current with python? I'd like to connect a small solar panel (2v 50ma) to a USB cable and measure the output on python. Now I was wondering if this would work and how to make it work.
How many volts can I send into my pc? And would pyUSB work for reading this?

A: You cannot connect a voltage source directly to the USB data lines - USB is a complex digital communications system.
You would require an Analog to Digital converter (ADC) that could interface to USB, and connect your solar panel to the ADC analog input.

A: Looks like the simplest way would be this which means one of these with a shunt resistor to convert the current to a voltage drop. The bad news is that it isn't the smallest possible package for the job; the good news is that it's a single package (since the PIC does all the USB) with supporting hardware, and there's more than enough room to expand if you want to get fancy (e.g. parallel LCD output, keypad input, multiple panels, etc.).

simulate this circuit – Schematic created using CircuitLab
You can then use PySerial to talk with the PIC since it will show up as a serial port on the computer.

A: You can't do this directly.
Get a microcontroller with an ADC and an USB interface, then use the ADC to read from the solar panel and transmit this over USB (or other communication method) to the computer where Python is running.


text:
Q: Is it possible to transfer the save data of COD BO2 from a PS3 to an Xbox One S? I'm planning to buy an Xbox One S and continue playing Black Ops 2, but I don't know how to transfer my save data from my PS3 to an Xbox One S.

A: No, unfortunately saves are formatted for the console on which they are created.  Microsoft and Sony use completely different formats.  It is not possible to move a save between console lines.


text:
Q: Decrypt .Net cookie in nodejs I've created an encrypted cookie in .Net and I'm trying to decrypt it's content in nodejs. But nodejs keeps throwing the exception "TypeError: DecipherFinal fail"
In .Net I'm using the AES encryption method with the key
932D86BB1448EEAA423F38495A2290746D81C27E55D1DC264279537006D6F4CC.
My web.config file has the following row
<machineKey validationKey="A5326FFC9D3B74527AECE124D0B7BE5D85D58AFB12AAB3D76319B27EE57608A5A7BCAB5E34C7F1305ECE5AC78DB1FFEC0A9435C316884AB4C83D2008B533CFD9"
decryptionKey="932D86BB1448EEAA423F38495A2290746D81C27E55D1DC264279537006D6F4CC"
validation="SHA1" decryption="AES"  />

And the code that generates my cookie in .Net looks like this:
var ticket = new FormsAuthenticationTicket(0, "test", DateTime.Now, DateTime.Now.AddYears(1), true, "test");
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(cookieName, encryptedTicket));

The nodejs code that decrypts the cookie is
var crypto = require('crypto');
var logger = require('winston');
var deckey = "932D86BB1448EEAA423F38495A2290746D81C27E55D1DC264279537006D6F4CC";

function hex2a(hex) {
  var str = '';
  for (var i = 0; i < hex.length; i += 2)
    str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
  return str;
}

function decrypt(cookie) {
  var ivc = cookie, iv, cipherText, ivSize = 16, res;

  ivc = new Buffer(ivc, 'hex');
  iv = new Buffer(ivSize);

  cipherText = new Buffer(ivc.length - ivSize);
  ivc.copy(iv, 0, 0, ivSize);
  ivc.copy(cipherText, 0, ivSize);

  iv = new Buffer(Array(16));
  c = crypto.createDecipheriv('aes-256-cbc', hex2a(deckey), iv.toString());
  res = c.update(cipherText, 'binary');
  res += c.final('binary'); //<-- throws TypeError: DecipherFinal fail
  return res;
 }

I'm kind of lost and I would appreciate tips or ideas on what could be the issue.

A: You can see the source code of Encryp and Decrypt here with all the different possibilities (Framework20SP1, Framework20SP2, etc)
https://github.com/Microsoft/referencesource/blob/master/System.Web/Security/FormsAuthentication.cs
It took me hours to read that code, but once you got it, it's possible to write a simple code just for your specific encryption settings.

A: A key is not a String, take a look at the method fromCharCode():

The fromCharCode() method converts Unicode values into characters.

This means that any hexadecimal is converted to a textual character, while createDecipheriv() method specifies that:

key and iv must be 'binary' encoded strings or buffers.

Note that this is just one of the issues that may be present, I haven't had time to run the code (yet).

A: Your problem is probably a failure in automatic padding, turned on by default. You want to turn this off, by adding:
c.setAutoPadding(false);


text:
Q: Can't access ambari UI I want to use Hadoop. Unfortunately, I cannot access the Ambari login. How do I fix this?

A: Looks like you have some other web server running on port 8080 for Apache + Postgres
Also, the link in the VM says 1080. Can you get there? Can you access the other UI's on the HDP quickstart dashboard? If so, then Ambari isn't the issue.


text:
Q: Proper polynomial mappings One of the comments in this question says:
"Polynomial mappings in more than one variable are generally not proper
(definitely not when we work over $\mathbb{C}$) because the zero-sets are algebraic varieties and hence often unbounded (always over $\mathbb{C}$)."
(Proper map means preimages of compact sets are compacts).

(1) What happens over $\mathbb{R}$?
(2) Can one please elaborate on cases where such mappings are proper?

Thank you very much!


text:
Q: Maui group a List and show it in a ListView I have a list with this structure:
public class Words
{
    public string Word { get; set; }
    public int Word_Order { get; set; }
    public string Type { get; set; }
    public string Mainmeaning { get; set; }
    public string Language { get; set; }
    public string Meaning_Group { get; set; }
    public string Source { get; set; }
    public string Translation { get; set; }
    public string IPAUK { get; set; }
    public string IPAUS { get; set; }
    public string WordForms { get; set; }
    public string Level { get; set; }
    public string Examples { get; set; }
}

Each Words.Word can repite n times. I'd like to meke a new List grouped by the by each Word and show it in a ListView where in the main line shows (Word,IPAUK,IPAUS)  and for each word shows Type, Mainmeaning and Translation.
Thanks in advance.

A: I recommend to use CollectionView instead of ListView. They are similar with some differences: CollectionView and ListView differences. However,There is a known issue about iOS GroupHeaderTemplate :ListView GroupHeaderTemplate produces blank headers on iOS and MacCatalyst. It just render a blank headers.That's why i recommend to use CollectionView.
In your case, I suppose that you want the Words.Word to be the Group title name. So you could follow the documentation: Display grouped data in a CollectionView.
First step is to create a type that models a single item. (Is this model Words class?)
Then there should be a WordsGroup class which inherits from the List class.
public class WordsGroup : List<Words>
{
    public string Name { get; set; } // this is the group title name

    public WordsGroup(string name, List<Words> words) : base(words)
    {
        Name = name;
    }
}

Also there is an IEnumerable collection of group which ItemSources of Collection should bind to.
public List<WordsGroup> WordsGroups { get; private set; } = new List<WordsGroup>();

Then we could add group data in many ways. Actually, I don't know how you organize your data. So I cannot give you specific suggestions. Maybe you may refer to my previous post
Also in CollectionView don't forget to set IsGrouped to true.
<CollectionView ItemsSource="{Binding WordsGroups}"
      IsGrouped="True">

Hope it works for you.


text:
Q: ACF plugin categories bug in WordPress 3.9 i recently started using ACF plugin, i noticed that variables for custom fields i created and use in categories are saved in 'wp_options' tables, and although i am doing everything right they do not appear in the front-end i get a bool(false) for the field, i do not know if this has something to do with the WordPress update and the way it handles categories but i noticed that category metadata are stored in wp_postmeta table. So now i can not get the data to show on front-end everything works great in back-end.
The interesting part is if i add the field in the first post of this category (maybe i should mention this is a custom section not the default category-post one that i use as a portfolio) the call on the category will start getting data, the ones that i specify on the post.
Could anyone please help me or suggest anything else that i need to check, i am using WordPress 3.9 and ACF 4.3.6. This might even be a template related bug, but since i am not that familiar with WordPress architecture and i have yet to receive any answer from plugin developers i thought of asking here.

A: Well after some time time and the support of the guys in ACF i got through this. My template was accessing category data only by reference, a variable was created that referenced to the category id, and by that variable the category name and other data were called.
Thankfully the guys at ACF have thought through that and the only thing i had to add was the variable in the classic function the_field('field_name',$variable) and everything worked great.


text:
Q: Contentfile in nuget gets compiled causing build errors I have a nuget that has a contentfile in it. It is a json file and denoted in the nuspec file when the nuget is packed.
When installing the nuget in a regular wpf app, I get a couple build errors. It appears that Visual Studio is trying to compile the .json file. Wondering if anyone knows what may cause this. As you'll see in the nuspec snippet I have BuildAction=None in the nuspec

ContentFile.json(1,1,1,2): error CS1022: Type or namespace definition, or end-of-file expected
ContentFile.json(4,16,4,26): error CS1001: Identifier expected
ContentFile.json(4,37,4,45): error CS1001: Identifier expected

A:
When installing the nuget in a regular wpf app, I get a couple build
  errors. It appears that Visual Studio is trying to compile the .json
  file. Wondering if anyone knows what may cause this. As you'll see in
  the nuspec snippet I have BuildAction=None in the nuspec

I think the main point is that you mistakenly assume that <files include="path"> is the path of the source file ContentFile.json in your current nuget project, which is actually the path relative to the contentFiles folder inside the nuget package(xxxx.nupkg).(You can view the contentFiles folder by decompressing the xxx.nupkg file).
Besides, you can check this official document for more detailed info.
As a right guidance, you can try this step:
Solution
change to these in xxx.nuspec file
....
<metadata>
....
<contentFiles>
<files include="any/any/ContentFile.json"(the relativepath of the file under the ContentFiles folder in the xxx.nupkg) buildAction="None" copyToOutput="true" flatten="false" />
</contentFiles>
</metadata>

<files>
<file src="xxxxx/Resource/ContentFile.json(the relativePath of the file under the nuget project)" target="contentFiles/any/any" />
</files>
....

Before you install this package into another project , do not forget to clean the nuget cache.
In additon, you can check this thread for more info.
Hope it could help you.


text:
Q: Select all checkbox to be checked if all checkboxes are checked I need my selectAll checkbox to be checked if all the other checkboxes are checked.
Any idea how to do this in javascript?
My javascript code:
function selectAll(box) {
    var selectAllchk = box.checked;
    var checkboxes = document.getElementsByName('chkbox');
    if (box.checked){
        for (var i in checkboxes){
            $(":checkbox").attr("checked", true);
        }
    } else {
        $('input:checkbox:not(:disabled)').removeAttr('checked');
    }
}

function selectCheckAll(box){
    var a = ('.checkbox').length;
    if ($(':checkbox:checked').length == $('.checkbox').length) {
       //do something
    }
};

Jsp code:

  <display:table name="contratBonusForm" property="contrats" defaultsort="1"
  sort="list" defaultorder="ascending" requestURI="/gestionContratBonusActionIn.do?dispatch=searchContrat"
  uid="current" pagesize="30" class="tableauDisplayTag">
   <display:column title="ID Type" property="id" sortable="true"/>
   <display:column title="Type de contrat" property="type" sortable="true"/>
  <% %>
  <display:column title="Bonus <input type='checkbox' name='selectall' onClick='selectAll(this)'/>" align="center" >
  <% TypeContratPOJO type = (TypeContratPOJO) pageContext.getAttribute("current");
  Long Eli = 1L;
  int ok = type.getBonus().compareTo(Eli);
  (current != null &&  ok == 0) { %>
  <input type="checkbox" name="chkbox" checked="checked" onClick='selectCheckAll(this)' value="<%=indice%>"/>
  <% } else { %>
  <input type="checkbox" name="chkbox" value="<%=indice%>"/>
  <% } %>
  </display:column>
  <%indice++; %>
  </display:table>

When I select a checkbox it does not enter the selectCheckAll function.

A: You can compare the number that can be checked vs the number that are checked and set the check all checkbox accordingly. The following is a quick hack in POJS to demonstrate the method, there's likely a jQuery equivalent.

function checkAll(inp) {
  document.querySelectorAll('.groupA').forEach(el => el.checked = inp.checked);
}

function setCheckAll() {
  document.querySelector('input.checkAll').checked =
     document.querySelectorAll('.groupA').length ==
     document.querySelectorAll('.groupA:checked').length;
}
A <input class="groupA" type="checkbox" checked onclick="setCheckAll()">

B <input class="groupA" type="checkbox" onclick="setCheckAll()">

Check all<input class="checkAll" type="checkbox" onclick="checkAll(this)">

A: Use jquery to bind a change event to your check box then check it.
I don't know if there is any other better way, but I'd do it in this way, please tell me if there are any other better ways. Thanks
var myChkBoxes = $('.checkbox')
myChkBoxes .on('change', function(){
  var blnAllChk = $('.checkbox:checked').length === myChkBoxes.length;
  blnAllChk ? (all checkboxes are checked, do something) : (else, do something);
});


text:
Q: Как получить имя узла? Когда в консоли пишешь
console.dir(
  d.getElementById("blog-container")
)

он возвращает объект с таким вот названием section#blog-container

Как получить это название ?
Мне это нужно для делегированных событий, что бы я мог писать в функцию селектор, а при событии функция брала такой селектор у элемента и сравнивала.
Пример:
on("click", "section#blog-container", function () {
  ДЕйствие
})

в идеале конечно хотелось бы заставить работать селекторы такого типа body > div > header > bottom, но у меня нет вообще никаких идей. Если подскажите что нибудь буду рад)
p.s. Я не использую jQuery, я делаю в некотором роде его клон. Задача стоит сделать функцию делегированных событий. Конкретно проблема заключается в удобном отлавливании событий вот по таким селекторам ".texteditor > header > button". и само событие вешается на body т.к. весь сайт ajax

A: Я как то раз решал похожую задачу. Вот что вышло:
function(el){
    if(el==document){
        //Костыль(
        return {
            selector:'document'
        };
    }
    if(el==window){
        //Костыль(
        return {
            selector:'window'
        };
    }
    var selector=null;
    if(el.id){
        selector='#'+el.id;
    }else{
        if(el.className){
            selector='.'+el.className.split(' ').join('.');
        }else{
            //Ох..ну ничего,прорвемся.
            selector=el.tagName;//tagName то у тебя точно есть.
            if(el.name){
                selector+='[name='+el.name+']';
            }
        }
    }
    if(!selector)console.error('Cant build selector!',el);
    var index=$(selector).index(el);
    return {
        selector: selector,
        index: index
    }
}

Как видите, здесь кроме селектора есть еще index - т.е. номер конкретного элемента в списке элементов с таким селектором. Позволяет точно определять любой элемент на странице.


text:
Q: Date format in lotus notes I have a lotus notes field which should save the date/time in the GMT format,
for that I used
Dim timenow As Variant
timenow = Now()
Dim dateTime As New NotesDateTime( timenow )
doc.abc = dateTime.GMTTime
This will set the field 'abc' to have the date and time in GMT. But now I am having issues with the date format. In my system it saves it in the format 10/28/2016, but for other users whose system date format is different, it saves it in the format 28.10.2016. I need to force the date format to be 10/28/2016, I tried used format function
doc.abc = Format(dateTime.GMTTime, "m/d/yy h:nn")
The above code gives the date and time in GMT, but doesn't change the date format.

A: You are wrong in the assumption, that the date is SAVED in that format.
Date items in the backend are number- items. They store the date as number, the integer part is the day, the fraction part is the time of the day (day 0 is 12/31/1899 00:00)
Then the setting in the client determins, how the client displays the date.
In the properties of the item you usually define "Client" as display format, but you could fix the display of the date to a specific form.
But usually this is NOT necessary, and every german will not like the "reversed" order of english / american time formatting.
This will only be a problem, if you construct a text from that date, as @Text() will convert it using the clients format.
I guess, that your problem is not in the "saving" of the item, but somewhere else in your code, where you interpret the date as text, and this is always a problem.

A: What type of field is it? If it's a date field, the Notes client will use the user's local date format.
If you want to use a specific format, you can use a text field instead, but of course then the time won't adjust to the user's local time zone.
The way to get the best of both worlds is to store the date in  date field, but use a computed-for-display field to show it in the user's current timezone, but in exactly the format that you want.

A: Most people use a NotesDateTime object to set the date in a field
Dim ExpiryDate As New NotesDateTime(Cstr(Today))

Even if the field in the form uses a specific format, the date like 2019-09-08 can mean 8th september 2019 or 9th august 2019 depending of the LocalDate setting
To avoid this behavior, you need to force the format in your NotesDateTime Object
Like this
Dim ExpiryDate As New NotesDateTime(Format$( Today, "yyyy-mm-dd "))


text:
Q: Python - Index Error: string index out of range I'm trying to replicate Adam Calhoun's experiment of reducing classic novels to punctuation and present it in posters.
Using his code, I was able to get to the punctuation stage, but, when I tried to transform it in a poster, I got the "IndexError: string index out of range" error message in the "symb = txt[jj + ii * symbolsPerLine]" line.
for ii in range(linesOfText):
    for jj in range(symbolsPerLine):
        symb = txt[jj + ii * symbolsPerLine]
        if (symb == "."):
            draw.text((trim + jj * deltaW, trim + ii * deltaH - round(font2size / 4)), symb, fill=endSentenceFill,
                      font=font2)
        elif (symb == ','):
            draw.text((trim + jj * deltaW, trim + ii * deltaH - round(font2size / 4)), symb, fill=transitionFill,
                      font=font2)
        elif (symb == '!') or (symb == '?'):
            draw.text((trim + jj * deltaW, trim + ii * deltaH), symb, fill=endSentenceFill, font=font2)
        elif (symb == '"') or (symb == '\'') or (symb == '(') or (symb == ')') or (symb == '[') or (symb == ']'):
            draw.text((trim + jj * deltaW, trim + ii * deltaH), symb, fill=parentheticalFill, font=font2)
        elif (symb == ';') or (symb == '-') or (symb == ':'):
            draw.text((trim + jj * deltaW, trim + ii * deltaH), symb, fill=transitionFill, font=font2)
        else:
            draw.text((trim + jj * deltaW, trim + ii * deltaH), symb, fill="green", font=font2)

What's the problem with the code?

A: symb = punct[jj + ii*symbolsPerLine]

A: maybe this
for ii in range(len(linesOfText)):
    for jj in range(len(symbolsPerLine)):

Lets say txt is 2 long but if  ii + jj * symbolsPerLine is 3 it will return index out of range
symb = txt[jj + ii * symbolsPerLine]


text:
Q: SOQL: following a lookup field, then SELECTing all its children Imagine I have Custom Objects A, B and C.
A has a lookup field B__c that looksup a B field.
C also has a lookup field B__c that lookups a B field.
If we were to draw the lookup relations graphically, it would look like
A -> B <- C
Now I want to have a SOQL query that, given an A Id, fetches A, B and all the C elements of that B. The one->many name from B to C is Cs. How can I do this?
When I try something like
SELECT Id, (SELECT Id FROM A.B__r.Cs__c) FROM A__c

it gives the error

Error: Compile Error: First SObject of a nested query must be a child
  of its outer query

A: Depends on how you want your data returned. Two options are:
SELECT Id, B__c FROM C__c WHERE B__c IN (SELECT B__c FROM A__c)

or
SELECT Id, (SELECT Id FROM C__r) FROM B__c WHERE Id IN (SELECT B__c FROM A__c)

A: Re: comment

Is it possible to get A, B and all the C of B?

SELECT Id, Name,
    (SELECT Id, Name FROM A__r WHERE Id = :...),
    (SELECT Id, Name FROM C__r)
FROM B__c
WHERE Id = (SELECT B__c FROM A__c WHERE Id = :...)

Say Account, all it's Contacts and Opportunities where contact = John Doe
SELECT Id, Name,
    (SELECT Id, LastName FROM Contacts WHERE LastName = 'Doe'),
    (SELECT Id, StageName FROM Opportunities)
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE LastName = 'Doe')

Experiment with WHERE Id IN and WHERE Id = depending on your needs etc but that's the baseline I'd say.

A: I am developing an iOS app in Swift and needed to get the first and last name from the Lookup(Contact) field in a SOQL query. That Lookup(Contact) field was given the API Name FirstField__c. In Xcode, as much as I tried, I could not use the __r method. Instead I found it easier to create a second custom read only Formula (Text) field with the formula:
FirstField__r.FirstName & " "& FirstField__r.LastName

That new field was given the API Name SecondField__c and then in my SOQL, I easily queried that new field.
I hope this helps someone in a similar situation.


text:
Q: MySQL get the difference on joined table - stock transactions/inventory system I am not sure how to ask this, but I will try anyway. I have a DB structure that tracks stock inventory for each product, product lots and warehouse locations. This allows me to know exactly what products are on stock, at what price and on what location.
Basically I use two tables for tracking

*

*stock_transactions [id, product_id, lot_id, warehouse_location_id, type, quantity]

*

*product_id = Unique identifier for SKU item in the warehouse

*lot_id = Unique identifier for product lots that arrived into the warehouse.

*warehouse_location_id = Unique identifier of warehouse location

*type = type of transaction [IN = into location, OUT = OUT of location]

*stock_transactions_serials [stock_transaction_id, serial_id]`:
I am creating an entry in stock_transactions for every item we move from warehouse location to location. E.g. if I move 5 quantity of product A from location X to location y I will create two entries:
INSERT INTO stock_transactions
(id, product_id, lot_id, warehouse_location_id, type, quantity)
VALUES (1, 'A', 'Aq2er4', 'X', 'Out', -5)

INSERT INTO stock_transactions
(id, product_id, lot_id, warehouse_location_id, type, quantity)
VALUES (1, 'A', 'Aq2er4', 'Y', 'In', 5)

Some products we track via serial numbers. For example if above product would have serial numbers we would use barcode reader to scan which serail numbers of product A we have moved to another locations. The table stock_transactions_serials will track serial numbers for each stock transaction.
Now I have two problems that I need to solve:
1. I need to get the list of products and quantities on stock (grouped by product_id, lot_id and location_id. I have achieved this by:
SELECT id, product_id, lot_id, warehouse_location_id, sum(ST.quantity) as qty
FROM stock_transactions ST
GROUP BY product_id, lot_id, warehouse_location_id
HAVING qty > 0

I have created SQLFiddle with some data here: http://sqlfiddle.com/#!9/fb352/2.
2. I need to get the right serial numbers for that stock. I don't know how to tackle this...
If I join the tables I don't get the right results, or my stock SUM's are wrong. Any ideas? I would need to somehow get the difference between In and Out transactions and get the right serials.

A: It seems product_id + lot_id + warehouse_location_id is the natural key for stock_transactions. You chose to add a surrogate id, so a record gets uniquely identified both by either its natural key or its ID. You chose to group by the natural key, but you could just as well have grouped by id. Is this assumption correct?
In that case you can simply aggregate the serial numbers per stock_transactions.id (i.e. concatenate them) and join this list:
SELECT
  ST.id,
  ST.product_id,
  ST.lot_id,
  ST.warehouse_location_id,
  sum(ST.quantity) as qty,
  STS.serials
FROM stock_transactions ST
LEFT JOIN
(
  SELECT stock_transaction_id, GROUP_CONCAT(serial_id) AS serials
  FROM stock_transactions_serials
  GROUP by stock_transaction_id
) STS ON STS.stock_transaction_id = ST.id
GROUP BY ST.product_id, ST.lot_id, ST.warehouse_location_id
HAVING qty > 0;

A: I think you just need a JOIN:
SELECT st.product_id, st.lot_id, st.warehouse_location_id,
       st.quantity as qty
       GROUP_CONCAT(sts.serial_id) as serials
FROM stock_transactions st JOIN
     stock_transactions_serial sts
     ON sts.stock_transaction_id = st.id
GROUP BY st.product_id, st.lot_id, st.warehouse_location_id, st.quantity
HAVING qty > 0;

Note:  This will produce a comma-delimited list of the serial numbers.


text:
Q: How to use a .svg file in Material-UI Avatar component I have an svg file that I want to use within mui avatar component but
Doing this <Avatar src="./**.svg" /> does not render (blank).
While this <Avatar src="./**.png" /> works.
Is there a workaround?

A: You can create a separate component for SVG and pass it a child for SVG as per the documentation present in
https://mui.com/components/avatars/

<Avatar>
  <SVGComponent />
</Avatar>

A: You could create a SvgIcon component based on the .svg file and next you could use that component in the Avatar to show the icon.
I will show you an example step by step:

*

*Download the .svg file to be used in the example

*Create the SvgIcon component in a .tsx file based on the downloaded file. All the path tags are important:
import * as React from "react";
import SvgIcon, { SvgIconProps } from "@material-ui/core/SvgIcon";

const AddCircleOutlineIcon: React.FC<SvgIconProps> = (props) => (
    <SvgIcon {...props}>
        <path d="M0 0h24v24H0V0z" fill="none"/>
        <path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
    </SvgIcon>);

export default AddCircleOutlineIcon;

*Add the icon component created in the Avatar:
<Avatar>
    <AddCircleOutlineIcon />
</Avatar>

*Icon Avatar Doc

A: If you have the SVG stored locally, you can use import {ReactComponent as YourSvg} from 'path/to/svg' and simply use it as a component.
<Avatar>
  <YourSvg />
</Avatar>

You could also import your SVG and use it as the src
import AvatarSvg from 'path/to/svg'

<Avatar src={AvatarSvg} />


text:
Q: Receiving delayed emails, could it be my domain or MX records if not what else? I noticed that when receiving emails on my domain they come delayed compared to another domains i have tested.
The emails are being forwarded from a google email to two different addresses most of the time the emails are delivered with no delay but sometimes the delay have been up to 8 minutes.
Due to the nature of my application i need the email once received be sent as an HTTP request to my server, first time i tried using mailgun and i those issues emerged, so then i switched to using: https://github.com/Flolagale/mailin on my own server and then POST to localhost and for my surprise the delays kept happening.
It doesn't happen all the time but it happens a few times a day but some of those emails are time sensitive and can't be delayed.
At some point i started forwarding the emails to another service who does the same i'm doing ( receiving emails and posting the messages to a  telegram room ) and their service ALWAYS receive it and post with no delays, funny enough they use mailgun which was my first choice.
I thought it could be due to my application implementation but it doesn't seem to have any load on the machine at all, the linux machine running my http server and mail server has a lot of CPU and RAM headroom.
I suspected it could be the TTL or any other configuration on my MX record but i can't find information regarding this sort of connection between emails being delayed.
What am i possibly doing wrong?

A: Anything that is time sensitive should not go via email as it only offers best efforts and no guarantees about delivery.
Check your logs to see if there is information regarding the delays. If there isn't then there isn't much you can do to influence the sending side.


text:
Q: Is a random intercept model exactly the same as a linear model with dummy variable? I have a large household dataset for 28 different countries. Upto now I have used OLS (R command lm()) with 'country' as a dummy variable, to control for unobserved heterogeneity between countries.
Is this exactly the same as using a linear mixed effects model with country random effects for the intercept (lmer() with + (1|country)?
I appear to get exactly the same results when I make predictions with both models (using predict()). I was wondering whether this is normal or whether I have overlooked something?

A: The difference between the two is that dummy variables do not share information with each other whereas random effects do via a distribution. The dummy variable model estimates 28 different effects. The mixed model estimates a distribution from which the 28 effects are drawn from. They share information because they all contribute to the estimation of the variation. This is my favorite blog post on the topic.

A: The blog post that @statwonk mentioned is superb and worth reading in full. However, for an alternative simple demonstration, consider just the intercepts that we get from these two models, when using the sleepstudy dataset:

*

*Model 0: Dummy variables for each subject (group)

*Model 1: Using random effect for each subject (group)

Here's the distribution of intercepts in each case:

As @statwonk mentioned, this difference is because in the random effects model, there is a "soft constraint" that ensures that the intercepts are all drawn from a common distribution. There is no similar constraint in the dummy variables model.
Here's the code for generating the plot:
library(lme4)
library(magrittr)
library(dplyr)

# ### Model 0: Using dummy variables for group
m0_dummy <- lm(Reaction ~ Subject, data = sleepstudy)

# Extract coeffiencts:
df_m0_coef <- m0_dummy$coefficients %>% as.data.frame()

# Convert intercepts from relative to absolute values:

# By default, one subject is assigned as the baseline, and all other
# subject intercepts are shown as deviations from the baseline.
# Here, we convert all subject intercepts to absolute values.

baseline_intercept <- df_m0_coef[1,1]
df_m0_coef <- df_m0_coef %>%
  mutate(group_intercept = ifelse(. != baseline_intercept,
                                  baseline_intercept + .,
                                  .)) %>%
  select(group_intercept)

# ### Model 1: Using random effect for group
m1_random_effects <- lmer(Reaction ~ 1 + (1 | Subject), data = sleepstudy)

# Extract coeffiencts:
df_m1_coef <- coef(m1_random_effects)$Subject

# ### Comparison plots
x_range <- c(150, 400)
y_range <- c(0, 10)

par(mfrow = c(1, 2))

df_m0_coef$group_intercept %>%
  hist(xlim = x_range, ylim = y_range, breaks = 10,
       main = 'Dummy model: \nEstimates of group intercepts')

df_m1_coef$`(Intercept)` %>%
  hist(xlim = x_range, ylim = y_range, breaks = 10,
       main = 'Random effects model: \nEstimates of group intercepts')


text:
Q: What is the exactly Perf buffer size? after I read the manual of perf_event_open(), I have a few question about buffer's size in capture sampling event.
In the description section, it says that

A sampling event periodically writes measurements to a
         buffer that can then be accessed via mmap(2).

And when the buffer overflow, PMU will trigger the PMI, we can access the content of buffer via mmap() system call. (is my understanding correct?)
But the question is, how big is the Perf buffer? Can I set a new value (buffer length) to overwrite it?
Variable __u64 data_size in the struct perf_event_mmap_page only indicates the records size in this time.

A: Your understanding is correct, when you say that you can use mmap to collect perf data periodically.
Before I begin, perf uses two buffers to record different kinds of events. An auxiliary buffer is used, under the main ring buffer( the ring buffer contains this auxiliary buffer ), to store different kinds of event information. Since you are asking me about the main perf buffer I will try answering that.
You can modify the perf buffer size. As per the documentation, the perf buffer size is defined in terms of pages. It is defined to be 1 + 2^n pages, where one page is required to store metadata about the ring buffer that perf  uses.
When you try recording events, using perf record , (read the manpage for perf record), you will have a switch -m which will allow you to specify the number of pages that will increase/decrease the perf ring buffer. The number of (mmap) pages that you specify must be a power of 2.(However, you can also directly specify the size) Increasing the number of pages by 1, will increase the ring buffer size by 4kB (which is the page-size, specified in code by 1 << 12).
However, as far as I know, this number of pages will only go so far as 2^31. Moreover, using such a huge buffer will risk not recording any events at all or recording arbitrary events.


text:
Q: $.post data success returning data unsuccessfully, but successfully? I'm working on a "like" function in php and jquery and I'm at the last part of it. When I click on the:
<a href="#" class = "like" onclick="like_add(<?php echo $post_id ?>);">like
<span id="post_<?php echo $post_id ?>_likes">
    <?php echo $post_likes; ?>

the function in add_like.php:
<?php add_like() ?>

submits the user data and increments the like count by one in the database.
The problem I'm having is I'm getting an alert that say success in it when it shouldn't be and it doesn't update the like count until I refresh the page. I should be getting a alert that says 'works!' and getting the like count back.
edit**
Right now it is returning the echoed "success" from the like_add.php in the alert when I click on the like button. This to be exact:
'
success'
like.js
function like_add(post_id){
 $.post('../public/like_add.php', {post_id:post_id}, function(data){
    if (data == 'success') {
        like_get(post_id);
        alert("works!");
    }else{
        alert("'" + data + "'");
    }
 });
}
function like_get(post_id){
 $.post('../public/like_get.php', {post_id:post_id}, function(data){
     $('#post_'+post_id+'_likes').text(data);
 });
}

add_like.php
<?php
if(isset($_POST['post_id'], $_SESSION['user_id'])
&& post_exists($_POST['post_id'])){

$post_id = $_POST['post_id'];
$user_id = $_SESSION['user_id'];

  if (previously_liked($post_id, $user_id) === true) {
    echo "You've already liked this";
  } else{
    add_like($post_id, $user_id);
    echo 'success';
  }
}?>

A: If you have whitespace (like a hard return) before your <?php or after your closing ?> tag, you will return more than "success" as you saw when you alerted ' success'. Find this whitespace and remove it. Make sure your opening PHP tag is flush against the top left of your script page.

As commenters have mentioned, an easy fix is to trim the data variable so ' success' becomes 'success';


text:
Q: Update Query in asp.net when i try to preform Update Profile Page in my project , the query does not work very well .
the code on below :
 Protected Sub btnSubmimt_Click(sender As Object, e As EventArgs) Handles btnSubmimt.Click
        Dim dt As DataTable = New DataTable()
        dt = Session("Info")
    Dim connStr As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString

    Dim conn As SqlConnection = New SqlConnection(connStr)
    conn.Open()
    Dim cmd As SqlCommand = New SqlCommand()
    Dim da As SqlDataAdapter = New SqlDataAdapter()

    cmd.CommandType = CommandType.Text
    cmd = New SqlCommand("Update [users] Set  Email = @Email , Role = @Role  , Country= @Country where UserName = @UserName")

    cmd.Parameters.Add(New SqlParameter("@Email", txtEmail.Text.ToString))
    cmd.Parameters.Add(New SqlParameter("@Role", txtRole.Text.ToString))
    cmd.Parameters.Add(New SqlParameter("@Country", DDLCountry.SelectedValue.ToString))
    cmd.Parameters.Add(New SqlParameter("@UserName", Session("UserName")))
    cmd.Connection = conn

    cmd.ExecuteNonQuery()

    conn.Close()

    ModalPopupExtender1.Show()

End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt = Session("Info")
        txtusername.Text = dt.Rows(0)("UserName").ToString
        txtEmail.Text = dt.Rows(0)("Email").ToString
        txtRole.Text = dt.Rows(0)("Role").ToString
        DDLCountry.SelectedItem.Text = dt.Rows(0)("Country").ToString
    End If
End Sub

A: You do not need DataTable and SqlDataAdapter as you are not retrieving any data.
I believe you want something like this -
Protected Sub btnSubmimt_Click(sender As Object, e As EventArgs)
    Dim connStr As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
    Dim cmdText As String = "Update [users] Set Email = @Email , Role = @Role, Country= @Country where UserName = @UserName"
    Using conn = New SqlConnection(connStr)
        Using cmd = New SqlCommand(cmdText, conn)
            conn.Open()
            cmd.Parameters.Add(New SqlParameter("@Email", txtEmail.Text))
            cmd.Parameters.Add(New SqlParameter("@Role", txtRole.Text))
            cmd.Parameters.Add(New SqlParameter("@Country", DDLCountry.SelectedValue))
            cmd.Parameters.Add(New SqlParameter("@UserName", Session("UserName")))
            cmd.ExecuteNonQuery()
        End Using
    End Using
    ModalPopupExtender1.Show()
End Sub


text:
Q: Initialize class variable by passing a reference to it I have a quite interesting and funny C++ exercise:
This the imposed main:
int main(void)
{
    Exam e = Exam(&Exam::cheat);
    e.kobayashiMaru = &Exam::start;
    (e.*e.kobayashiMaru)(3);
    Exam::cheat = true;
    if (e.isCheating())
        (e.*e.kobayashiMaru)(4);
    return (0);
}

And this is the asked output:
[The exam is starting]
3 Klingon vessels appeared out of nowhere.
You lost again.
[The exam is starting]
4 Klingon vessels appeared out of nowhere.
Win !

You now need to create the Exam class to get the correct output.
Here is what I've done:
class Exam
{
public:

    Exam(bool *_cheat);

    typedef void (Exam::*func)(int);
    void            start(int);
    bool                       isCheating();
    static bool               cheat;
    func                       kobayashiMaru;
};

I encounter problems with the Exam(&Exam::cheat) thing. What I understand so far is that Exam is taking the address of it's own cheat variable. When entering the Exam's constructor cheat is uninitialized. So for me I would initialize it here with false.
Exam::Exam(bool * _cheat)
{
   *_cheat = false;
}

But by doing this I get a multiple definition with Exam(&Exam::cheat). I'm not sure about my reflection, can maybe someone enlighten me on what's really happening here?

A: Change:
static bool cheat;

to:
bool cheat;

inside your Exam class to allow every new object handle its own cheat variable with its own value.
Constructor will initialize your cheat variable by given value while you creating new object with constructor like this:
Exam::Exam(bool isCheating)
{
   this->cheat = isCheating;
}

Or if you want to initialize cheat variable as false/true by default you can make constructor like this:
Exam::Exam()
{
   cheat = false;
   //or cheat = true;
}

You can handle multiple constructors too.
Now to create new object from Exam class use:
Exam *exam1 = new Exam(true); //Will initialize cheat as false
Exam *exam2 = new Exam(false); //Will initialize cheat variable as true

Then access your methods inside exam1 and exam2 object like this:
exam1->methodName(1243);
exam2->secondMethodName(true);
exam2->thirdMethodName();
exam3->addFriend(&exam1);

Those ones are just examples.
Hope I understood your problem. :)

A: You have a few issues (described in comments below)
class Exam
{
public:

    // If cheat is supposed to be a member variable assigned to each instance, passing a pointer to itself is silly and unnecessary
    // If cheat is supposed to be shared between all instances of exam, passing a pointer to itself is silly and unnecessary
    Exam(bool *_cheat);
    static bool               cheat;

    // these two declarations are unnecessary.  They do nothing but add complexity where it is not needed
    typedef void (Exam::*func)(int);
    func                       kobayashiMaru;

    void            start(int);
    bool                       isCheating();
};

I encounter problems with the Exam(&Exam::cheat) thing. What I
  understand so far is that Exam is taking the address of it's own cheat
  variable. When entering the Exam's constructor cheat is uninitialized.
  So for me I would initialize it here with false.

Static variables are initialized before the creating of the first instance of a class.  The problem you have is two-fold:  1) you haven't initialized your static member variable, 2) you aren't treating it as a static member variable.
Declaring a variable as static means it will be shared between all instances of the class (e.g. there will be 1 memory location for cheat).  Unless you want everyone taking the Exam to cheat as soon as 1 person cheats, this is not likely what you want.
To fix it, you would want your Exam class to look more like this:
class Exam
{
public:
    Exam(bool cheat) : m_cheat(cheat) {}

    // don't expose member variables directly - use accessor functions
    void setCheating(bool cheat) { m_cheat = cheat; }
    bool isCheating() const { return m_cheat; }

    void start(int);
private:
    bool               m_cheat;
};

The corresponding changes to your main function
int main(void)
{
    Exam e(false);
    e.start(3);
    e.setCheating(true);
    if (e.isCheating())
        e.start(4);
    return 0;
}


text:
Q: Trying to scroll into view a nested scrollbar element's child I'm trying to scroll into view a dummy div (id = "bottom"), which is contained inside a nested scrollbar.
But whenever the statement is executed, it just scrolled the main scrollbar (the one on the page it self.)
Below is the code, the mapped element is a list of messages, which rerenders after a new message has been sent. I've kept document.getElementById('bottom').scrollIntoView();
Which indeed works but it just scrolls the scrollbar outside the "messageList" div (the main scrollbar of the webpage.).

                {data &&
                  data.map((msg) => {
                    const currentMsg = msg.data();
                    const messageState =
                      currentMsg.uid === currentUser.uid ? 'sent' : 'received';
                    return (
                      <ChatBubble
                        key={msg.id}
                        text={currentMsg.text}
                        // Send time stamp as well
                        photo={currentMsg.photo}
                        messageState={messageState}
                      />
                    );
                  })}

dfdsf

Here is the img ref -

A: scrollIntoView is a method for document only, and can't be applied for a specific element.
You need to measure the distance between the #button element, and the top boundary of its parent.
You can use this method for measuring.
function scrollParentToChild(parent, child) {
// Where is the parent on page
  var parentRect = parent.getBoundingClientRect();
  // What can you see?
  var parentViewableArea = {
    height: parent.clientHeight,
    width: parent.clientWidth
  };

  // Where is the child
  var childRect = child.getBoundingClientRect();
  // Is the child viewable?
  var isViewable = (childRect.top >= parentRect.top) && (childRect.bottom <= parentRect.top + parentViewableArea.height);

  // if you can't see the child try to scroll parent
  if (!isViewable) {
        // Should we scroll using top or bottom? Find the smaller ABS adjustment
        const scrollTop = childRect.top - parentRect.top;
        const scrollBot = childRect.bottom - parentRect.bottom;
        if (Math.abs(scrollTop) < Math.abs(scrollBot)) {
            // we're near the top of the list
            parent.scrollTop += scrollTop;
        } else {
            // we're near the bottom of the list
            parent.scrollTop += scrollBot;
        }
  }

}


text:
Q: How to find row wise total and grand total for dynamic rows using nested form? I have used nested form. This is my jquery code to find row wise total and grand total for invoice application.
$("tr.sum_hours td").on("change", '.hr', function() {
  row = $(this).parent("td").parent();
  total    = 0;
  qnt      = 0;
  rate     = 0;
  discount = 0;
  tax      = 0;
  $(row).find("td input.hr").each(function(index) {
    if ($(this).val() !== "") {
      if ($(this).hasClass('quantity')){
        qnt = parseFloat($(this).val());
      }
      if($(this).hasClass('rate')){
        rate = parseFloat($(this).val());
      }
      if($(this).hasClass('discount')){
        discount = parseFloat($(this).val());
      }
      if($(this).hasClass('tax')){
        tax = parseFloat($(this).val());
      }
      return total = ((qnt*rate)-(discount)+(tax))
    }
  });
  $(row).find("td input.total").val(total);
  grand_total = 0;
  return $(".total").each(function() {
    if ($("#invoice_grand_total") !== "") {
      grand_total = grand_total + parseFloat($(this).val());
    }
    return $("#invoice_grand_total").val(grand_total);
  });
  });

and this is my html code.

    Item name
    Description
    Qty
    Rate
    Discount
    Tax
    Total
    Action

<input id="invoice_item_details_attributes_0_item_name" name="invoice[item_details_attributes][0][item_name]" size="30" type="text" />
<input id="invoice_item_details_attributes_0_description" name="invoice[item_details_attributes][0][description]" size="30" type="text" />
<input class="quantity hr" id="invoice_item_details_attributes_0_quantity" name="invoice[item_details_attributes][0][quantity]" size="30" type="text" />
<input class="rate hr" id="invoice_item_details_attributes_0_rate" name="invoice[item_details_attributes][0][rate]" size="30" type="text" />
<input class="discount hr" id="invoice_item_details_attributes_0_discount" name="invoice[item_details_attributes][0][discount]" size="30" type="text" />
<input class="tax hr" id="invoice_item_details_attributes_0_tax" name="invoice[item_details_attributes][0][tax]" size="30" type="text" />

<input class="total" disabled="disabled" id="invoice_item_details_attributes_0_total" name="invoice[item_details_attributes][0][total]" size="30" type="text" />
remove

<input id="invoice_item_details_attributes_1_item_name" name="invoice[item_details_attributes][1][item_name]" size="30" type="text" />
<input id="invoice_item_details_attributes_1_description" name="invoice[item_details_attributes][1][description]" size="30" type="text" />
<input class="quantity hr" id="invoice_item_details_attributes_1_quantity" name="invoice[item_details_attributes][1][quantity]" size="30" type="text" />
<input class="rate hr" id="invoice_item_details_attributes_1_rate" name="invoice[item_details_attributes][1][rate]" size="30" type="text" />
<input class="discount hr" id="invoice_item_details_attributes_1_discount" name="invoice[item_details_attributes][1][discount]" size="30" type="text" />
<input class="tax hr" id="invoice_item_details_attributes_1_tax" name="invoice[item_details_attributes][1][tax]" size="30" type="text" />

<input class="total" disabled="disabled" id="invoice_item_details_attributes_1_total" name="invoice[item_details_attributes][1][total]" size="30" type="text" />
remove

this code is working for static rows. But it is not working for the dynamically added rows.
Please help.

A: replace
$("tr.sum_hours td").on("change", '.hr', function() {

with this
$("body").on("change", 'tr.sum_hours td .hr', function() {

i hope it will work.
if you want more clarification see jQuery click function doesn't work after ajax call?
a jsfiddle demo of want went wrong http://jsfiddle.net/suhailvs/wjqjq/
jsfiddle of your code after the above changes,visit http://jsfiddle.net/suhailvs/t67pn/1/