text:
Q: Android memory used by ListView vs TableLayout In an attempt at reducing total heap size of my app I was trying to change a TableLayout into a ListView.
The source list is an ArrayList which items containing a drawble, a text and a checkbox state. This array is entirely initialized beforehand.
Before opening the activity using either the ListView or TableLayout, heap size is about 7.5Mb
With the TableLayout it grows to 8.3Mb and doesn't grow higher
With the ListView it grows to 8.1Mb initially and grows to 11.5Mb when scrolling through the list!
Why is the ListView consuming more when scrolling whereas it's supposed to reuse views?
I was expecting that ListView will consume less and actually not grow when scrolling!?
Is the behavior I'm seeing normal or expected or am I missing something?
I've verified the ListAdapter does reuse views, here is an extract of the ListAdapter code. It contains the only new() in the getView() method.
private static class AppListAdapter implements ListAdapter
{
    WeakReference<MyActivity>   wr;
    ArrayList<AppInfo>      app_list;

    public AppListAdapter(MyActivity activity, ArrayList<AppInfo> list)
    {
        wr = new WeakReference<at_startup_apps>(activity);
        app_list = list;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        MyActivity activity = wr.get();
        if (sa == null)
            return null;

        AppInfo ai = app_list.get(position);

        LinearLayout ll;
        ImageView img;
        TextView new_txt;
        CheckBox cb;
        if (convertView == null)
        {
            ll = new LinearLayout(activity);

            img = new ImageView(sa);
            img.setScaleType(ScaleType.FIT_CENTER);
            ll.addView(img);

            new_txt = new TextView(activity);
            new_txt.setOnClickListener(activity.onTextClick);
            new_txt.setGravity(Gravity.CENTER_VERTICAL);
            new_txt.setPadding(4, 2, 4, 2);
            new_txt.setTextSize(activity.font_size + 2);
            ll.addView(new_txt);

            cb = new CheckBox(sa);
            ll.addView(cb);
        }
        else
        {
            Log.d(at_data.TAG, "Reusing view " + position);
            ll = (LinearLayout)convertView;
            img = (ImageView)ll.getChildAt(0);
            new_txt = (TextView)ll.getChildAt(1);
            cb = (CheckBox)ll.getChildAt(2);
        }
        ll.setId(position);

        img.setImageDrawable(ai.drawable);

        new_txt.setText(ai.name);

        new_txt.setId(position);

        cb.setOnCheckedChangeListener(null);
        if (!ai.frozen)
            cb.setChecked(true);
        cb.setOnCheckedChangeListener(sa.onCheckedListener);

        cb.setId(position);

        return ll;
    }

A: So i decided to test the behavior on 5 test devices, each tests were performed twice to ensure results accuracy.
From the results I'd say ListView improves performance and memory consumption only if enough items are to be displayed. With 300 or less it seemed not very useful for any improvements.
Beyond that the gain is immediately visible, both in term of performance and consumption.
The Iconia A500 is the only device on which the ListView consumed more when scrolling. Not sure why, but any results are reassuring ;)
On the Nexus ListView didn't seem to be effective, but couldn't redo the tests or test with more items.
On the S3, not sure what's going on either but apps are definitely consuming a lot for nothing!
All this doesn't solve my initial problem: saving heap memory space, while my lists rarely grows higher than 300 (all apps installed).
Tested HW acceleration on/off, no difference in results.
Iconia A500 4.0.3: list contains 180 items
TableLayout: it grows to 8.9Mb, 8.8Mb allocated
ListView: it grows to 8.3Mb, 8.2Mb allocated and then to 12.6Mb / 10.3 when scrolling!

TF700 4.0.3: list contains 160 items
TabletLayout: 11.9Mb / 11.8Mb
ListView: 11.3Mb / 10.1Mb

Galaxy S3 JB 4.1: list contains 365 items
TableLayout: 20.7 / 19.8
ListView: 19.1 / 18.3

Galaxy Nexus JB 4.1: list contains 185 items
TableLayout: to 11Mb
ListView: to 13Mb

Galaxy S 2.3.6: list contains 205 items
TabletLayout: 6.4 / 3.8
ListView: 6.0 / 3.4

Some tests with 10 times more items
Obviously TableLayout is very slow to initialize: a few seconds!
Galaxy S 2.3.6: list contains 2050 items
TabletLayout: 14.6 / 11.9
ListView: 6.0 / 3.4

Galaxy S3 JB 4.1: list contains 3650 items
TableLayout: 20.7 / 19.8
ListView: 19.3 / 18.4

Iconia A500 4.0.3: list contains 1800 items
TableLayout: 17.1 / 16.9
ListView: 8.1 / 7.9 then growing to 10.8 / 10.6 when scrolling


text:
Q: Validation of clustering results I have a data which  contains several columns which I later reduced using a PCA algorithms to two different components. I then applied the k-means algorithms to the data.
Now, how can I verify that my data  clustered  well into each group? Or how do I determine misclassification rate?
For instance, using R, if I check the cluster vector say k$cluster against the labels of the data I had previously before clustering  can I just draw a confusion matrix from that and assume that 1 in the clustered vector is equivalent to 1 in my labels?
col3    col2     Col1   lables
123     2.32      2.50    0
124    2.81      3.10     1
125    2.72      3.09     2
126    2.92      3.03     3
127    2.32      2.95     4

Please note this is a hypothetical data; my data is way bigger than this.

A: If you have an a priori classification into groups, you should not rely on labels being identical between the a priori classification and the one you obtained. I would start  by computing the distances between the two clusterings (treating the classification  as a clustering) using a metric distance between clusterings. All such metrics can typically be derived from the confusion matrix only, and hence do not depend on labels beyond their indicating commonality of grouping within a single clustering. I usually recommend Comparing clusterings by the variation of information by Marina Meila. It discusses three metrics: the main contribution of the paper, the variation of information (which is very good), the Mirkin distance (related to the Jaccard index, well known, but not so good as it is affected in a quadratical manner by cluster sizes), and the split/join distance (Meila calls it 'van Dongen' distance). Disclaimer: the last one was developed by me. It has the advantage that it is interpretable as the number of nodes that need reallocation to change one clustering or classification into the other. There are many other clustering (dis)similarity measures, but I would only recommend these three, and although popular, I would not recommend the Jaccard/Mirkin measures.

A: One classic approach is the adjusted Rand index, which is a chance-corrected measure of similarity between two partitions (a clustering is, after all, a partition).  This is already implemented in R, in the mclust package (see here).  This value of the adjusted Rand index always lies between -1 and 1, and the index is not a metric (e.g., it doesn't satisfy the triangle inequality).  It has the nice property of being able to compare partitions of different sizes (i.e., clusterings containing different numbers of clusters).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selenium - click on anchor tag which is within a ul tag with attribute style="display: none;

      Actions

      Account Details

      Change Password

      My Works

      My Page

      My Resources

There is a login page where the below mentioned html gets loaded after complete login. So in order to get the clickable element, i tried to make Thread sleep as follows :
Thread.sleep(3000L);

Even after this, it says element is not found. now i want to write an automated selenium code to click on "Change Password" which is in nested li.
I have tried different selectors but resulted with negative results.
Selenium code:
List<WebElement> elems = driver.findElements(By.cssSelector("ul.menuUL>li.menuLI.ui-menu-item>a"));
elems.get(0).click();//for the 1st element
elems.get(1).click();//for the 2nd element
elems.get(2).click();

HTML :

                  Actions

                        Account Details

                        Change Password

                        My Works

                        My Page

                        My Resources

A: List<WebElement> elems = driver.findElements(By.cssSelector("ul.menuUL>li.menuLI.ui-menu-item>a"));

should fix your problem.
Also in your HTML code there is style="display: none; because of which Account Details Change Password My Works My Page My Resources are not visible. When the element is not visible even if you try Thread.sleep(3000L); you will not be able to click on the desired element.

A: In your HTML code if you look at the following line

you will see the display: none; attribute. This will hide the element and all its sub elements from view. So selenium can find the element but is not able to perform an action.
Solution 1
You have to ask the dev guy to display the element. (Remove the display: none; for the element). But the problem is why is it hidden in the first place?
Solution 2
Fire a javascript command instead of the selenium command for the element. The JavaScript command will work even if the element is not visible on the page.
List elems = driver.findElements(By.cssSelector("ul.menuUL>li.menuLI.ui-menu-item>a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", elems.get(0)); // select the element index from elemennt list as you need

A: You can use below code to perform your operation:-
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.xpath("//ul[@class='menuUL ui-menu ui-widget ui-widget-content ui-corner-all']"));

js.executeScript("arguments[0].setAttribute('style', 'display: fixed;')",element);

List<WebElement> elems = driver.findElements(By.cssSelector("ul.menuUL>li.menuLI.ui-menu-item>a"));

  elems.get(0).click();

A: @Prathibha and @debugger89 have pointed to the right direction that the
 tag containing the
 tags have the attribute style="display: none;. So to click on the element with text as Change Password you can use the following code block :
import java.util.List;
import org.openqa.selenium.JavascriptExecutor;
// lines of code
WebElement ulContainer = driver.findElement(By.cssSelector("ul.menuUL.ui-menu.ui-widget.ui-widget-content.ui-corner-all[role='menu']"));
((JavascriptExecutor)driver).executeScript("arguments[0].removeAttribute('style')", ulContainer);
List<WebElement> elems = driver.findElements(By.cssSelector("ul.menuUL li.menuLI.ui-menu-item[role='presentation'] > a"));
for(WebElement ele:elems)
    if(ele.getAttribute("innerHTML").contains("Change Password"))
    {
        ele.click();
        break;
    }


text:
Q: Regular expression to extract a numeric value on a changing position within a variable string How can I extract the bold numeric part of a string, when the most of the string can change? /data/ is always present and followed by the relevant, variable, numeric part (in this case 123456).
differentcontentLocationhttps://example.com/api/result/13548/data/123456differentstuffincludingwhitespacesandnewlines8484
$str = "differentcontentLocationhttps://example.com/api/result/13548/data/123456differentstuffincludingwhitespacesandnewlines8484";

$str2 = "differentcontentLocationhttps://example.com/api/result/13548/data/123456";

In this example I need 123456. The only constant parts in the string are /data/ and maybe the first part of the URL, like https://.
preg_match("@/data/([0-9]+)([^0-9]+)@siU", $str, $matches);

Results in Array ( [0] => /data/123456d [1] => 123456 [2] => d ), what would be acceptable. But if there's nothing following the relevant numeric part, like in $str2, this expression fails. I've tried to make the tailing part optional with preg_match("@/ads/([0-9]+)(([^0-9]+)?)@siU", $x, $matches);, but it fails, too; returning only the first number of the numeric part.

A: The U greediness swapping modifier makes all greedy subpattern lazy here, you should remove it together with ([^0-9]+). You also do not need DOTALL modifier because there is no . in your pattern whose behavior could be modified with that s flag.
preg_match("@/data/([0-9]+)@i", $str, $matches);

Now, the pattern will match:

*

*/data/ - a sequence of literal chars

*([0-9]+) - Group 1 capturing 1+ digits (same as (\d+))

See the PHP demo.
$str = "differentcontentLocationhttps://e...content-available-to-author-only...e.com/api/result/13548/data/123456differentstuffincludingwhitespacesandnewlines8484";
$str2 = "differentcontentLocationhttps://e...content-available-to-author-only...e.com/api/result/13548/data/123456";
preg_match("@/data/([0-9]+)@i", $str, $matches);
print_r($matches); // Array ( [0] => /data/123456  [1] => 123456  )
preg_match("@/data/([0-9]+)@i", $str2, $matches2);
print_r($matches2); // Array ( [0] => /data/123456  [1] => 123456  )


text:
Q: Apriori algorithm in plain English? I read wiki article about Apriori. I have the trouble in understanding the prune and Join step. Can anyone explain me how Apriori algorithm works in simple terms(such that Novice like me can understand easily)?
It will be good if someone explains the step by step process involved in it.

A: Apriori algorithm is an association rule mining algorithm used in data mining. It is used to find the frequent itemset among the given number of transactions.
It consists of basically two steps

*

*Self-Join

*Pruning

Repeating these steps k times, where k is the number of items, in the last iteration you get frequent item sets containing k items.
Look here for a very simple explanation with a detailed example http://nikhilvithlani.blogspot.com/2012/03/apriori-algorithm-for-data-mining-made.html.
It has a simple explanation without any complicated equations.

A: The Wikipedia article is not particularly impressive.  You might find these slides more helpful: 1, 2, 3.
At each level $k$, you have $k$-item sets which are frequent (have sufficent support).
At the next level, the $k$+$1$-item sets you need to consider must have the property that each of their subsets must be frequent (have sufficent support).  This is the apriori property: any subset of frequent itemset must be frequent.
So if you know at level 2 that the sets $\{1,2\}$, $\{1,3\}$, $\{1,5\}$ and $\{3,5\}$ are the only sets with sufficient support, then at level 3 you join these with each other to produce $\{1,2,3\}$, $\{1,2,5\}$, $\{1,3,5\}$ and $\{2,3,5\}$  but you need only consider $\{1,3,5\}$ further: the others each have subsets with insufficent support (such as $\{2,3\}$ or $\{2,5\}$ ).

A: Apriori in plain English.
Apriori employs an iterative approach known as level-wise search, where k-itemsets are used to explore (k+1)-itemsets. First, the set of frequent 1-itemsets is found by scanning the database to accumulate the count for each item, and collecting those items that satisfy minimum support. The resulting set is denoted as L1. Next, L1 is used to find L2, the set of frequent 2-itemsets, which is used to find L3, and so on, until no more frequent k-itemsets can be found. The finding of each Lk requires one full scan of the database.
At final iteration you will end up with many k-itemsets which is basically called association rules. To select interesting rules from the set of all possible rules various constraint measures such as support and confidence is applied.
Terms & Terminologies

*

*1-itemsets means {a} , {b} , {c}

*2-itemsets means {a, b} , {d, d} ,
{a, c}

*K-itemsets means {i1, i2, i3,... ik}, {j1, j2, j3, .... jk}

Join step : meaning 1-itemset is made to self join with itself to generate 2-itemsets.
Prune step : here resulting set from join is filtered with minimum support threshold.
cardinality set : resulting set from Prune  step .

Support = no.of transcations containing 'a' and 'b' /  total no of transaction.
Support => supp(a,b) => p(a U b)
Confident = No.of transactions containing 'a' and 'b' / no of transaction containing 'a'.
Confident => con (a, b) == > P (b|a) nothing but conditional probability.


text:
Q: How to initiate super in python 2 I need to make this python 3 code python 2 compatible:
class AlarmThread(threading.Thread):
    def __init__(self, file_name="beep.wav"):
        super().__init__()
        self.file_name = file_name
        self.ongoing = None

I get this error when I try to use the class in python 2:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "plugin.py", line 144, in run
    alert_after_timeout(seconds, message)
  File "plugin.py", line 96, in alert_after_timeout
    thread = AlarmThread()
  File "plugin.py", line 78, in __init__
    super().__init__()
TypeError: super() takes at least 1 argument (0 given)

A: You'll need to pass in the current class and self:
super(AlarmThread, self).__init__()

Also see Why is Python 3.x's super() magic? why and how Python 3 dropped the need to specify those.


text:
Q: Cells apears blank but cannot be replaced I try to replace blank cells by Ctrl+F function, however, there is one cell that cannot be replaced, although it appears empty. But when I use data filter, it is shown as "blanks".
Could anyone suggest a solution to this "blank but not blank" cells issue.
A copy of my sample file can be found here

A: These are space characters. Just find 'space' and replace by nothing.
The cell by definition is not 'blank' but contains characters that are not visible in normal conditions. Filtering however will show them as being blank.

A: Some special characters are rendered as space. Replacing with space will not do you any good. Try replacing with Ctrl+H with the character you copy from that "empty" space.


text:
Q: Computing the Initial Velocity of an orbiting body I'm working on a simulation program that replicates the movement of planets around a large celestial body (the sun). This is a three dimensional simulation that uses vectors. At present, I'm struggling to work out how to calculate the correct initial velocity vector so that the planet will enter into a stable orbit around the sun.

I've attempted to take the vector cross product of v1 and v0 but to no avail. I also attempted to calculate..
$T_0 = v_1 - v_0$
$T_1 = v_0 - v_1$
$NV = T_0 * T_1$
Where NV is the new velocity and * is the cross product function. This resulted in a zero vector because $T_0$ is parallel to $T_1$ so I find myself somewhat stuck. Does anyone know how to compute the correct vector?

A: The planet will follow an elliptical path and as an ellipse is a 2D figure it can only be traced to a plane and from two points infinite planes can pass, so you need to decide first which plane you want which is the missing information, because of which you are not able to do so. If finally you form a plane $\vec r.\vec N=p$ then the direction of the velocity vector of the planet is given by $\pm\vec N \times(\vec v_1-\vec v_0)$ the sign depending upon in which sense you want your planet to move clockwise or anti clockwise. On a paralle note the magnitude of velocity should be:
$$\frac{GMm}{|\vec v_1-\vec v_0|^2}=\frac{m|\vec v|^2}{|\vec v_1-\vec v_0|}\implies |\vec v|=\sqrt{\frac{GM}{|\vec v_1-\vec v_0|}}$$
where $G$ is the universal gravitation constant and M and m the mass of sun and the planet respectively.You must play with values so that it looks very real
Great help here


text:
Q: How to rename an associative array in Bash? I need to loop over an associative array and drain the contents of it to a temp array (and perform some update to the value).
The leftover contents of the first array should then be discarded and i want to assign the temp array to the original array variable.
Sudo code:
declare -A MAINARRAY
declare -A TEMPARRAY
... populate ${MAINARRAY[...]} ...

while something; do     #Drain some values from MAINARRAY to TEMPARRAY
    ${TEMPARRAY["$name"]}=((${MAINARRAY["$name"]} + $somevalue))
done
... other manipulations to TEMPARRAY ...

unset MAINARRAY        #discard left over values that had no update
declare -A MAINARRAY
MAINARRAY=${TEMPARRAY[@]}  #assign updated TEMPARRAY back to MAINARRAY (ERROR HERE)

A: This one-liner does an associative array copy: MAINARRAY=TEMPARRAY
eval $(typeset -A -p TEMPARRAY|sed 's/ TEMPARRAY=/ MAINARRAY=/')

A: Here is a small Copy-Function for bash-Variables of any kind
 - normal scalar variables
 - indexed arrays
 - associative arrays
### Function vcp    -VariableCoPy-
# $1 Name of existing Source-Variable
# $2 Name for the Copy-Target
vcp() {
    local var=$(declare -p $1)
    var=${var/declare /declare -g }
    eval "${var/$1=/$2=}"
}

Usage, Examples:
# declarations
var="  345  89  "
ind_array=(Betty "  345  89  ")
declare -A asso_array=([one]=Harry [two]=Betty [some_signs]=" +*.<\$~,'/ ")

# produce the copy
vcp var varcopy
vcp ind_array ind_array_copied
vcp asso_array asso_array_2

# now you can check the equality between original and copy with commands like
# declare -p <name>

The results
--3    1: "${asso_array[@]}"
(5)       asso_array[one]:        |Harry|
(11)      asso_array[some_signs]: | +*.<$~,'/ |
(5)       asso_array[two]:        |Betty|
--3    4: "${asso_array_2[@]}"
(5)       asso_array_2[one]:        |Harry|
(11)      asso_array_2[some_signs]: | +*.<$~,'/ |
(5)       asso_array_2[two]:        |Betty|
--2    7: "${ind_array[@]}"
(5)       ind_array[0]:   |Betty|
(11)      ind_array[1]:   |  345  89  |
--2    9: "${ind_array_copied[@]}"
(5)       ind_array_copied[0]:   |Betty|
(11)      ind_array_copied[1]:   |  345  89  |
(11)  11: "$var":   |  345  89  |
(11)  12: "$varcopy":   |  345  89  |

A: Copying associative arrays is not directly possible in bash. The best solution probably is, as already been pointed out, to iterate through the array and copy it step by step.
There is another solution which I used to pass variables to functions. You could use the same technique for copying associative arrays:
# declare associative array
declare -A assoc_array=(["key1"]="value1" ["key2"]="value2")
# convert associative array to string
assoc_array_string=$(declare -p assoc_array)
# create new associative array from string
eval "declare -A new_assoc_array="${assoc_array_string#*=}
# show array definition
declare -p new_assoc_array

A: Following both the suggestions of glenn jackman and ffeldhaus, you can build a function which might become handy:
function cp_hash
{
    local original_hash_name="$1"
    local copy_hash_name="$2"

    local __copy__=$(declare -p $original_hash_name);
    eval declare -A __copy__="${__copy__:$(expr index "${__copy__}" =)}";

    for i in "${!__copy__[@]}"
    do
        eval ${copy_hash_name}[$i]=${__copy__[$i]}
    done
}

Usage:
declare -A copy_hash_name
cp_hash 'original_hash_name' 'copy_hash_name'

Example:
declare -A hash
hash[hello]=world
hash[ab]=cd

declare -A copy
cp_hash 'hash' 'copy'

for i in "${!copy[@]}"
do
    echo "key  : $i | value: ${copy[$i]}"
done

Will output
key  : ab | value: cd
key  : hello | value: world

A: How about this one (Doesn't create a real copy, just a link to source variable):
#!/bin/bash
declare -A my_array=(["key1"]="value1" ["key2"]="value2")
declare -n arr=my_array
arr['LOG_FILE']=/tmp/log.txt
echo ${arr['key1']}
echo ${arr['LOG_FILE']}

Will print:
value1
/tmp/log.txt

A: With associative arrays, I don't believe there's any other method than iterating
for key in "${!TEMPARRAY[@]}"  # make sure you include the quotes there
do
  MAINARRAY["$key"]="${TEMPARRAY["$key"]}"
  # or: MAINARRAY+=( ["$key"]="${TEMPARRAY["$key"]}" )
done

A: expanding on Luca Borrione's cp_hash - which didn't work for me, and I gave up trying to track down the eval expansion issue - I ran into differences before and after bash 4.2.   after 4.2(something) this gets a lot easier... but that's not backwards compatible. See 1 and 2
so my variation tested on 4.1.2(1) and 4.3.46(1):
#!/bin/bash
## bash4 due to associative arrays!

    function cp_hash() {
        ## REQUIRES you to declare -A $2 in advance.
        local original_hash_name="$1"
        local copy_hash_name="$2"
        #
        # sadly we have no way to identify if you have already declared it, so bull ahead.
        #
        ## store the definition of the old array
        local __copy__=$(declare -p $original_hash_name)
        ## rename the array inside the definition
        __copy__=${__copy__/${original_hash_name}=/__copy__=}

        ## for bash 4.2 > we could end here.
        ## declare -A creates local scope variables by default, so add -g
        ## this DOES NOT work prior to 4.2, even w/o -g and w/ a declare outside.
        #    __copy__=${__copy__/${original_hash_name}=/${copy_hash_name}=}
        #    eval ${__copy__/-A/-g -A}

        ## for bash4 where we can't do -g, then:
        ## local associative array based on the definition we stored and modified
        eval ${__copy__}
        ## loop through the local copy, and store it in the declared-outside copy.
        for i in "${!__copy__[@]}"
        do
            eval ${copy_hash_name}[$i]=${__copy__[$i]}
        done
    }

    declare -A hash
    hash[hello]=world
    hash[ab]=cd

    #not required for 4.2+ if you use -g, neither helps nor hinders
    declare -A copy

    cp_hash 'hash' 'copy'

    echo hash: ${hash[@]}
    echo copy: ${copy[@]}

    echo "copy result loop"
    for i in "${!copy[@]}"
    do
        echo "key  : $i | value: ${copy[$i]}"
    done

A: MAINARRAY=( "${TEMPARRAY[@]}" )


text:
Q: What do the American nicknames 'Dutch' and 'T-Bone' mean? Does the nickname Dutch have any significance? I know it was Reagan's, and I'm sure I've come across it in other books/films.
Also T-Bone, as in T-Bone Walker, T-Bone Burnett: what does that mean? (I realise T-bone is a steak, but why would people be named after a meat cut, and why this one?)

A: Arnold Schwarznegger's character's (nick)name in the film "Predator" was "Dutch". I once read a review which claimed this was a way to explain his accent away.
As for T-Bone Walker, Wikipedia tells me

Aaron Thibeaux Walker[4] .... In 1929,
  Walker made his recording debut with a
  single for Columbia, "Wichita Falls
  Blues"/"Trinity River Blues," billed
  as Oak Cliff T-Bone.[1] Oak Cliff was
  the community he lived in at the time
  and T-Bone a corruption of his middle name.

A: We have answers for T-Bone Walker, but not for T Bone Burnett. An article by the Newark Star Ledger (posted on his own site) says:

Christened Joseph Henry Burnett, T Bone came by his nickname "honestly," around the age of 5, he says. The fact that he shared a moniker with famous Texas guitarist T-Bone Walker caused some wincing when he first started to perform, but he stuck with it.

So his name doesn't begin with a T and he didn't copy it from Walker, he just picked it somehow.
Some other T-Bones:

*

*T-Bone Slim (1890-1942), pen name for American poet, songwriter, and labour activist Matti Valentine Huhta: Apparently Slim was a common name for hoboes, perhaps because they tended to be skinny from lack of food. And maybe the T-Bone was for ironic contrast, and for the T sound from the end of Matti. His "Lumberjack's Prayer" begins: "I pray dear Lord for Jesus' sake, / Give us this day a T-Bone Steak".

*T-Bone (rapper), a Christian rapper: "His name came from being called 'Bones' as a youngster because he was very skinny. The 'T' was "added to give the name a little slang edge, hence the name 'T-Bone' was born.""
And these three all have names beginning with T:

*

*Tony "T-Bone" Bellamy, lead guitarist, pianist and vocalist of the 1970s band Redbone.

*Tom "T-Bone" Wolk, an American bassist: "guitarist G.E. Smith ... gave him the nickname T-Bone — for blues guitarist T-Bone Walker — after Wolk played his bass behind his head during a solo".

*Tom "T-Bone" Stankus, an American musician.

A: I have no doubt that "T-Bone" comes from the steak.  I think that a cut of steak is something considered fairly rugged and manly, so for this reason it might be attractive as a nickname.  Of course that is just speculation.  Also, I notice (from Wikipedia) that T-Bone Walker got his nickname because his middle name starts with a T.  I suspect that a name like T-Bone could easily arise from this sort of connection.

A: Having played in the brass section of a marching band in grade school, I know that trombones are frequently referred to as "t-bones". In the context of musicians, I have often assumed that those bearing the moniker "T-Bone" were, among other things, notorious trombonists (or "tromboners" per band director Dewey Largo on The Simpsons) but clearly this is not a reference that translates into popular culture with any frequency.

A: Dutch, not an uncommon nickname, seems to be used for a variety of reasons. It could be because a person is connected to Holland, or because a person is of German descent. Here, "Dutch" is from "Deutsch," the German-language word for "German." Other reasons are more idiosyncratic. Here are some examples:
Ronald Reagan, 40th President of the United States
As a boy, Reagan's father nicknamed his son "Dutch", due to his "fat little Dutchman"-like appearance, and his "Dutchboy" haircut; the nickname stuck with him throughout his youth.
Dutch Schultz, notorious gangster
His old associates dubbed him "Dutch" Schultz in honor of a deceased strong-arm thug who was notorious for dirty fighting at the turn of the century.
Dutch Ruppersberger, U.S. congressman
Dutch is legally part of his name: Charles Albert Dutch Ruppersberger III, but it wasn't always. When Rep. Charles Albert Ruppersberger III (D-Md.) first ran for Congress in 2002, he decided that his 13-letter last name was too long to put on a bumper sticker.
Besides, he says, he needed something catchier, something that would stick in people's heads. So he opted for his lifelong nickname: Dutch. But there was one hitch: It wasn't his real name, so he couldn't put "Dutch" on the ballot.
"When you market yourself, you have to make sure that you have the same name on the ballot, so I needed 'Dutch' on the ballot," he said in an interview. "So what I did is I legally -- I'm a lawyer -- I legally added Dutch to my name. So I would go by C -- period -- A -- period -- Dutch, and all of the bumper stickers would say, 'Go Dutch.' So legally I added Dutch to my name."
But why did he choose "Dutch"? The Maryland Democrat's nickname has been --Dutch-- since the moment of his birth.
--When I was born ... the doctor came out and said to my father, 'You have a big blond Dutchman,' -- he said. --So they started calling me 'Dutch,' and when my mother and he would write letters, he'd ask, 'How's the Dutchman doing?' I've been called Dutch all of my life.--
Dutch Fehring, Stanford's winningest baseball coach.
It was during his freshman year in high school that he earned the nickname --Dutch,-- because he was of German descent.  After Fehring returned a kickoff 60 yards for a touchdown, a local sportswriter tabbed him --The Flying Dutchman-- and the nickname stuck.

A: A T-Bone steak is a hearty cut, so a person whose name is Tom or Terry etc may like the name "T-Bone" because it has a "Beefy" or "Strong" connotation.
I have a friend whose last name is "Holland" so some people call him "Dutch".

A: My grandfather, named Richard, was given the nickname Dutch by his high school football coach and stuck with it his entire life and he was of German descent. Good thing too, at least he wasn't called Dick!


text:
Q: Conversion function for error checking considered good? I'd like to have a simple way of checking for an object to be valid. I thought of a simple conversion function, something like this:
operator bool() const { return is_valid; }

Checking for it to be valid would be very simple now
// is my object invalid?
if (!my_object) std::cerr << "my_object isn't valid" << std::endl;

Is this considered a good practise?

A: In C++03, you need to use the safe bool idiom to avoid evil things:
int x = my_object; // this works

In C++11 you can use an explicit conversion:
explicit operator bool() const
{
    // verify if valid
    return is_valid;
}

This way you need to be explicit about the conversion to bool, so you can no longer do crazy things by accident (in C++ you can always do crazy things on purpose):
int x = my_object; // does not compile because there's no explicit conversion
bool y = bool(my_object); // an explicit conversion does the trick

This still works as normal in places like if and while that require a boolean expression, because the condition of those statements is contextually converted to bool:
// this uses the explicit conversion "implicitly"
if (my_object)
{
    ...
}

This is documented in §4[conv]:

An expression e can be implicitly
  converted to a type T if and only if
  the declaration T t=e; is well-formed,
  for some invented temporary variable t
  (§8.5). Certain language constructs
  require that an expression be
  converted to a Boolean value. An
  expression e appearing in such a
  context is said to be contextually converted to bool and is well-formed
  if and only if the declaration bool t(e); is well-formed, for some
  invented temporary variable t (§8.5). The effect of either
  implicit conversion is the same as performing the
  declaration and initialization and then using the temporary
  variable as the result of the conversion.

(What makes the difference is the use of bool t(e); instead of bool t = e;.)
The places were this contextual conversion to bool happens are:

*

*the conditions of if, while, and for statements;

*the operators of logical negation !, logical conjunction &&, and logical disjunction ||;

*the conditional operator ?:;

*the condition of static_assert;

*the optional constant expression of the noexcept exception specifier;

A: No, a simple bool conversion operator is not, as you can now make evil comparisions between unrelated types. Generally, yes, a conversion function is a-okay. Just use the right one (safe-bool idiom). I can't explain it any better than the given links.

A: The original question was

Is this considered a good practise?

The issue with the safe bool conversion was very relevant in practice, but fortunately has now been addressed by the standards.
But the judgement if this approach is appropriate, is a question of design.
By introducing such a "validity check", effectively you are stating that your objects can be in an invalid state. That is, speaking in the terms of computer science, you added a new separate value to the value domain represented by your objects. A so called bottom value
The most prominent example for a value domain with that propery is the pointer. A pointer can refer to various memory locations, but it also can be NULL (invalid).
Thus we need do ask ourselves: does such a bottom value really reflect the nature of the things we want to model with our classes -- and -- do we really need to cover this aspect of the nature within our model?
Experience shows that bottom values tend to be error prone, easy to forget and generally more of a liability than an asset. If you're able to arrange your code in a way that your objects can not be invalid, your code gets simpler, easier to read, to understand and to maintain..


text:
Q: How do I make wordpress tag input box add a tag by pressing enter key? I have the following text input inside a form that I would like be triggered after I press the enter key.  Please note that I can't use the ID to trigger this code. (ID changes on pageload)
<input type="text" id="cant_use" name="tmp_post_tag" value="" data
taxonomy="post_tag" data-taxtype="flat" class="wpt-new-taxonomy-title js-wpt-
new-taxonomy-title form-control wpt-form-textfield form-textfield textfield"
data-wpt-type="textfield" data-wpt-id="cant_use" data-wpt-autocomplete="off">
autocomplete="off">

The top code actually works IF it is not used inside the form, but on my wordpress site (plugin creates form) it does not.
This is the JS that has worked with an input, but without the form.
 $('input[name="tmp_post_tag"]').keypress(function(event)
 {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13'){
       alert('You pressed a "enter" key in textbox');
    }
 });

What conflicts could it be causing?


text:
Q: Unable to file multiple BLOB to Synapse using data factory I want to copy bulk data from BLOB storage to Azure Synapse with the following structure:
BLOB STORAGE:-
devpresented (Storage account)
        processedout (Container)
                Merge_user (folder)
                    > part-00000-tid-89051a4e7ca02.csv
                Sales_data (folder)
                    > part-00000-tid-5579282100a02.csv

SYNAPSE SQLDW:
SCHEMA:- PIPELINEDEMO
TABLE: Merge_user, Sales_data

Using data factory I want to copy BLOB data to Synapse database as below:
BLOB        >>  SQLDW
Merge_user  >>  PIPELINEDEMO.Merge_user
Sales_data  >>  PIPELINEDEMO.Sales_data

The following doc in mentioned for SQL DB to SQL DW:
https://learn.microsoft.com/en-us/azure/data-factory/tutorial-bulk-copy-portal
However, I didn't find anything for BLOB source in data facory.
Can anyone please suggest, how can I move multiple BLOB files to different tables.

A: If you need to copy the contents of different csv files to different tables in Azure Synapse, then you can enable multiple copy activities within a pipeline.
I create a .csv file, this is the content:
111,222,333,
444,555,666,
777,888,999,

I upload this to my storage account, Then I set this .csv file as the source of the copy activity.

After that, I create a table in azure synapse, and set this as the sink of the copy activity:
create table testbowman4(Prop_0 int, Prop_1 int, Prop_2 int)

At last, trigger this pipeline, you will find the data is in the table:

You can create multiple similar copy activities, and each copy activity performs a copy action from blob to azure synapse.


text:
Q: Google Analytics Embed API issue i created a page on my website that showing my google analytics report. Actually i just modified some of this demo https://ga-dev-tools.appspot.com/embed-api/custom-components/.
It's working good, but when i have too much tables and chart of some dimension and metrics, some tables and data are not appear. Is there anyone know how to fix this, or someone know how to get all the data in a different way?
Here is my code
gapi.analytics.ready(function() {

// authorize google account
gapi.analytics.auth.authorize({
    container: 'embed-api-auth-container',
    clientid: 'xxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com'
});

// view selector
var viewSelector = new gapi.analytics.ViewSelector({
    container: 'view-selector-container'
});

viewSelector.execute();

// date range
var dateRange = {
    'start-date': '7daysAgo',
    'end-date': 'yesterday'
};

// date range selector
var dateRangeSelector = new gapi.analytics.ext.DateRangeSelector({
    container: 'date-range-selector-container'
})
.set(dateRange)
.execute();

// configuration for line chart
var chart1Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:date'
    },
    chart: {
      type: 'LINE',
      options: {
        width: '100%'
      }
    }
};

// configuration for operation system
var chart2Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:operatingSystem',
      sort: '-ga:sessions',
      'max-results': '10'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

var chart3Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:operatingSystem, ga:operatingSystemVersion',
      sort: '-ga:sessions',
      'max-results': '15'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

// config for browser
var chart4Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:browser',
      sort: '-ga:sessions',
      'max-results': '10'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

var chart5Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:browser, ga:browserVersion',
      sort: '-ga:sessions',
      'max-results': '15'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

// mobile
var chart6Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:mobileDeviceBranding',
      sort: '-ga:sessions',
      'max-results': '10'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

var chart7Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:mobileDeviceBranding, ga:mobileDeviceModel',
      sort: '-ga:sessions',
      'max-results': '15'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

// audience
var chart8Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:userAgeBracket',
      sort: '-ga:sessions'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

var chart9Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:userGender',
      sort: '-ga:sessions'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

// Pageviews
var chart10Config = {
    query: {
      metrics: 'ga:pageviews, ga:uniquePageviews, ga:timeOnPage',
      dimensions: 'ga:pagePath, ga:pageTitle',
      sort: '-ga:pageviews',
      'max-results': '20'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

// traffic sources
var chart11Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:fullReferrer',
      sort: '-ga:sessions',
      'max-results': '15'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

var chart12Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:keyword',
      sort: '-ga:sessions',
      'max-results': '15'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

// geo network
var chart13Config = {
    query: {
      metrics: 'ga:sessions',
      dimensions: 'ga:networkLocation',
      sort: '-ga:sessions',
      'max-results': '10'
    },
    chart: {
      type: 'TABLE',
      options: {
        width: '100%'
      }
    }
};

// graph user
var chart14Config = {
    query: {
      metrics: 'ga:users',
      dimensions: 'ga:userType',
      sort: '-ga:users'
    },
    chart: {
      type: 'PIE',
      options: {
        width: '100%'
      }
    }
};

// chart 1
var dataChart = new gapi.analytics.googleCharts.DataChart(chart1Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container'}});

// chart 2 (Operation System)
var dataChart2 = new gapi.analytics.googleCharts.DataChart(chart2Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-2'}});

var dataChart3 = new gapi.analytics.googleCharts.DataChart(chart3Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-3'}});

var dataChart4 = new gapi.analytics.googleCharts.DataChart(chart4Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-4'}});

var dataChart5 = new gapi.analytics.googleCharts.DataChart(chart5Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-5'}});

var dataChart6 = new gapi.analytics.googleCharts.DataChart(chart6Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-6'}});

var dataChart7 = new gapi.analytics.googleCharts.DataChart(chart7Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-7'}});

var dataChart8 = new gapi.analytics.googleCharts.DataChart(chart8Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-8'}});

var dataChart9 = new gapi.analytics.googleCharts.DataChart(chart9Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-9'}});

var dataChart10 = new gapi.analytics.googleCharts.DataChart(chart10Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-10'}});

var dataChart11 = new gapi.analytics.googleCharts.DataChart(chart11Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-11'}});
var dataChart12 = new gapi.analytics.googleCharts.DataChart(chart12Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-12'}});

var dataChart13 = new gapi.analytics.googleCharts.DataChart(chart13Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-13'}});

var dataChart14 = new gapi.analytics.googleCharts.DataChart(chart14Config)
    .set({query: dateRange})
    .set({chart: {container: 'chart-container-user'}});

// date range selector
dateRangeSelector.on('change', function(data) {
    dataChart.set({query: data}).execute();
    dataChart2.set({query: data}).execute();
    dataChart3.set({query: data}).execute();
    dataChart4.set({query: data}).execute();
    dataChart5.set({query: data}).execute();
    dataChart6.set({query: data}).execute();
    dataChart7.set({query: data}).execute();
    dataChart8.set({query: data}).execute();
    dataChart9.set({query: data}).execute();
    dataChart10.set({query: data}).execute();
    dataChart11.set({query: data}).execute();
    dataChart12.set({query: data}).execute();
    dataChart13.set({query: data}).execute();
    dataChart14.set({query: data}).execute();

    var datefield = document.getElementById('from-dates');
    datefield.innerHTML = data['start-date'] + '—' + data['end-date'];
});

// render chart every view changed
viewSelector.on('change', function(ids) {
    dataChart.set({query: {ids: ids}}).execute();
    dataChart2.set({query: {ids: ids}}).execute();
    dataChart3.set({query: {ids: ids}}).execute();
    dataChart4.set({query: {ids: ids}}).execute();
    dataChart5.set({query: {ids: ids}}).execute();
    dataChart6.set({query: {ids: ids}}).execute();
    dataChart7.set({query: {ids: ids}}).execute();
    dataChart8.set({query: {ids: ids}}).execute();
    dataChart9.set({query: {ids: ids}}).execute();
    dataChart10.set({query: {ids: ids}}).execute();
    dataChart11.set({query: {ids: ids}}).execute();
    dataChart12.set({query: {ids: ids}}).execute();
    dataChart13.set({query: {ids: ids}}).execute();
    dataChart14.set({query: {ids: ids}}).execute();
});

});

Is there a way to retrieve all of the data requested until the page fully load and then show them up?


text:
Q: if isinstance(x, list) appending new values from the list overwrites the previous one I'm absolutely new to Python trying to automate some of my stuff.
I'm currently trying to find a way to make a dictionary to a table based on columns from the table itself.
cursor.execute(query)

columns = [col[0] for col in cursor.description]
rows = [dict(zip(columns, row)) for row in cursor.fetchall()]

results = []

for row in rows:
    arg1 = row['arg1']
    arg2 = row['arg2']
    temp = row

    temp['concat'] = (str(arg1) + str(arg2))

    concat = row['concat']

    def map_sth(x):

        return {
            'arg1arg2': ["abcd","efgh"],
            'arg1arg2': "xyz",
                    }[str(x)]

    mapped = map_sth(concat)

    if isinstance(mapped, list):
        for mapping in mapped:
            temp['new_column'] = mapping
            results.append(temp)
    else:
        temp['new_column'] = mapped
        results.append(temp)

df = pandas.DataFrame(results)
df.to_csv("file.csv",index=False)

I debugged the code and it works fine for results with only one item in map_sth
    if isinstance(mapped, list):
        for mapping in mapped:
            temp['new_column'] = mapping
            results.append(temp)
    else:
        temp['new_column'] = mapped
        results.append(temp)

One it gets into isinstance it gives me correct value for the first loop but once entered in the second loop it overwrites both values with the second phrase from map_sth
Any help would be much appreciated as i'm currently stuck :/
Thanks!


text:
Q: Getting null or empty userid in Sinch FATAL EXCEPTION: main
java.lang.IllegalArgumentException: toUserId must not be null or empty
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.call(DefaultCallClient.java:153)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(DefaultCallClient.java:102)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(DefaultCallClient.java:97)
at packagename.SinchService$SinchServiceInterface.callUser(SinchService.java:91)
at packagename.PlaceCallActivity.callButtonClicked(PlaceCallActivity.java:142)
at packagename.PlaceCallActivity.access$000(PlaceCallActivity.java:26)
at packagename.PlaceCallActivity$1.onClick(PlaceCallActivity.java:173)
at android.view.View.performClick(View.java:4802)
at android.view.View$PerformClick.run(View.java:20101)
at android.os.Handler.handleCallback(Handler.java:810)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5532)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)

What could be the possible issues please elaborate tell. I am getting random mobile number from database using json parser request.
private void callButtonClicked() {

        try {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("status",status));
            params.add(new BasicNameValuePair("mobile", callNo));
            JSONObject json = jsonParser.makeHttpRequest(Config.URL_Random, "POST",
                    params);
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                response=json.getString(MOBILE);
            }

        }catch (JSONException e){
            e.printStackTrace();
        }
        String userNo = response;
          Log.d("Response is",userNo);
        try {
            Call call = getSinchServiceInterface().callUser(userNo);
            if (call == null) {
                // Service failed for some reason, show a Toast and abort
                Toast.makeText(this, "Service is not started. Try stopping the service and starting it again before "
                        + "placing a call.", Toast.LENGTH_LONG).show();
                return;
            }
            String callId = call.getCallId();
            Intent callScreen = new Intent(this, CallScreenActivity.class);
            callScreen.putExtra(SinchService.CALL_ID, callId);
            startActivity(callScreen);
        } catch (MissingPermissionException e) {
            ActivityCompat.requestPermissions(this, new String[]{e.getRequiredPermission()}, 0);
        }

    }

I am storing user mobile number at login screen and callno is the number in Textview of LoggedIn No Ok. This json response response=json.getString(MOBILE); will get any random number from a database. So tell me please where i am doing it wrong and also i guess my php api made by another guy who is storing the number giving random number assured me that everything is absolutely fine from there side.

A: seems to me you have empty ot null values in you database, we dont allow emty strong as userid to send to

A: Try this maybe because your callNo is out of scope of callbuttonclicked
Suppose if you have number in textview then you do this inside callbuttonclicked function:
callNo= userNo.getText().toString();
userNo = (TextView) findViewById(R.id.number); --> do this in onCreate method
hope that would resolve your problem.


text:
Q: Parallelizable vs. Parallelable Which sentence is correct and meaningful?

*

*The following computer algorithm is highly parallelizable.

*The following computer algorithm is highly parallelable.

A: An article in Wikipedia uses various derivatives of "parallelize":
parallelizable
parallelizability
parallelization
parallelizable
so it looks like that's the customary term.
Wikipedia "Parallel algorithm"
I have seen "parallelable" used in reference to electronic inverters, meaning they can be connected in parallel for higher power output, so it's a valid word, but maybe in other contexts.

A: According to  this Google Ngram It seems like parallelizable is far more common, so I believe parallelizable should be preferred over parallelable.


text:
Q: Uploading multifiles I can't upload multiple files. I have a table of 4 items, each may have an uploaded file.
How should the code be?
$target_dir = "uploads/";
    foreach ($_FILES as $f => $a) {
        if ($a["name"]) {
            $target_file = $target_dir . "paper_" . $id . "_" . $f[12];
            $file_name = basename($a["name"]);
            $uploadOk = 1;
            $imageFileType = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
             && $imageFileType != "pdf" && $imageFileType != "doc" && $imageFileType != "docx") {
                echo "Sorry, only JPG, JPEG, PNG, PDF, DOC and DOCX files are allowed. Your type is $imageFileType ";
                continue;
            }
            if ($a["size"] > 1024 * 1024 * 4) {
                echo "Sorry, your file is too large. Max is 4 MB";
                continue;
            }
            $col = "";
            switch ($f[12]) {
                case 1:
                    $col = "path_salary_def";
                    break;
                case 2:
                    $col = "path_social";
                    break;
                case 3:
                    $col = "path_identification";
                    break;
                case 4:
                    $col = "path_accom";
                    break;
                default:
                    die("invalid column");
            }
            $bol = substr($col, 5);
            if (move_uploaded_file($a["tmp_name"], $target_file)) {
                $query = "update papers SET $col = '$target_file', $bol = 1 WHERE id = " . $id;
                $result = mysqli_query($con,$query) or die ("Error in the data table 5");
                echo "The file $file_name has been uploaded.<br/>";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
    }

A: If your $_FILES array is empty perhaps  you omitted the enctype attribute form the form.
It should look like:
<form action="yourAction.php" method="POST" enctype="multipart/form-data">


text:
Q: time series for binary shapes I have been working around extracting the time series from shapes based on distances to center of mass clockwise starting from angle 0 to 360.
My Implementation that arranges contour points based on their angle to the  [1,0], vector might be good for some shapes but is not useful for shapes that has much articulation. Consider the following code:

im = Image.open(os.path.join(path,filename))
im = im.filter(ifilter.MedianFilter)
contim = im.filter(ifilter.CONTOUR)
contim = contim[1:-1,1:-1] # this is because borders are extracted here as contours
contpts = np.where(contim ==0)
contpts = np.vstack((contpts[0],contpts[1])) # Just need to arrange these points clockwise with respect to the center of mass of the shape

Can anyone direct me to how I can extract that feature from any shape where I can start from a point and keep going along the contour to extract all the distances to the center of mass of the shape.
For more information about the feature, please view this paper: "LB_Keogh Supports Exact Indexing of Shapes under Rotation Invariance with Arbitrary Representations and Distance Measures"

A: If I understood, there's a geometrical figure in a discretized plane, represented as a matrix. If the entry is 1, you're inside the figure. If it's 0, you're outside. He wants to determine de distance between the edge of the figure and the center of the figure for all points in the edge. He parametrized it with a polar coordinate system. The center of the figure is the origin and now he wants to get the distance to the border as a function of the angle. This is what he calls his "time series".
Is this correct?
If yes, couldn't you just:
1. determine the center of mass,
2. reposition the origin to match the center of mass.
3. start angle at 0
4. r = 0
5. for each angle in [0,1,...,360]
      1. If you're in inside the figure, increase r until you reach the border.
      2. If you're outside the figure, decrease r until you reach the border.
      3. When you reach the border, d(angle) = r

It the figure have a more or less continuous border, this will follow the contour.
Would this work?


text:
Q: What is difference between path and connection in iSCSI volume? we have connected few Iscsi volumes. When we execute

Get-IscsiConnection

it shows connection between target IP address and initiator IP address.
But when we execute

mpclaim.exe -s -d

It shows the different values. When i enquired about this my seniors said that this is path not connection.
What is Path ? How it differs from connection?

A: Get-IscsiConnection

shows (all) iSCSI connections
mpclaim

shows multipaths I/O devices (incl. iSCSI)
Get-iSCSISession showing the exact connection, but not the MPIO policy which is used for iSCSI volume. By executing - mpclaim.exe -s -d you can find out the Load Balance Policy, and a number of the system disk. If you will specify needed Disk, you will see how many paths are active/standby, active/active or active/optimized.


text:
Q: Concatenation of strings in a list of dictionary based on matching pattern in python I am trying to find a pattern 'ABC' in the values of dictionary of list. If the 'ABC' exist in the key value pair then it will concatenate the values of key 'b' and the rest of the key value pair will comes from the first dictionary till find the next 'ABC' in the dictionary 'b' of list of other elements
Sample Data:
L = [{'a': 0, 'b': 'radndaos43', 'c': 234},
     {'a': 1, 'b': 'lABChfgdd65a', 'c': 90011},
     {'a': 2, 'b': 'ddasda423sdABC', 'c': 324},
     {'a': 3, 'b': 'ddas236dasd', 'c': 123},
     {'a': 4, 'b': 'ddasd234asdABC', 'c': 900},
     {'a': 5, 'b': 'ddasd678hfasd', 'c': 342},
     {'a': 6, 'b': 'ddasd234dasdasdABC', 'c': 567}]

So, in the first element there is no 'ABC', so it should add the dictionary as it is and samething applies with the next one as there is 'ABC' but in the next element there is also 'ABC'. 3rd and 4the element will concatenate and 5th and 6th will also concatenate.
Current Output:
[{'a': 1, 'b': 'lABChfgdd65a', 'c': 90011},
{'a': 2, 'b': 'ddasda423sdABC ddas236dasd','c': 324},
{'a': 4, 'b': 'ddasd234asdABC ddasd678hfasd', 'c': 900}]

Expected Output:
[{'a': 0, 'b': 'radndaos43', 'c': 234},
{'a': 1, 'b': 'lABChfgdd65a', 'c': 90011},
{'a': 2, 'b': 'ddasda423sdABC ddas236dasd','c': 324},
{'a': 4, 'b': 'ddasd234asdABC ddasd678hfasd', 'c': 900},
{'a': 6, 'b': 'ddasd234dasdasdABC', 'c': 567}]

1st and 6th element is missing from the output
This is what I tried so far,
updated_list = []
dict_holder = {}
for i in range(len(L)):
    if 'ABC' in L[i]['b'] and not dict_holder:
        dict_holder.update(L[i])
    elif 'ABC' not in L[i]['b'] and dict_holder:
        dict_holder.update({'b': dict_holder['b'] + ' ' + L[i]['b']})
    elif 'ABC' in L[i]['b'] and dict_holder:
        updated_list.append(dict_holder)
        dict_holder = {}
        dict_holder.update(L[i])

print(updated_list)

A: Here is how you would solve your problem:
for element in L: # don't need to use range() can access the element directly in the for loop as it is an iterable
    if 'ABC' in element['b'] and not dict_holder:
        dict_holder.update(element)
    elif 'ABC' not in element['b'] and dict_holder:
        dict_holder.update({'b': dict_holder['b'] + ' ' + element['b']})
    elif 'ABC' in element['b'] and dict_holder:
        dict_holder = {} # changed this ordering as you were adding the previous dict_holer to updated_list then adding a new element
        dict_holder.update(element)
        updated_list.append(dict_holder)
    else: # for 234 which has no ABC in it
        dict_holder.update(element)
        updated_list.append(element)

I included one code improvement to make it more readable (for loop iteration https://www.w3schools.com/python/python_for_loops.asp)


text:
Q: Avoid slow looping when plotting irregular raster plot using patches.Rectangle I've written a code to make an irregular raster plot (i.e. one in which the size of the raster rectangles is variable).  Here is a minimum reproducible example below.
The problem is that looping over the blocks is very slow for my example (each plot has a lot of rectangles and there are a lot of plots to make).  I tried to convert the coordinates into a list of tuples, but that threw up an error.
Is it possible to get patches.Rectangle to return a list of patches, rather than one, so I can get rid of the loop over the patches and speed up the code?
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
import matplotlib.colorbar as cbar

fig,ax=plt.subplots(1)

rng=6
plt.ylim(0,rng)
plt.xlim(0,rng)

N = 30
x = np.random.rand(N)*rng
y = np.random.rand(N)*rng
s = np.random.rand(N)
colors=np.random.rand(N)
normal = plt.Normalize(0,1) # my numbers from 0-1

cmap=plt.cm.RdYlBu_r
c=cmap(colors)

for i in range(N):
    val=0.5
    rect=patches.Rectangle((x[i],y[i]),s[i],s[i],
                            edgecolor='black',
                            linewidth = 1,
                            facecolor = c[i],
                            )
    ax.add_patch(rect)

cax, _ = cbar.make_axes(ax)
cb2 = cbar.ColorbarBase(cax, cmap=cmap,norm=normal)

plt.savefig("test.png")

output:

A: One sentence summary: Use a PolyCollection.

Using a collection to draw many shapes is sure more efficient than drawing individual rectangles. The other answer suggests to use a PatchCollection. Even more efficient is the use of a PolyCollection.
The reason is twofold:

*

*In a PolyCollection you do not need to create each patch individually

*It is sufficient to define exactly one shape, and only specify the sizes, colors and offsets.

I made some modifications to the code concerning the color definition (best let the collection do it for you) and the colorbar (use the collection, instead of an independen colorbar)
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
from matplotlib.collections import PatchCollection, PolyCollection
import matplotlib.transforms as mtrans

PatchCollection:
def patchcoll(N, show=False):
    fig,ax=plt.subplots()

    rng=6
    plt.ylim(0,rng+1)
    plt.xlim(0,rng+1)

    x = np.random.rand(N)*rng
    y = np.random.rand(N)*rng
    s = np.random.rand(N)
    c = np.random.rand(N)
    norm = plt.Normalize(0,1) # my numbers from 0-1
    cmap=plt.cm.RdYlBu_r

    pat = []

    for i in range(N):
        rect=patches.Rectangle((x[i],y[i]),s[i],s[i])
        pat.append(rect)

    col = PatchCollection(pat, cmap=cmap, norm=norm)
    col.set_array(c)
    col.set_edgecolor('k')
    col.set_linewidth(1.)
    ax.add_collection(col)

    fig.colorbar(col)
    if show:
        plt.show()
    else:
        fig.canvas.draw()

    plt.close()

PolyCollection:
def polycoll(N, show=False):
    fig,ax=plt.subplots()

    rng=6
    plt.ylim(0,rng)
    plt.xlim(0,rng)

    x = np.random.rand(N)*rng
    y = np.random.rand(N)*rng
    s = np.random.rand(N)
    c = np.random.rand(N)
    norm = plt.Normalize(0,1) # my numbers from 0-1
    cmap=plt.cm.RdYlBu_r

    offsets = np.c_[x,y]
    verts = list(zip([0,1,1,0,0], [0,0,1,1,0]))

    col = PolyCollection([verts], sizes=s, offsets=offsets,
                         transOffset=mtrans.IdentityTransform(),
                         offset_position="data", cmap=cmap, norm=norm)

    col.set_array(c)
    col.set_edgecolor('k')
    col.set_linewidth(1.)
    ax.add_collection(col)

    fig.colorbar(col)

    if show:
        plt.show()
    else:
        fig.canvas.draw()

    plt.close()

Single Rectangles:
def rectangles(N, show=False):
    fig,ax=plt.subplots()

    rng=6
    plt.ylim(0,rng)
    plt.xlim(0,rng)

    x = np.random.rand(N)*rng
    y = np.random.rand(N)*rng
    s = np.random.rand(N)
    c = np.random.rand(N)
    norm = plt.Normalize(0,1) # my numbers from 0-1

    cmap=plt.cm.RdYlBu_r

    for i in range(N):
        rect=patches.Rectangle((x[i],y[i]),s[i],s[i],
                               facecolor=cmap(norm(c[i])), edgecolor="k", linewidth=1)
        ax.add_patch(rect)

    sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
    sm.set_array([])
    fig.colorbar(sm)

    if show:
        plt.show()
    else:
        fig.canvas.draw()

    plt.close()

Run all:
patchcoll(30, show=True)
polycoll(30,show=True)
rectangles(30,show=True)

Timing
For N=1000 I get
%timeit(rectangles(1000))
757 ms ± 4.26 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit(patchcoll(1000))
184 ms ± 462 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit(polycoll(1000))
58.3 ms ± 146 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

So in this case using a PatchCollection is a factor 3 more efficient than single rectangles, and using a PolyCollection is a factor 3 more efficient than a PatchCollection.
Overview of the time it takes to create a figure with N rectangles with the 3 different methods from above:

A: I don't know exactly how to time it, but it seems like that would be the perfect job for a PatchCollection. Does this speed up your graph at all?
EDIT: crude tests seem to show a gain of performance with PatchCollection, especially when N is large. I tested here with N=1000:
%timeit withCollection()
316 ms ± 5.41 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit withoutCollection()
772 ms ± 30.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Full code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
import matplotlib.colorbar as cbar
from matplotlib.collections import PatchCollection

fig,ax=plt.subplots()

rng=6
plt.ylim(0,rng)
plt.xlim(0,rng)

N = 30
x = np.random.rand(N)*rng
y = np.random.rand(N)*rng
s = np.random.rand(N)
colors=np.random.rand(N)
normal = plt.Normalize(0,1) # my numbers from 0-1

cmap=plt.cm.RdYlBu_r
c=cmap(colors)
pat = []

for i in range(N):
    rect=patches.Rectangle((x[i],y[i]),s[i],s[i])
    pat.append(rect)

col = PatchCollection(pat)
col.set_facecolor(c)
col.set_edgecolor('k')
col.set_linewidth(1.)
ax.add_collection(col)

cax, _ = cbar.make_axes(ax)
cb2 = cbar.ColorbarBase(cax, cmap=cmap,norm=normal)


text:
Q: Build WAR file from Graddle Project on InteliJ IDEA Community (excluding resources from build) I developed a Spring Application using InteliJ IDEA community version.
Community edition don't have support to WAR artifacts, so I have to get it manually.
I've found how to do it on maven projects, but mine is a graddle project. So, how can I build a WAR from my graddle project?
In maven projects you can configure a maven run that uses wagon-maven-plugin in order to obtain a WAR file. Is it possible to make the same with graddle?
EDIT
I've been testing with bootWar and bootJar in order to make both (Jar and War).
Ok, it worked. My problem now is that these two pluguins are actually packing my resources diretory.
I've tried to use exclude but it didn't worked.
Thats what i'm doing:
bootJar {
    mainClassName = 'Server.Application'
    exclude("/src/resources/**")
    version =  '0.1.7'
}

bootWar {
    mainClassName = 'Server.Application'
    exclude("/src/resources/**")
    version = '0.1.3'
}

And my project structure is like:

*

*libs

*src

*

*main

*

*java

*Server

*resources

EDIT 2 - Final aproach
In order to keep the resouces out of the build I delete them before building:
bootJar {
    mainClassName = 'FitServer.Application'
    setDestinationDir(new File ('build/war'))
    version = '0.1.2'

    doFirst {
        delete('build/resources')
    }
}

A: As per Gradle Guide there is a war plugin for building Java web applications, and the community supplies an excellent plugin called gretty for testing and deploying web applications on Jetty or Tomcat.
You can use this war plugin in build.gradle file.


text:
Q: Periods and L-values of modular forms Suppose $f$ is a modular form of weight $k \ge 2$.
It's "well-known" that there are "periods" $\Omega_-$ and $\Omega_+ \in \mathbb{C}$, such that the $L$-values $L(f, \chi, j)$, for $\chi$ a Dirichlet character and $1 \le j \le k-1$, are $(2\pi i)^j$ times an algebraic multiple of one of $\Omega_{\pm}$.
What is the correct statement of this "well known" result? Colmez claims in his Bourbaki seminar on $p$-adic BSD (here, Section 3.1.3) that
$$L(f, \chi, j) \in \begin{cases} \overline{\mathbb{Q}} \cdot (2\pi i)^j \Omega_+ & \text{if $\chi(-1) = (-1)^j$} \\ \overline{\mathbb{Q}} \cdot (2 \pi i)^j\Omega_- & \text{if $\chi(-1) =-(-1)^{j}$.}\end{cases} $$
On the other hand, Vatsal claims in Theorem 0.1 of this paper (in which he defines canonical choices for the periods $\Omega_{\pm}$ up to $p$-adic units for a given prime $p$) that the conditions should be
$$L(f, \chi, j) \in \begin{cases} \overline{\mathbb{Q}} \cdot (2\pi i)^j \Omega_+ & \text{if $\chi(-1) = 1$} \\ \overline{\mathbb{Q}} \cdot (2 \pi i)^j\Omega_- & \text{if $\chi(-1) =-1$.}\end{cases} $$
Vatsal's statement is repeated verbatim in the MathSciNet review of the paper (here if you have an institutional subscription).
These can't both be right, surely? If $k = 2$ then the only possibility for $j$ is $1$, so the two claims can be reconciled by simply switching the labelling of the two periods; but for $k \ge 3$ then the only way they can both hold is if $\Omega_+ / \Omega_-$ is algebraic, which I gather isn't expected to be the case unless $f$ is CM.
Colmez doesn't give a reference, while Vatsal cites a 1976 paper of Shimura, which I haven't been able to get hold of to check the exact statement.
Which of these two statements are correct? Or are they both correct but I've misunderstood them?

A: Check out Manin's paper Periods of parabolic forms and $p$-adic Hecke series. He only deals with level 1 and even weight, but this is enough to know that Vatsal's statement is not the right one (though not enough to fully confirm Colmez's statement, though it's true as given in Theorem 1 of Shimura's paper you can't get your hands on; you should also be able to dig it out of Mazur–Tate–Teitelbaum or Emerton–Pollack–Weston, which generalizes Vatsal). In particular, see section 1.2: The Periods Theorem of Manin's paper.
Update: In fact, the statement in the form you're looking for is written down in Theorem 1(ii) of Shimura's On the periods of modular forms (doi:10.1007/BF01391466), where he even tells you what you can take as $\Omega_\pm$ (and the result in the weight 2 case in Shimura's aforementioned 1976 paper was still conditional on a result proved in this 1977 paper).

A: Vatsal actually would write $(-2\pi i)^j$, so both his and Colmez's are the same correct statement.


text:
Q: How to pass value of a button into a function when it's clicked So I'm trying to create a quiz for a class of mine. I've created an array of objects to hold my questions, answers, and what the correct answer is. I'm using a forEach to generate buttons for each "answer" option at the specified index. I've added and onClick event to attempt to pass the value of the button into a function but I cannot seem to figure out what's the best way to go about doing this. I've included some of my code below to hopefully help.
var answers = quiz[index].answers;
answers.forEach(function(element) {
    var optionButton = document.createElement("button");
    optionButton.innerHTML = element;
    optionButton.className = "btn";
    optionButton.setAttribute("option-answer", element)
    optionButton.setAttribute("onClick", "verifyAnswer()")
    questionTitle.appendChild(optionButton);
})

A: just pass the argument in your function call. here i use arrow function:
optionButton.addEventListener("click", () => {verifyAnswer(element)})

A: Instead of making an onClick attribute, you could use an event listener to do additional actions when the button is clicked:
optionButton.addEventListener("click", function(){
   verifyAnswer(currentIndex);
});

A: You could add the info using dataset and then recover it in the EventListener

const answers=["option 1","option 2","option 3"];

answers.forEach(function(element) {
    let optionButton = document.createElement("button");
    optionButton.innerHTML = element;
    optionButton.className = "btn";
    //Add data info
    optionButton.dataset.answer=element;
    optionButton.addEventListener("click", verifyAnswer);
    document.getElementById("container").appendChild(optionButton);
})

function verifyAnswer(event){
    clickedElement = event.target || event.srcElement;
  //getting info in the element
    alert(clickedElement.dataset.answer);
}
<div id="container">

</div>

Or if your answer data is the same as the text inside de button you can also use this
function verifyWithText(event){
    clickedElement = event.target || event.srcElement;
    alert(clickedElement.innerHTML);
}

Hope it helps

A: You could keep track of the answer index when creating a button, either via a data- attribute or directly in the function call.
var answers = quiz[index].answers;
answers.forEach(function(element, currentIndex) {
    var optionButton = document.createElement("button");
    optionButton.innerHTML = element;
    optionButton.className = "btn";
    optionButton.setAttribute("option-answer", element)
    optionButton.setAttribute("onClick", "verifyAnswer(" + currentIndex + ")")
    questionTitle.appendChild(optionButton);
})

And then, in your function call, you can retrieve the answer using a simple accessor.
function verifyAnswer(index) {
    const answer = answers[index]
    /* ... */
}

A: You can do it with passing argument in your verifyAnswer function
"verifyAnswer("+element+")"

where "element" is argument that you want to provide it can be anything.
The other way is with listener
optionButton.addEventListener('click', function(){
    verifyAnswer(element);
});


text:
Q: Set maximum height and width of Scaffold? I am trying to build a Flutter web app. My app is currently optimised for phones & tablets however it isn't for desktop. What i'm trying to achieve is if the user opens the website it should show the app like a tablet. and the left and right to be white or a different background color. Something similar to what Instagram has for its iPad version of the app.

A: Place your whole app inside a Container with a black Background. Set a certain ratio at which point the black background image gets shown (Width and Height are MediaQuery.of(context).size.width/height)


text:
Q: Two functions in one plot with different y-axis scales? I have two function that I plot over the same domain. They have quite different ranges. I wanted to show them together in one in one plot which displayed both over their full range. I solved the problem by overlapping the two which is not seem elegant to me.
This plots a quite nice figure but is there a better way to do it?
Clear[c, L, Δν, R]
c =  299792458;
L = 3440*10^(-9);
Δν = c/(2L);
R = 0.9;
ReflectionCoefficient[ν_] = R (Exp[I 2 Pi ν /Δν ]-1)/(1-R^2 Exp[ν I 2Pi /(Δν)]);

Phase =
  Plot[Abs[ReflectionCoefficient[ν*c/(2L)]], {ν, 0. 5 + 2L/c, 1.5 + 2L/c},
    PlotRange -> {{0.5, 1.5}, {-0.1, 1.1}},
    PlotStyle -> {Red, Thick},
    LabelStyle -> Directive[Bold, 12, Black],
    FrameLabel -> {{"Intensity", "Phase in °"}, {"Free Spectral Range", ""}},
    ImagePadding -> True,
    ImageSize -> 500,
    Frame -> {True, True, True, True},
    FrameStyle -> {Black, Red, Black, Transparent},
    FrameTicks ->
      {{All, {{0.025, "-150"}}}, {True, True}},
    FrameStyle -> Directive[22]]

Intensity =
  Plot[Arg[ReflectionCoefficient[ν * c/(2L)]]*360/(2Pi), {ν, 0.5 +  2L/c , 1.5 + 2L/c},
    PlotRange->{{0.5,1.5},{-190,190}},
    LabelStyle->Directive[Bold,12,Black],
    FrameLabel->{{"Intensity","Phase in °"},{"Free Spectral Range",""}},
    ImagePadding->True,
    ImageSize->500,
    Frame->{True, True, True, True},
    FrameStyle -> {Black, Transparent, Transparent, Blue},
    FrameTicks ->
      {{{{0, "0.2"}, {160, "1.0"}}, {{0, "0"}, {90, "90"},{180, "180"}, {-90, "-90"}, {-180, "-180"}}},
       {True,True}},
    FrameStyle -> Directive[22],
    PlotStyle -> {Thick ,Blue}]

PowerPlot = Overlay[{Intensity, Phase}, Alignment->Left]

Edit by User:
My goal is to simplify the workflow to combine the two plots for creating a plot with two vertical axes.
Do you have a better idea?

End result:

A: Similar question answered on this post.
Simple Solution
Plot your functions as usual, keep the axes styling and labeling for the end, instead of FrameTicks use Ticks :
c = 299792458;
L = 3440*10^(-9);
\[CapitalDelta]\[Nu] = c/(2 L);
R = 0.9;
ReflectionCoefficient[\[Nu]_] =
  R (Exp[I 2 Pi \[Nu]/\[CapitalDelta]\[Nu]] - 1)/(1 -
      R^2 Exp[\[Nu] I 2 Pi/(\[CapitalDelta]\[Nu])]);

p1 = Plot[
  Abs[ReflectionCoefficient[\[Nu]*c/(2 L)]], {\[Nu], 0.5 + 2 L/c,
   1.5 + 2 L/c}, PlotRange -> {{0.5, 1.5}, {-0.1, 1.1}},
  PlotStyle -> {Red, Thick}]

p2 = Plot[Arg[ReflectionCoefficient[\[Nu]*c/(2 L)]]*360/(2 Pi), {\[Nu],
  0.5 + 2 L/c, 1.5 + 2 L/c}, PlotRange -> {{0.5, 1.5}, {-190, 190}},
 PlotStyle -> {Blue, Thick},
 Ticks -> {Automatic, {-180, -90, 0, 90, 180}}]

Outputs:

Extract PlotRange for the plots:
p1range = AbsoluteOptions[p1, PlotRange][[1, 2, 2]];
(*Out: {-0.1, 1.1} *)

p2range = AbsoluteOptions[p2, PlotRange][[1, 2, 2]];
(*Out: {-190., 190.} *)

Rescale only the Y-values for p2 base on p1 Y-axis:
p2[[1]] = Replace[p2[[1]], {x_, y_} :> {x, Rescale[y, p2range, p1range]}, All];

Extract the p2 ticks and rescale them base on p1 Y-axis:
p2ticks = Cases[AbsoluteOptions[p2, Ticks][[1, 2, 2]], {_, x_ /; x != "", __} -> x, All]
(*Out: {-180., -90., 0., 90., 180.} *)

p2ticks = Transpose@Append[{Rescale[p2ticks, p2range, p1range]}, p2ticks]
(*Out: {{-0.0684211, -180.}, {0.215789, -90.}, {0.5, 0.}, ... } *)

Combine the plots with Show with styling options (Show accepts any option that Plot accpets):
Show[p1, p2, Frame -> True,
 FrameTicks -> {{Automatic, p2ticks}, {Automatic, None}},
 FrameLabel -> {{"Intensity",
    "Phase in \[Degree]"}, {"Free Spectral Range", ""}},
 FrameStyle -> {{Red, Blue}, {Black, Black}}]

Output:

All the code tested on Mathematica 12.2.

A: I use ResourceFunction["CombinePlots"]. It is quite easy and more elegant.
Phase = Plot[
  Abs[ReflectionCoefficient[\[Nu]*c/(2 L)]], {\[Nu], 0. 5 + 2 L/c,
   1.5 + 2 L/c}, PlotRange -> {{0.5, 1.5}, {-0.1, 1.1}},
  PlotStyle -> {Red, Thick}, LabelStyle -> Directive[Bold, 12, Black],
   FrameLabel -> {{"Intensity",
     "Phase in \[Degree]"}, {"Free Spectral Range", ""}},
  ImagePadding -> True, ImageSize -> 500,
  Frame -> {True, True, True, True},
  FrameStyle -> {Black, Red, Black, Transparent},
  FrameTicks -> {{All, {{0.025, "-150"}}}, {True, True}},
  FrameStyle -> Directive[22]]

Intensity =
 Plot[Arg[ReflectionCoefficient[\[Nu]*c/(2 L)]]*360/(2 Pi), {\[Nu],
   0.5 + 2 L/c, 1.5 + 2 L/c}, PlotRange -> {{0.5, 1.5}, {-190, 190}},
  LabelStyle -> Directive[Bold, 12, Black],
  FrameLabel -> {{"Intensity",
     "Phase in \[Degree]"}, {"Free Spectral Range", ""}},
  ImagePadding -> True, ImageSize -> 500, Frame -> True,
  FrameStyle -> {Black, Blue, Transparent, Transparent},
  FrameTicks -> {{{{0, "0.2"}, {160, "1.0"}}, {{0, "0"}, {90,
       "90"}, {180, "180"}, {-90, "-90"}, {-180, "-180"}}}, {True,
     True}}, FrameStyle -> Directive[22], PlotStyle -> {Thick, Blue}]

then
ResourceFunction["CombinePlots"][Phase, Intensity,
 "AxesSides" -> "TwoY"]

Plot


text:
Q: Nuget xml file dependency I have a dependency on a config file/xml file that I am wrapping up into a nuget package, having googled this and found a SO post or two, is this even possible? I want the project referencing the nuget package to have the config/xml file copied to the debug/release output folder on build to enable it to function properly.
Related SO posts:
Copy xml from nuget dependency to output
NuGet doesn't copy config file
http://blog.nuget.org/20160126/nuget-contentFiles-demystified.html
I have tried the tips/suggestions mentioned in the above posts/blogs, but no such luck.
Is this even possible? If so, how?

A: The answer, as it turns out, is to put the xml file in as a "content" and then use an install.ps1 script in the nuget "tools" directory to set the file to "Copy To Output". The important thing to note is that this script only gets executed in visual studio, so any content files must be checked in/source controlled, so that any build server has the content files when the server checks it out. A small but incredibly important detail!!
The script I use to set the content files as copy to output:
param($installPath, $toolsPath, $package, $project)

function SetFilePropertiesRecursivelyByFolderName
{
    $folderKind = "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}"; #Physical Folder
    foreach ($subItem in $args[0].ProjectItems)
    {
        $path = $args[1]
        if ($subItem.Kind -eq $folderKind)
        {
            SetFilePropertiesRecursively $subItem ("{0}{1}{2}" -f $path, $args[0].Name, "\")
        }
        else
        {
            Write-Host -NoNewLine ("{0}{1}{2}" -f $path, $args[0].Name, "\")
            SetFileProperties $subItem 2 2 ""
        }
    }
}

function SetFileProperties
{
    param([__ComObject]$item, [int]$buildAction, [int]$copyTo, [string]$customTool)
    Write-Host $item.Name
    Write-Host "  Setting Build Action to Content"
    $item.Properties.Item("BuildAction").Value = $buildAction
    Write-Host "  Setting Copy To Output Directory to Copy if newer"
    $item.Properties.Item("CopyToOutputDirectory").Value = $copyTo
    Write-Host "  Setting Custom Tool to blank"
    $item.Properties.Item("CustomTool").Value = $customTool
}

function SetIndividualFileProperties
{
    param([string]$fileName)
    Write-Host $fileName
    $file1 = $project.ProjectItems.Item($fileName)
    $file1.Properties.Item("CopyToOutputDirectory").Value = 2
    $file1.Properties.Item("BuildAction").Value = 2
}

#SetFilePropertiesRecursivelyByFolderName $project.ProjectItems.Item("FolderName")
#SetIndividualFileProperties "FileName.ext"

EDIT
As it was pointed out that folderKind wasnt very clear (the guid or purpose at least), there is a link on microsoft site for the list of supported visual studio guids that define sln/project structures i.e. for physical file/folders and many other elements. This can be found here: https://learn.microsoft.com/en-us/visualstudio/extensibility/ide-guids?view=vs-2017
This information is mostly unnecessary as the script above should work as is, but provided for further reading/background material!


text:
Q: Unable to find href of new window using javascript I am using below mentioned script to get href of new opened window, but its not working
Browser FF 7, IE 9, WIN 7
Can someone please let me know what's wrong in the script
Thanks in Advance
Akhil

A: You can't get the URL of sites that are in a different domain or protocol as the script that you are running.  It is due to cross-domain restrictions. Chrome gives you the following error:
Unsafe JavaScript attempt to access frame with URL http://www.thesun.co.uk/sol/homepage/ from frame with URL http://fiddle.jshell.net/_display/. Domains, protocols and ports must match.

A: I think that it might be because the variable is not set yet. I think you might need a callback to say that the dom is ready for the new window.


text:
Q: Duplicate field name problem in a nested multi-mapping Dapper pagination query I've ran into an issue when trying to do multi-mapping using Dapper, for pagination queries.
Because I am using a nested query in this pagination scenario, there are multiple tables within the nested query that I must join to get my multi-mapped data, but some of these tables will share some fields of the same name which you can see in my example query below (e.g. id, displayname and email):
q = @"select * from (select p.id, p.title, p.etc...,
u1.id, u1.displayname, u1.email,
u2.id, u2.displayname, u2.email,
t.id, t.name,
row_number() over (order by " + sort.ToPostSortSqlClause() + ") as rownum" +
" from posts p" +
" join users u1 on p.owneruserid = u1.id" +
" join users u2 on p.lastediteduserid = u2.id" +
" join topics t on p.topicid = t.id" +
") seq where seq.rownum between @pLower and @pUpper";

In the example above you can see that within the nested query, there are going to be problems with the fields id (appears in the posts table, both users table joins and the topics table join), and also displayname and email (appear in both users table joins).
The only workaround I have thought of so far involves casting each of these 'problem' fields as a different name, but this then involves the very messy process of creating dummy properties in the affected models, so multimapping can map into these, and editing the 'real' properties in my models to also check the dummy property for a value if the real value has not been set.
Also, in the above scenario I would have to create x dummy properties where x is the number of joins I may have on the same table within a query (in this example, 2 joins on the same Users table, therefore requiring 2 uniquely named dummy properties just for Dapper mapping purposes).
This is obviously not ideal and I'm sure would have knock on problems and more untidyness as I created more of these multi-mapping pagination queries.
I'm hoping there is nice, clean solution to this problem?

A: There are 2 options I can think of:
option 1: join back to your extended properties outside of your nested query:
select s.*, t1.*, t2.* from
(
select s.*, ROW_NUMBER() OVER (order by somecol) AS RowNumber from Something s
) as X
left join Table t1 on Id = x.SomeId
left join Table t2 on Id = x.SomeOtherId

option 2: Extend SqlBuilder to handle column aliasing:
select s.*, /**unalias(Table,t1)**/, /**unalias(Table,t2)**/ from
        (
        select s.*, /**alias(Table,t1)**/, /**alias(Table,t2)**/ ROW_NUMBER() OVER (order by somecol) AS RowNumber from Something s
        left join Table t1 on Id = x.SomeId
        left join Table t2 on Id = x.SomeOtherId
        ) as X

Then define the alias macro to query and cache a list of columns from the db using INFORMATION_SCHEMA.COLUMNS and simply add a 'column as column_t1` string for each column.
Unalias can do the reverse quite simply.


text:
Q: Calculate minimum angle to rotate arrow to token I am developing a platform game, and I would like there to be an arrow pointing to a token:

Just snapping the arrow to the token is fine - everything works correctly:
const dist_x = player.x - token.x
const dist_y = player.y - token.y
const angle = Math.atan2(dist_y, dist_x)

arrow.angle = angle

But the problem is that I would like the arrow to swing around the token as shown below. It works OK, but when the angle of the arrow is near 360 and the angle of the token is near 0, the code thinks that the arrow needs to swing all the way around to zero - as opposed to just adding up a bit and nicely looping around. This is my code:
const dist_x = player.x - token.x
const dist_y = player.y - token.y
const angle = Math.atan2(dist_y, dist_x) // angle between arrow & token

arrow.angle += arrow.rot_speed // acceleration
arrow.rot_speed *= .9 // slowly calm down

// distance between goal angle of arrow and angle at the moment
const angle_dist = angle - arrow.angle

// move in that direction
arrow.rot_speed += angle_dist

This problem has been a large stopping blocker for me on multiple occasions so I would appreciate any help.

A: To fix something like this, you'd need to check if the difference of the angle you're swinging to is below 180, and if it's not, add 360 to the angle you're swinging to. I think that would fix the part where it would swing around. I don't know how you'd implement this in your code, but this is the general solution I came across on previous experiences.
Ofcourse, you'd need to convert all of this into radians :D

A: I am not sure whether this helps. Suppose that there are values of dist_x and dist_y used to get the angle back using atan2() as follow
N = 8
r = 1
console.log("angle dist_x dist_y atan2 angle")
for(i = 0; i < N; i++)  {
  q = (i / 8) * 2 * Math.PI
  dist_x = r * Math.cos(q)
  dist_y = r * Math.sin(q)
  theta = Math.atan2(dist_y, dist_x)
  theta2 = theta
  if(q > Math.PI) {
    theta2 += 2 * Math.PI
  }
  console.log(
    q.toFixed(3),
    dist_x.toFixed(3),
    dist_y.toFixed(3),
    theta.toFixed(3),
    theta2.toFixed(3)
  )
}

that produces
angle   dist_x  dist_y  atan2  angle
0.000   1.000   0.000   0.000  0.000
0.785   0.707   0.707   0.785  0.785
1.571   0.000   1.000   1.571  1.571
2.356  -0.707   0.707   2.356  2.356
3.142  -1.000   0.000   3.142  3.142
3.927  -0.707  -0.707  -2.356  3.927   <---
4.712  -0.000  -1.000  -1.571  4.712   <---
5.498   0.707  -0.707  -0.785  5.498   <---

which is showing that results in 3rd and 4th quadrants

3rd quadrant: dist_x < 0, dist_y < 0
4rd quadrant: dist_x > 0, dist_y < 0

must be added with 2 PI to get all angle between 0 and 2 PI.
Edit
Possible implementation to the given code
..
const angle = Math.atan2(dist_y, dist_x) // angle between arrow & token

/*
result of atan2():
dist_x > 0, dist_y > 0 ==>    0  < angle <  PI/2  (1st quadrant)
dist_x < 0, dist_y > 0 ==>  PI/2 < angle <  PI    (2nd quadrant)
dist_x < 0, dist_y < 0 ==> -PI   < angle < -PI/2  (3rd quadrant)
dist_x > 0, dist_y < 0 ==> -PI/2 < angle <  0     (4th quadrant)
*/

// Map all angles from (-PI, PI) to (0, 2 PI)
if(dist_y < 0) angle += 2 * Math.PI

A: Thank you @Aquil Contractor for your answer, I had a play around with the code and this is the solution I came up with:
const dist_x = player.x - token.x
const dist_y = player.y - token.y

let angle = Math.atan2(dist_y, dist_x) // angle between arrow & token

const quarter = Math.PI / 2 // equivalent to 90° (I just thought I'd mention)

/* if the distance between the angles is greater
than 180°, bring the goal angle toward the current. */
if (arrow.angle > quarter && angle < -quarter) angle += Math.PI * 2
else if (arrow.angle < -quarter && angle > quarter) angle -= Math.PI * 2

arrow.angle += arrow.rot_speed
arrow.rot_speed *= .9
arrow.rot_speed += angle - arrow.angle

The solution was a lot simpler than I expected, but it works well and it makes sense.
Thanks all for your help and ideas!


text:
Q: Jmeter testing for localhost server? I want to use Jmeter as performance testing tool for my java web project but my project is on localhost server which is Tomcat server. How can i able to do performance testing of my project using Jmeter?

A: You can do that...just provide the IP address for the request and If it hits the server then you will get the response.
Below is more info from @Dmitri T post:-
Meter doesn't care whether application under test is local or remote, if you cannot hit local URL with JMeter - something is wrong with your HTTP Request Sampler configuration, most likely "Port" value is wrong.
In order to be able to help we need to know the following: 1. URL of your application 2. Output of View Results Tree listener 3. Contents of JMeter log 4. Description of screenshot of your HTTP Request sampler
As an alternative option you can try recording your scenario using JMeter Chrome Extension and see if you're able to replay recorded scenario without errors. Again, use View Results Tree listener to inspect request and response details.
In general it is not recommended to run the application under test and the load generator on the same physical or virtual machine as the load generator (JMeter in your case) may consume immense amount of resources like CPU and RAM and it may interfere your application health (unless you're using completely isolated containers), so I would recommend use separate hosts for application and the load generator.
Reference:-How to make Jmeter recognize "localhost" URL?


text:
Q: clustered index on a column which has duplicate values I have a table with no index. I need to add a clustered index on one column but the table does not have any column having unique data.Will this allow me to add clustered index on a duplicate column?

A: A clustered index does not enforce uniqueness unless you specify the keyword UNIQUE.
CREATE CLUSTERED INDEX bob ON foo( bar )

is not the same as
CREATE UNIQUE CLUSTERED INDEX bob on foo( bar )

You may be thinking of a PRIMARY KEY constraint in a CREATE TABLE statement.
In this example:
CREATE TABLE foo ( bar PRIMARY KEY )

ASE will create a UNIQUE, CLUSTERED index on bar.


text:
Q: ProgressDialog not showing up My ProgressDialog is not showing.
Here's the code:
et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId,
                KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                return true;
            }
            return false;
        }

        private void performSearch() {
            ProgressDialog pd = null;
            pd = ProgressDialog.show(MainActivity.this, "Buscando...",
                    "Buscando " + et.getText() + " en GuiaColor");
            lv.setAdapter(new SearchAdapter(MainActivity.this, handler
                    .search(et.getText().toString(), 20)));
            pd.dismiss();
        }
    });

It works just fine, the only issue is that the Dialog does not show up.

A: Try the following code to make your query in a background thread and dismiss your dialog once the task is completed:
    private void performSearch() {
        final ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Buscando...", "Buscando " + et.getText() + " en GuiaColor");

        new Thread() {
            public void run() {
                lv.setAdapter(new SearchAdapter(MainActivity.this, handler.search(et.getText().toString(), 20)));
                dialog.dismiss();
            }
        }.start();
    }


text:
Q: How to move Object in And-engine with velocity I am developing a game.In which i need to move object or sprite with static body attach to it.how can i move it.As i have four sided wall's so ma object do not move out of container.The walls are also static body in nature.I want to rotate and move object at the same time. I  have done so far rotating object but moving is not done yet.Here is the code how i rotate it `
@Override
    protected Scene onCreateScene() {
        scene = new Scene();
        this.mphysicworld = new PhysicsWorld(new Vector2(0,
                SensorManager.GRAVITY_EARTH), false);
        float pX = (CAMERA_WIDTH - Iregion_blackEgg.getWidth());
        sp_blackEgg = new Sprite(pX - 50, 50, this.Iregion_blackEgg,
                getVertexBufferObjectManager());

        Body eggBody =PhysicsFactory.createBoxBody(this.mphysicworld, sp_blackEgg,
                BodyType.DynamicBody, FIXTURE_DEF);
        this.mphysicworld.registerPhysicsConnector(new PhysicsConnector(
                sp_blackEgg, eggBody, true, true));

        eggBody.setLinearVelocity(pX, pY);

        RectFunction();

        final Vector2 gravity = new Vector2(0, 0f);
        mphysicworld.setGravity(gravity);

        scene.registerUpdateHandler(new IUpdateHandler() {

            @Override
            public void reset() {

            }

            @Override
            public void onUpdate(float pSecondsElapsed) {

                final float rotationOffset = pSecondsElapsed
                        *rotationIncrementalFactor;
                // if(i==100){

                RotateFunct(rotationOffset);
                // }else{
                // i=i+1;
                // }

                // this.onUpdate(pSecondsElapsed);
                  mphysicworld.onUpdate(pSecondsElapsed);
            }
        });

        scene.attachChild(sp_blackEgg);

        return scene;
    }

    public void RectFunction() {

        final Rectangle Right = new Rectangle(0, 0, CAMERA_WIDTH, 10f,
                this.getVertexBufferObjectManager());
        Right.setColor(org.andengine.util.color.Color.GREEN);
        Body myBodyRight = PhysicsFactory.createBoxBody(this.mphysicworld, Right,
                BodyType.StaticBody, FIXTURE_DEF);

        final Rectangle Top = new Rectangle(0, 0, 10f, CAMERA_HEIGHT,
                this.getVertexBufferObjectManager());
        Top.setColor(org.andengine.util.color.Color.GREEN);
        Body myBodyTop = PhysicsFactory.createBoxBody(this.mphysicworld,
                Top, BodyType.StaticBody, FIXTURE_DEF);

        final Rectangle Bottom = new Rectangle(CAMERA_WIDTH-10, 0, 10f, CAMERA_HEIGHT,
                this.getVertexBufferObjectManager());
        Bottom.setColor(org.andengine.util.color.Color.GREEN);
        Body myBodyBottom = PhysicsFactory.createBoxBody(this.mphysicworld,
                Bottom, BodyType.StaticBody, FIXTURE_DEF);

        final Rectangle Left = new Rectangle(0, CAMERA_HEIGHT-10, CAMERA_WIDTH, 10f,
                this.getVertexBufferObjectManager());
        Left.setColor(org.andengine.util.color.Color.GREEN);
        Body myBodyLeft = PhysicsFactory.createBoxBody(this.mphysicworld,
                Left, BodyType.StaticBody, FIXTURE_DEF);

        scene.attachChild(Right);
        scene.attachChild(Top);
        scene.attachChild(Bottom);
        scene.attachChild(Left);

    }

    public void RotateFunct(float rotationOffset) {

        sp_blackEgg.setRotation(sp_blackEgg.getRotation() + rotationOffset);
eggBody.applyForce(0f, 2000f,
            eggBody.getWorldCenter().x,
            eggBody.getWorldCenter().y);
    eggBody.applyLinearImpulse(0f, 200f,
            eggBody.getWorldCenter().x,
            eggBody.getWorldCenter().y);
    eggBody.setLinearVelocity(0f, 20f);
    eggBody.applyTorque(2000f);
    eggBody.applyAngularImpulse(20f);
    eggBody.setAngularVelocity(10f);

    }

`