text:
Q: JQuery success callback isn't being called or? I have searched a lot of threads but i can't find any answer that suits me. Now I will try to explain my problem.
I have a simple jQuery script that does a little ajax request. its simple like this:
print("

");

And the PHP page does this:
<?php
    $ret = "
hello world
";
    exit($ret);
?>

I have tried putting the return data on an HTML element via $.html(msg) too.
Problem is: alert or the $.html() on callback NEVER fires although on firebug I can check the request has the return code 200 OK.
Notice that the function code is wrapped into a PHP print("") command and the return dataType is HTML which is what I really need to get (can't use JSON).
Any miraculous advice? Thanks in advance.
Solved: changing dataType to 'text' according to Splash-X advices it worked.

A: try this way :
<?php
    $ret = "
hello world
";
    echo $ret;
?>

and see the result
UPDATED code:
<?php
        if(isset($_POST['value_s']))
        {
          $ret = "
hello world
";
          echo $ret;
        }
        else {
        echo "Nothing received !";
       }
?>

and the javascript:
$.ajax({
            url: target,
            //dataType: 'html',
            data: { "value_s":true},   //or something different value for `value_s`
            dataType: 'text',
            type: 'POST',
            success: function(msg){
                alert(msg);
            }
        });

A: You need your php page to return the value of $ret to your ajax call; try the following:
<?php
    $ret = "
hello world
";
    return $ret;
?>

A: We've tracked the issue down to the dataType attribute on the AJAX request:
 print("

 ");

Our suggestion was to add an error handeler and change the dataType:
      $.ajax({
             url: target,
             dataType: 'html' ,
             type: 'POST',
             success: function(msg){
                 alert(msg);
             },
             error: function(){
                  alert('error occured');
             }
         });

After getting the error alert we suggested removing the dataType property and letting jQuery auto-determine it OR changing it to text. The OP decided to specify the type as text and it worked:
      $.ajax({
             url: target,
             dataType: 'text',
             type: 'POST',
             success: function(msg){
                 alert(msg);
             }
         });

The issue was resolved


text:
Q: Fsync too fast? I'm surprised about big file ftruncate and fsync operations. I wrote a program that create an empty file on a Linux 64 bits system, truncate it to 0xffffffff bytes and after, fsync it.
After all operations, file is correctly created with this length.
I see that ftruncate cost about 1442 microseconds and fsync cost only 4 microseconds.
Is normal this high performance? Are really wrotten all bytes on disc? If not, how can I ensure this sync?
#include <sys/time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>

static const size_t __tamFile__ = 0xffffffff;

int main(int, char **)
{
    std::string fichero("./testTruncate.dat");

    unlink(fichero.c_str());

    int fd = open(fichero.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    if (fd != -1)
    {
        struct timeval t1, t2;

        timerclear(&t1);
        timerclear(&t2);

        gettimeofday(&t1, NULL);
        ftruncate(fd, __tamFile__);
        gettimeofday(&t2, NULL);

        unsigned long long msecTruncate = static_cast<unsigned long long>((((t2.tv_sec * 1E6) + t2.tv_usec) - ((t1.tv_sec * 1E6) + t1.tv_usec))) ;

        gettimeofday(&t1, NULL);
        fdatasync(fd);
        gettimeofday(&t2, NULL);

        unsigned long long msecFsync = static_cast<unsigned long long>((((t2.tv_sec * 1E6) + t2.tv_usec) - ((t1.tv_sec * 1E6) + t1.tv_usec))) ;

        std::cout << "Total microsec truncate: " << msecTruncate << std::endl;
        std::cout << "Total microsec fsync: " << msecFsync << std::endl;

        close(fd);
    }
    return 0;
}

A:
I wrote a program that create an empty file on a Linux 64 bits system,
  truncate it to 0xffffffff bytes and after, fsync it.

Unless you write something to it, it's extremely possible the file contains holes.
From TLPI:

What happens if a program seeks past the end of a file, and then
  performs I/O? A call to read() will return 0, indicating end-of-file.
  Somewhat surprisingly, it is possible to write bytes at an arbitrary
  point past the end of the file.
The space in between the previous end
  of the file and the newly written bytes is referred to as a file hole.
  From a programming point of view, the bytes in a hole exist, and
  reading from the hole returns a buffer of bytes containing 0 (null
  bytes).
File holes don't, however, take up any disk space. The file
  system doesn't allocate any disk blocks for a hole until, at some
  later point, data is written into it.

A: Which Linux kernel version do you have, which filesystem, and which mount options (in particular, are barriers enabled?)?
On Linux 2.6.32 64-bit, ext4 with barriers enabled (the default), I get

$ ~/src/cpptest/truncsync
Total microsec truncate: 32
Total microsec fsync: 266
Total microsec close: 14

Otherwise the same, but with a NFS mounted filesystem, I get

$ ./truncsync
Total microsec truncate: 38297
Total microsec fsync: 6
Total microsec close: 6
$ ./truncsync
Total microsec truncate: 3454967
Total microsec fsync: 8
Total microsec close: 330

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to populate datatable B based on selecting a column value in datatable A I am working on Primefaces and want to select particular column value based on selecting a column value in datatable A
<p:dataTable var="record" value="#{upshighlevel.upstclist1}" id="highLevelTable"
                selectionMode="single" selection="#{upshighlevel.selectedOverView}" rowKey="#{record}"
                paginator="true" rows="10" resizableColumns="true" scrollable="true"
                scrollWidth="100%" scrollHeight="150" rowsPerPageTemplate="10,20,50"
                paginatorTemplate="{FirstPageLink} {PreviousPageLink} {CurrentPageReport}
                            {RowsPerPageDropdown} {NextPageLink} {LastPageLink}"
                currentPageReportTemplate="(Displaying {startRecord} - {endRecord} of
                            {totalRecords}, Page: {currentPage}/{totalPages})">

                 <p:ajax event="rowSelect" listener="#{upshighlevel.onRowSelect}" update=":form:drillDownTable"/>

I am ussing rowSelect event how we make it for column select?

A: There is no columSelect event as you already found out and in this case it would even be cellSelect I pressume.
And why so difficult? Why not just do
<p:column>
    <p:commandLink value="#{cellValue}"
       actionListener="#{selectionBean.selectCell(cellValue)}"
       update="myOtherDatatable" />
</p:column>

Just clicking on the cell fires the actionListener and updates the other datatable.


text:
Q: Getting overflow: hidden to behave itself I'm trying to implement a simple image carousel and I can't keep the images from dropping down to the next line. Here's my CSS:
#gallery-wrap{margin: 0 auto; overflow: hidden; width: 532px; position: relative; float: left;}
#gallery{position: relative; left: 0; top: 0; float: left;}
#gallery li{float: left; margin: 0 20px 15px 0;}
#gallery li a img{border: 4px solid #40331b; height: 175px; width: 60px; float: left;}

#gallery-controls{margin: 0 auto; width: 732px; float: left;}
#gallery-prev{float: left;}
#gallery-next{float: right;}

Here's my HTML:

I'm trying to display 5 images at a time, with the rest hidden. Then clicking on the prev and next buttons scrolls it back and forth using jQuery. Right now, when there are more than 5 images, the start dropping down to the next line instead of becoming hidden.

A: Well, yeah. If you specify a height value on #gallery-wrap, it will hide child elements beyond that height. If you don't (and you haven't), then #gallery-wrap will be as tall as its children need it to be.
Set a height on #gallery-wrap and you're good to go.


text:
Q: Developing a graphical user interface in Python / connecting GUI to other code? I just want to know if this is possible or if I need to look for other options...
I am trying to develop medical software for heart disease diagnosis, and already coded the machine learning algorithm to analyze patient data. It is a .py file, and the algorithm outputs a heart disease severity score from 0-4.
I would like to incorporate this algorithm into a desktop application that gives the user (a doctor) an input field for the given patient's information, and then allows the doctor to run the algorithm I have coded (ideally by clicking a button, or other intuitive process) and then view the results for this one patient.
Is this possible to do in Python / PyQT for developing the interface and connecting it to the algorithm?
Thanks.

A: Yes, it is possible, and fairly straightforward too. Here is a decent PyQt5 tutorial series to start with.


text:
Q: How to plot a characteristic curve for silicon diode There is a figure given that shows the relation between Forward current(y axis) and forward Voltage (x axis ) for a forward biased diode, with the given formula
$$If(forward current)= I0*e^{(k*q*T*Vf)/n}$$
Where $n=2, q=1.6*10^-19 , k=1.3805*10^-23$, Vf is the forward voltage and i am guessing T is the temperature.
The data points are given for If and for Vf. I need to use ListPlot to model the data as a function and then plot the characteristic curve for the silicon diode.
I don't know what steps i need to provide (or what program i need to construct) in order to be able to plot a perfect curve for the diode so that when i try to insert the data points on the plotted curve they fit or are close.
I used Interpolation to function the data points firstly and then i used list plot command to plot the data points list.
Then when i used plot command to plot the points given to find the curve, it keeps giving error! How do i proceed?
IF = {0.0, 0.0, 0.02, 0.25, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9, 10, 11, 12, 13}
VF = {0.2, 0.3, 0.4, 0.5, 0.576, 0.603, 0.624, 0.636, 0.646, 0.654, 0.661, 0.667, 0.671, 0.676, 0.681, 0.684}
Riffle[VF, IF]
data = Partition[%, 2]

f1 = Interpolation[data]

PLOT1 = ListPlot[f1, Joined -> False, PlotRange -> {{0.0, 1.0}, {0, 13}}, PlotStyle -> {Red}, PlotMarkers -> {Style["\[CircleDot]", Red, Smaller]}, Frame -> True, FrameLabel -> {"VF (volt)", "IF(aM)"}, LabelStyle -> Directive[Black]]

CurveThickness = 0.05

PLOT2 = Plot[f1[VF], {VF, 0.0, 1.0}, PlotRange -> All, Frame -> True,
FrameLabel -> {"VF (volt)", "IF (aM)"},
LabelStyle -> Directive[Black],
PlotStyle -> {Black, Thickness[CurveThickness]}]

A: You have an extra value of IF for the number of values of VF you had, so I am commenting out the last one in your data. Also, rather than Riffle and Partition, I'd obtain the same thing with Transpose.
IF = {0., 0., 0.02, 0.25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12(*, 13*)};
VF = {0.2, 0.3, 0.4, 0.5, 0.576, 0.603, 0.624, 0.636, 0.646,
      0.654, 0.661, 0.667, 0.671, 0.676, 0.681, 0.684};
data = Transpose[{VF, IF}];

(* given parameter values *)
CurveThickness = 0.05
n = 2;
q = 1.6*^-19;
k = 1.3805*^-23;

(* Carry out the non-linear fit of data to your model *)
nlmf = NonlinearModelFit[data, i0 Exp[k q T Vf/n], {i0, T}, Vf];

(* generate and combine the two plots               *)
(* note that shared options have been moved to Show *)
(* rather than duplicating them in both plots       *)
Show[
  (* plotting the results of the fit *)
  Plot[
    nlmf[Vf], {Vf, 0, 1},
    PlotStyle -> Directive[Black, Thickness[CurveThickness]]
  ],
  (* plotting the raw data *)
  ListPlot[
    data,
    PlotStyle -> Directive[PointSize[0.02], Red],
    LabelStyle -> Directive[Black]
  ],
  PlotRange -> {{0.0, 1.0}, {0, 13}},
  Frame -> True,
  LabelStyle -> Directive[Black],
  FrameLabel -> {"VF (volt)", "IF(aM)"}
]


text:
Q: I am given the following numerical controlling system:
To create a MATLAB program that simulates the operation of the system at the step input (the graphs of v(t), e(t), u(t), and y(t) are required).
I did not find any example, I do not know where to start and how to approach this requirement Some clues, please.

A: Plotting Step Response for a Random System/Transfer Function
Here is a step response plot of a random system, where the period of the step is 0.5 seconds which is configured by the variable Step_End inputted into the step() function. I'll leave the computation of the respective transfer functions up to you. To find the closed-loop gain of a system you can employ the general form:

Where G_inner is the gain along the path that is not a part of the loop. Furthermore when there is a gain along the feedback path you can adapt the equation's denominator as 1 + H_Process*G_inner where H_Process the gain along the feedback.

%Random numerator coefficients%
a = 4;

%Random denominator coefficients%
b = 1;
c = 2;
d = 10;

%Creating the transfer function%
Numerator = [a];
Denominator = [b c d];
Transfer_Function = tf(Numerator, Denominator);
Transfer_Function

%Checking the step response with period 0.5%
Step_End = 0.5;
step(Transfer_Function,Step_End);

Ran using MATLAB R2019b


text:
Q: How to shift array list elements to the right with some index at fixed position in java I have an array list with a size of 10 elements. What I am trying to achieve here is that when I add an element at any index, the element which is next to it should get shifted except at some fixed indexes.
For example, Let's say my array list is as follows
[10, 20, 30, 40, 50,60,70,80,90,100]
indexes are {0,1,2,3,4,5,6,7,8,9}
fixed indexes{4,6}
when I remove an element from index  10 and add an index 3 the output should be as follows
[10, 20, 30, 100, 50, 40,70,60,80,90,]
if you notice the values at indexes {4,6} did not change after adding 10 th element at index 3.
    List<Integer> values = new ArrayList<>();
    values.add(10);
    values.add(20);
    values.add(30);
    values.add(40);
    values.add(50);
    values.add(60);
    values.add(70);
    values.add(80);
    values.add(90);
    values.add(100);
    System.out.println(values);

    values.removeAt(9)
    values.add(3,100);
    System.out.println(values);

    # Output
    [10, 20, 30, 40, 50,60,70,80,90,100]
    [10, 20, 30, 100, 40,50,60,70,80,90]

If anyone can Suggest any sorting method or collections to achieve this it will be really helpful.
Sample input and outputs:
int[] a= [7, 4, 3, 2, 1, 5, 6, 4, 8, 9] and fixed indexes are {1,2}
Remove 6th index element (6) and add at index 0
The output should be as follows:
[6, 4, 3, 7, 2, 1, 5, 4, 8, 9]

A: Here's my simple solution making use of the existing ArrayList class, though it might be best if you define your own implementation to meet your needs. Note that you may need to override more methods if you want to be sure they adhere to the rules you define:
public static class FixableArrayList<T> extends ArrayList<T> {

    // ascending and descending views of the fixed indices
    private final SortedSet<Integer> fixedAsc;
    private final SortedSet<Integer> fixedDec;

    public FixableArrayList() {
        TreeSet<Integer> treeSet = new TreeSet<>();
        fixedAsc = treeSet;
        fixedDec = treeSet.descendingSet();
    }

    public boolean addFixedIndex(int ind) { return fixedAsc.add(ind); }
    public boolean removeFixedIndex(int ind) { return fixedAsc.remove(ind); }

    public void move(int fromInd, int toInd) {
        if (fromInd == toInd) {
            return;
        }
        if (fixedAsc.contains(fromInd)) {
            throw new IllegalArgumentException("Cannot remove from fixed index: " + fromInd);
        }
        if (fixedAsc.contains(toInd)) {
            throw new IllegalArgumentException("Cannot add to fixed index: " + toInd);
        }

        super.add(toInd, super.remove(fromInd));

        if (toInd < fromInd) {
            // all between `from` and `to` shifted up, swap fixed indices down back into position
            // iterate from low (toInd) to high (fromInd)
            for (int i : fixedAsc.subSet(toInd, fromInd)) {
                super.add(i, super.remove(i + 1));
            }
        } else {
            // all between `from` and `to` shifted down, swap fixed indices up back into position
            // iterate from high (toInd) to low (fromInd)
            for (int i : fixedDec.subSet(toInd, fromInd)) {
                super.add(i, super.remove(i - 1));
            }
        }
    }
}

public static void main(String[] args) {
    FixableArrayList<Integer> values = new FixableArrayList<>();
    values.addAll(Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80, 90, 100));

    // set the indices that you want to remain fixed
    values.addFixedIndex(3);
    values.addFixedIndex(5);
    values.addFixedIndex(9);

    System.out.println(values);

    values.move(0, 8);
    System.out.println(values);

    values.move(8, 0);
    System.out.println(values);
}

A: There'is a special trick to do it in place and O(n) time.
[0,1,2,3,4,5,6,7,8,9] // init -> swapt 3 positions to the right
[9,8,7,6,5,4,3,2,1,0] // 1st rotate
[7,8,9,6,5,4,3,2,1,0] // 2nd rotate
[7,8,9,0,1,2,3,4,5,6] // 3rd rotate

public static void rotate(int[] arr, int k) {
    if ((k %= arr.length) != 0) {
        k = k < 0 ? arr.length + k : k;
        swapSubArr(arr, 0, arr.length);
        swapSubArr(arr, 0, arr.length - k);
        swapSubArr(arr, arr.length - k, arr.length);
    }
}

private static void swapSubArr(int[] arr, int from, int to) {
    for (int i = from, j = to - 1; i < j; i++, j--)
        swap(arr, i, j);
}

private static void swap(int[] arr, int i, int j) {
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

A: I think the only possible way is to loop through the list and create a new list and have a check for the two indices that when they occur then don't replace them and put the same value from the older list.
You can have a method in which you pass your parameters for the change you want and the indices those are fixed and in that method you can create a new list based on the passed parameters.


text:
Q: Prove that a set of linearly independent vectors added together is also linearly independent. Suppose we know that $S = \{v_1, v_2, v_3\}$ is a linearly independent set of
vectors in some vector space $V$ . Let $T = \{v_1 + v_2, v_2 + v_3, v_3 + v_1\}$.
Prove that $T$ is also linearly independent.
This proof makes sense to me that it would be true, but I cannot figure out the steps of the proof that make this a true statement?

A: $\det \begin{bmatrix} 1 & 1 & 0 \\ 0 & 1 & 1 \\ 1 & 0 & 1 \end{bmatrix} = 2 \neq 0$.

A: If $v_1,\, v_2,\, v_3$ are linearly independent, then $av_1 + bv_2 + cv_3 = 0 \implies a = b = c = 0 $. Now suppose $$
a(v_1+v_2) + b(v_2+v_3) + c(v_3+v_1) = 0,
$$
then this would imply
$$
(a+c)v_1 + (a+b)v_2 + (b+c)v_3 = 0.
$$
Because this is a linear combination of our original linear independent vectors, this implies $ a+c = a+b = b+c = 0$, from which you easily get $a = b = c = 0$.

A: Suppose $\{v_1,v_2,v_3\}$ are Linearly Independent. Then whenever $a_1v_1+a_2v_2+a_3v_3=0$ for scalars $a_1,a_2,a_3$ we have $a_1=a_2=a_3=0$.
Now let $b_1(v_1+v_2)+b_2(v_2+v_3)+b_3(v_3+v_1)=0$ for scalars $b_1,b_2,b_3$.
Then since a vector space is afterall a commutative group (additive), you can write the above as $(b_1+b_3)v_1+(b_1+b_2)v_2+(b_2+b_3)v_3=0$.
But $v_1,v_2,v_3$ are LI. From what I wrote in first line, $b_1+b_3=b_1+b_2=b_2+b_3=0$.
Thus we have from above that $b_1=b_2=b_3=0$.


text:
Q: Check whether array has keys that don't match a list What is the easiest way to check if an has array keys that don't match a particular list?
$a = array(
  [ignore_me] => "blah blah blah",
  [name] => "Don"
);

does_array_have_non_ignored_entries($a); // returns true

I can think of a ton of ways to write this function, didn't know if PHP has a quick solution. Best one I have is this:
$length = count($a);
$ignored_entry = (in_array($a, 'ignore_me') ? 1 : 0;
if ($length - $ignored_entry > 0) {...}

A: One way to do this, using standard functions, is as follows:
$ignored_keys = array("ignore_me"); // can be extended to ignore several keys
$diff = array_diff_key($array,array_flip($ignored_keys));
if( $diff) {
    // there are keys that weren't ignored.
}

A: How about this?
$count = isset($a['ignore_me']) ? count($a) -1 : count($a);

Substract 1, if that key is found, else use the full length.

A: Another solution is the array_diff_key function
$count = count(array_diff_key(array('ignore_me'=>null), $a)));

A: foreach($a as $key => $row)
{
    if($key == 'ignore_me')
    {
        unset($array[$key]);
    }
}
$count = count($array);

A: for this you can use a array in built function as:
$a = array(
  [ignore_me] => "blah blah blah",
  [name] => "Don"
);

if (array_key_exists("ignore_me",$a))
   {
   echo "Key exists!";
   }
else
   {
   echo "Key does not exist!";
   }
?>


text:
Q: How to get Angular.js binding tags safely past Python's Jinja2? Python's server-side Jinja2 and JavaScript's client-side Angular should both be able to run on the same application but it's sort of troublesome when i.e.

{{ object.attribute }}

has to "make it past the Python" first without hiccups. How would one best disambiguate the Jinja2 from the Angular?
I know that I can nest the Angular within Jinja2's {% raw %}{% endraw %} tags as far as the server goes, but what way could I solve this on the client-side?

A: As documented in the Angular Documentation, you can change the symbols used for expressions.

This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular template within a Python Jinja template (or any other template language). Mixing templating languages is very dangerous. The embedding template language will not safely escape Angular expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS) security bugs!

var customInterpolationApp = angular.module('customInterpolationApp', []);

customInterpolationApp.config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('//');
  $interpolateProvider.endSymbol('//');
});

customInterpolationApp.controller('DemoController', function() {
      this.label = "This binding is brought you by // interpolation symbols.";

  //demo.label//


text:
Q: Sublime regex change \n to space if followed by lower case I know this sounds like a repeated question, but I'm relatively new to Regex and don't really understand some of the other answers. I managed to get this to work previously with something like
Find: \n+[(a-z)]
Replace: *space*\1

I can't remember the exact terms I used though, and now if I try it the subsequent alphabet is deleted, and online regex testers say the \1 in replace is an invalid expression.
E.g.
I
want
this
To remove
Newlines

should become
I want this
To remove
Newlines

but is instead becoming
I ant his
To remove
Newlines

I don't remember what I used the first time round, but i disabled the "whole word" option in sublime, and somehow managed to remove the newlines without cutting characters. Why is \1 invalid? also what is the difference whether I use "+" or not? I don't really understand what greedy means. Sorry, and thank you!
Edit: thanks for all the responses! I definitely have a lot more to learn about using regex more flexibly, but in this case it was the difference between [(a-z)] and ([a-z]) that I missed.

A: Your regex does not contain a capturing group. A \1 in the replacement pattern is a backreference to the capture group inside the regex pattern. If the group does not exist, the error pops up.
You seem to want to replace 1+ line breaks before a lowercase letter. Make sure your settings are like this:
The regex is: \h*\R+([a-z]) (where \h* matches 0+ horizontal whitespaces, \R+ matches any 1+ line breaks, CRLF/LF/CR and ([a-z]) matches a lowercase ASCII letter)
Replacement:  \1 (where \1 puts back Group 1 value)
Settings:

Note that the case sensitivity must be enabled, too.

A: You could do it like
(?: )?[\n\r]([a-z])

And replace the occurence with $1 (space, followed by $1), see a demo on regex101.com.

Explanation:

(?: )?  # Looks for a space, this is optional
[\n\r]  # newline
([a-z]) # a character between a and z, lowercase


text:
Q: Convert single column dataframe to dataframe with multiple rows and named columns dfOrig <- data.frame(rbind("1",
                       "C",
                       "531404",
                       "3",
                       "B",
                       "477644"))
setnames(dfOrig, "Value")

I have a single column vector, which actually comprises two observations of three variables. How do I convert it to a data.frame with the following structure:
ID      Code     Tag
"1"     "C"      "531404"
"3"     "B"      "477644"

Obviously, this is just a toy example to illustrate a real-world problem with many more observations and variables.

A: Here's another approach - it does rely on the dfOrig column being ordered 1,2,3,1,2,3 etc.
x <- c("ID", "Code", "Tag")    # new column names
n <- length(x)                 # number of columns
res <- data.frame(lapply(split(as.character(dfOrig$Value), rep(x, nrow(dfOrig)/n)),
         type.convert))

The resulting data is:
> str(res)
#'data.frame':  2 obs. of  3 variables:
# $ Code: Factor w/ 2 levels "B","C": 2 1
# $ ID  : int  1 3
# $ Tag : int  531404 477644

As you can see, the column classes have been converted. In case you want the Code column to be character instead of factor you can specify stringsAsFactors = FALSE in the data.frame call.
And it looks like this:
> res
#  Code ID    Tag
#1    C  1 531404
#2    B  3 477644

Note: You have to get the column name order in x in line with the order of the entries in dfOrig$Value.
If you want to get the column order of res as specified in x, you can use the following:
res <- res[, match(x, names(res))]

A: Maybe convert to matrix with nrow:
# set number of columns
myNcol <- 3

# convert to matrix, then dataframe
res <- data.frame(matrix(dfOrig$Value, ncol = myNcol, byrow = TRUE),
                  stringsAsFactors = FALSE)

# convert the type and add column names
res <- as.data.frame(lapply(res, type.convert),
                     col.names = c("resID", "Code", "Tag"))
res
#   resID Code    Tag
# 1     1    C 531404
# 2     3    B 477644

A: You can create a sequence of numbers
x <- seq(1:nrow(dfOrig)) %% 3  #you can change this 3 to number of columns you need

data.frame(ID = dfOrig$Value[x == 1],
           Code = dfOrig$Value[x == 2],
           Tag = dfOrig$Value[x == 0])

#ID Code    Tag
#1  1    C 531404
#2  3    B 477644

Another approach would be splitting the dataframe according to the sequence generated above and then binding the columns using do.call
x <- seq(1:nrow(dfOrig))%%3
res <- do.call("cbind", split(dfOrig,x))

You can definitely change the column names
colnames(res) <- c("Tag", "Id", "Code")

#  Tag       Id  Code
#3 531404     1     C
#6 477644     3     B


text:
Q: Looking for how to add a new member Where can I now find the admin members page in the appengine.google.com console?
It looks like Google changed to a new interface in the appengine console. I'm trying to add a new member but I can't find where to do it.

A: Using the new Google Cloud Identity & Access Management (IAM) you are able to have more fine-grained control over the access permissions to your Google Cloud project resources.
Managing members of your project are now done directly in the IAM Dashboard. For more information on the processes, you can take a look at the guides provided in our documentation.


text:
Q: PCB layout for 8-16MHz crystal very near WiFi module AND small DC motor I'm designing an "Internet of Things" appliance where space and layout are constrained by mechanical and cost requirements. The main processor is a PIC18 and its crystal (probably 8MHz, maybe 16) is mounted close to some things I regard as "scary" from an EMI point of view:

*

*(~5mm away) A (2.4GHz) WiFi module (a PCB-with-shielded-can-on-top style module which solders onto the main board - the "business end" is to the top left of the module so as far away from the µC and xtal as it can be).

*(~10mm away) A small DC gearmotor (mounted a few mm above the board on a metal 'L' bracket which is grounded to the PCB).

*(~15mm away) A3906 motor driver IC and associated power components.

I've looked over a few other "how's my crystal routing?" posts here and it seems like mine is probably OK (though I'd really welcome any criticism) but I am a bit worried about the nearby noise sources, especially as this is a solar + battery powered device that will be minimising power consumption as much as possible including minimising the power drawn by the oscillator.
I have given the crystal section its own ground planes and connected these to the bottom main ground plane at one of the PIC's VSS pins, so there will be return current on this pin but presumably not via any of the oscillator circuit.

*

*OSC1 goes µC<>cap<>xtal and OSC2 goes µC<>xtal<>cap - is this OK?

*Is the local ground plane around the xtal area going appreciably to increase the power draw of the oscillator?

*Is the way I've connected the system & crystal grounds together sensible?

*The top & bottom ground planes for the crystal are tied together with 3 vias but there is a return path that doesn't go through any of them. Is this "right"?

*Are any of the above noise sources likely to be an issue and if so how might I mitigate this? (the rest of the PCB is full up, so "move it further away" isn't really an option)
2 layer board. Top red, bottom blue, white area around crystal & caps is a cutout from ground pours on top and bottom, returning via the via (ha) next to one of the two VSS pins on the PIC18 (other one is on the other side of the chip). White hatched is the top soldermask stop (motor bracket grounded to topside ground pour this way). 8 mil traces & .5mm via drills.
Below the crystal you can see the motor mounting bracket (red) and motor outline (cyan). Motor driver in extreme bottom right. BR corner of WiFi module to top/left.
Edit 0:

Edit 1:
Improved grounding around signal traces in bottom right area below motor.

A: Your general crystal layout looks pretty good. I've seen plenty of examples that were 10 to a 100 times worse than what you show here!
Have you considered the possibility of using an MCU that has its own onboard oscillator thus eliminating the need for concerns about an external crystal?
Is there any possibility that you can share some other frequency source to drive the MCU such that the source generator is away from the motor and WiFi module?
What is the dead ended trace as highlighted here in yellow area? Is that an intentional trace to shield the two adjacent traces from each other? If it is GND shield trace would it be in need of a via a several spots to tie it into the GND plane?


text:
Q: VB.NET Unloading and reloading a project when executing a program through the Visual Studio External Tools I'm making a software that is executed through the External tools of Visual Studio, and it changes some stuff in the loaded project.
But the modifications only appear after I reload the project in my solution.
Is there any way of automatically unload and reload a project through the program that I made?


text:
Q: spring mvc no xml configuration 404 error I am trying to develop a simple Spring MVC with no XML application .its basically show a simple home page. I am using tomcat on JetBrains IDE for development and problem is that when I run it on tomcat I see 404 error this is url  http://localhost:8080/MySpringSecurityApp_war/
this is a controller
@Component
public class DemoController {
    @GetMapping("/")
    public String showHome(){
        return "home";
    }
}

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.luv2code.springsecurity.demo")
public class DemoAppConfig  {
    //define a bean for view resolver
    @Bean
   public ViewResolver viewResolver(){
      InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
      viewResolver.setPrefix("/WEB-INF/view/");
      viewResolver.setSuffix(".jsp");
      return  viewResolver;
    }
}

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] {DemoAppConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

this is error log
9-Jun-2020 13:32:07.511 WARNING [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/MySpringSecurityApp_war/] in DispatcherServlet with name 'dispatcher'
09-Jun-2020 13:32:07.604 WARNING [http-nio-8080-exec-4] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/MySpringSecurityApp_war/] in DispatcherServlet with name 'dispatcher'

this is also how my project structure

A: You need to define a resource path if you adding something into your URL (after host part basically in your case MySpringSecurityApp_war)  you are calling localhost:8080/MySpringSecurityApp_war/ but you didn't define the resource path anywhere so I guess what you need to do is either add @RequestMapping("/MySpringSecurityApp_war/") at class level or just call localhost:8080/ without any resource path
You can also use @RestController in place of @Component.
I hope it will work.


text:
Q: Is using #pragma warning push/pop the right way to temporarily alter warning level? Once in a while it's difficult to write C++ code that wouldn't emit warnings at all. Having warnings enabled is however a good idea. So it is often necessary to disable warnings around some specific construct and have them enables in all other pieces of code.
I've seen two ways of doing that so far.
The first one is to use #pragma warning( push ) and #pragma warning( pop ):
 #pragma warning( push )
 #pragma warning( disable: ThatWarning )
 //code with ThatWarning here
 #pragma warning( pop )

The second is to use #pragma warning( default ):
 #pragma warning( disable: ThatWarning )
 //code with ThatWarning here
 #pragma warning( default: ThatWarning )

The problem I see in the second variant is that it discards the original warning level - the warning might have been off before that or its warning level might have been altered. Using default would discard those alterations.
The first approach looks clean. Are there any problems with it? Are there any better ways to achieve the same?

A: This will work with multiple compilers (and different versions of compilers).
Header "push"
#if defined(__clang__)
# pragma clang diagnostic push
#endif

#if defined(_MSC_VER)
# pragma warning(push)
#endif

#if defined(YOUR_FAVORITE_COMPILER)
# pragma your compiler push warning
#endif

Header "pop"
#if defined(__clang__)
# pragma clang diagnostic pop
#endif

#if defined(_MSC_VER)
# pragma warning(pop)
#endif

Some warning
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wunused-variable"
#  if __has_warning("-Wnew-special-warning")
#   pragma clang diagnostic ignored "-Wnew-special-warning"
#  endif
#endif

#if defined(_MSC_VER)
# pragma warning(disable: 4100) // unreferenced formal parameter
# if _MSC_VER > _MSC_SOME_VERSION
#  pragma warning(disable: xxxx) // disable one more for special version
# endif
#endif

Usage
// This code reports warnings
// ...
#include <ignore_compiler_warning/push>
#include <ignore_compiler_warning/warning_type_1>
#include <ignore_compiler_warning/warning_type_2>
#include <ignore_compiler_warning/warning_type_3>
// This code ignores warnings type_{1,2,3}
// ...
#include <ignore_compiler_warning/pop>
// Back to reporting warnings
// ...

Additionally include guards can check that there is no double push/pop/disable-warning pragmas.
Update

*

*Implementation

*List of available warnings

*CMake companion function to generate flags

A: Too late for sharptooth but for all the googlers out there:
#pragma warning ( suppress: ThatWarning )
// one single line with ThatWarning

is short for (generally since VS 2008, but in VS 2005 for Code Analyzer warnings only):
#pragma warning ( push )
#pragma warning ( disable: ThatWarning )
// one single line with ThatWarning
#pragma warning ( pop )

A: The first method is the best way to do it, IMO.  I know of no problems with it.
Simply bear in mind that a #pragma is compiler specific so don't expect it to work on every compiler out there :)

A: You can disable specific warnings in the project or file options and this setting applies as the 'default' per those #pragmas at the relevant scope.  Some of the warnings in VS2005 are so useless/annoying that this cleans up the output quite a bit, if using /W4.
This is in Properties under Configuration Properties -> C/C++ -> Advanced.

A: I have no problems with the first variant. May be the better way is to use the following:
 #pragma warning( push )
 #pragma warning( once: ThatWarning )
 //code with ThatWarning here
 #pragma warning( pop )

This will let you know that there're still warnings in the code, but the warning messages will not be so annoying. But that is the matter of taste.

A: The correct approach (although a bit ugly)
#ifdef _MSC_VER
 #pragma warning( push )
 #pragma warning( once: ThatWarning )
#endif
 //code with ThatWarning here
#ifdef _MSC_VER
 #pragma warning( pop )
#endif

A: The first approach allows you change the specific warning setting in a local scope. It first stores all the current warning state by push into stack, apply your warning modifications, then restore (pop) to last warning state.
#pragma warning( push )
 #pragma warning( once: ThatWarning )
 //code with ThatWarning here
 #pragma warning( pop )


text:
Q: WordPress Section of site will not Load Over SSL I have been recently working on a new site for a small business named Stick'em Stickers.
Right now the site is set up so that the front end that the uses see is a static webpage. In the background I have a WordPress instance running that we use to load dynamic content onto our site.
For a better understanding, you can just visit the website here.
My problem is that any pages or content that is trying to load that are WordPress related, will not load correctly or all the way.


text:
Q: Callback on client does not get triggered with SignalR I'm currently getting up to speed with SignalR, and tried to build a very basic message notification system using the very basic understanding of SignalR that I have but I can't get the messages to come back after the submission.
I've read up on numerous blogs on the topic and the very basic is to have a VOID method that accepts a string value and then passes that back by attaching it to the Clients context, however, this does not work for, as onReceiveNotification() is always undefined in JS debugger?
Am I missing something
notificationhub.cs
[HubName("notificationHub")]
public class NotificationHub : Hub
{

    public override System.Threading.Tasks.Task OnConnected()
    {
        return base.OnConnected();
    }

    public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
    {
        return base.OnDisconnected(stopCalled);
    }

    public override System.Threading.Tasks.Task OnReconnected()
    {
        return base.OnReconnected();
    }

    [HubMethodName("sendNotifications")]
    public void SendNotifications(string message)
    {
        Clients.All.onRecieveNotification(string.Format("{0} {1}", message, DateTime.Now.ToString()));
    }
}

message.html page

    <input type="text" id="messageinput" />
    <button id="notifybutton">Send Message</button>

display.html

A: It looks like you are missing client in:
   $hub.client.onRecieveNotification = function (message)
    {
        $("#message").append($("

", { text: message }));
    }


text:
Q: Fatal error: Cannot use object of type stdClass as array Всем, привет! Народ в продолжение вот этой темы, опираясь на советы отвечающих, каким то чудом я все таки получил примерно то что мне надо:
Array
(
    [0] => stdClass Object
        (
            [charsetinfo] => stdClass Object
                (
                    [name] => utf-8
                )
        )
    [1] => stdClass Object
        (
            [value] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 1
                            [secid] => test
                            [name] => TEST
                        )

                    [1] => stdClass Object
                        (
                            [id] => 2
                            [secid] => test
                            [name] => TEST
                        )
                )
        )
)

но за каким-то... появляется некий stdClass Object и вроде как из-за этого вываливается

Fatal error: Cannot use object of type
  stdClass as array in
  C:\webserver\www.test.ru\www\index.php
  on line 124

Обращаюсь к элементам массива вот таким вот образом:
$tmpArr = json_decode(file_get_contents($myString));
$value = $tmpArr[1]['securities'][0]['secid']; // вот эта line 124
echo $nick;

A: ой, я забыыыыл)))
$tmpArr = json_decode(file_get_contents($myString), true);

все же почитайте про json_decode ;)


text:
Q: ADO.NET not properly connecting to database (multiple errors) I have an ASP.NET MVC 3 application and in my project I use ADO.NET Entity Data Model.
For access to data I use intermediate class (DataManager):
public class DataManager
{
    private static mrhomeEntities _dataContext;

    public DataManager()
    {
        _dataContext = new mrhomeEntities();
    }

    private OptionStorageRepository _optionStorageRepository;

    public OptionStorageRepository OptionStorage
    {
        get { return _optionStorageRepository ?? (_optionStorageRepository = new OptionStorageRepository(_dataContext)); }
    }
}

In OptionStorageRepository class I have 1 method that returns a list of options:
    public IQueryable<OptionStorage> List()
    {
        return _dataContext.OptionStorage;
    }

Such classes I have more than 15 (with this structure) to get and edit data in database.
Still I have my ControllerFabrick, where I pass a new object of DataManager class:
public class ControllerFabricFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        return Activator.CreateInstance(controllerType, new DataManager()) as IController;
    }
}

Also I registered my controller fabrick in Global.asax like this:
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        ControllerBuilder.Current.SetControllerFactory(new ControllerFabricFactory());
    }

And in all Controllers I receive this parameter in constructor and using in my action methods:
public class HomeController : Controller
{
    private readonly DataManager dm;

    public HomeController(DataManager dm)
    {
        this.dm = dm;
    }
    [HttpGet]
    public ActionResult Main()
    {
        Page page = dm.Page.Details(mainPageName);

        PageNews pageNews = new PageNews();
        pageNews.page = page;
        pageNews.NewsList = dm.News.List(5);
        pageNews.PopularProject = dm.Project.GetPopularProject();

        if (pageNews.PopularProject != null)
        {
            var list = pageNews.PopularProject.ProjectPictures.Where(p => p.ProjectPictureTypes.Id == 1).ToList();
            if (list.Count > 0)
            {
                ViewData["img"] = list[0].ThumbPath;
            }
        }
        foreach (var item in dm.Page.List())
        {
            ViewData[item.Name] = item.ShortPageText;
        }
        ViewData["projects"] = dm.Project.GetMainPageProjects();
        ViewData["MainText"] = dm.Page.Details("maintext").PageText;
        return View(pageNews);
    }
}

And my question:
When I test my application in web browser I have strange errors, that contains information about connection to database or retrieving data, I have collection of my errors below:

*

*The connection was not closed. The connection's current state is
connecting.

*Invalid attempt to read when no data is present

*ExecuteReader requires an open and available Connection. The
connection's current state is open.

*New transaction is not allowed because there are other threads
running in the session.

*An item with the same key has already been added.

Maybe I used wrong structure for get the data?

A: Per question:

Update: problem resolved, object DataContext was static (


text:
Q: What Android device should I buy for Android app development? I'm in the market for a basic Android device.  My main reason for buying one is for learning to develop mobile apps.  While the Eclipse IDE offers a virtual Android device for testing apps, it's not the same thing as a real Android device and won't put me on the same wavelength as Android device users.  (The most obvious example: Visibility is poorer in a bright outdoor environment than indoors.)
Some questions:

*

*Is a tablet PC the type of device I should get?  I get the impression that it's more versatile than other devices.  I don't need a smartphone, because my dumbphone works well for me, and I don't even use it that much.  And I HATE the idea of being locked into a specific wireless provider.  I'm not interested in ebooks, because I still like books on paper better.

*Should I get a device with Android 2.3 or 4.0?  On the one hand, over 90% of current Android users are using version 2.3.3 or earlier.  On the other hand, 4.0 is better and will be gaining market share.  (Would buying an Android 2.3 device now and buying an Android 4.0 device later be my best bet?)

*In addition to wifi, what else should I look for?

*Are there any brands/models I should avoid?  I remember hearing that the Packard Bell PCs were the most unreliable.  The Yugo was a terrible value.  (An old Oldsmobile Cutlass clunker was a better value - at least as reliable but MUCH cheaper to buy.)

*Is there any point in buying used?  The listings on Ebay and Google Shopping don't show the used tablet PCs to be that much cheaper than new ones, and there are more new tablets than used ones available.

Ebay listings currently (5-23-2012) show over 200 Android 2.3 tablets selling for $55-$90:
http://www.ebay.com/sch/iPads-Tablets-eBook-Readers-/171485/i.html?Operating%2520System=Android%25202%252E3%252Ex%2520Gingerbread&LH_BIN=1&Internet%2520Connectivity=Wi%252DFi%7CWi%252DFi%2520%252B%25203G%7CWi%252DFi%2520%252B%25204G&_nkw=android+2.3&_dmpt=US_Tablets&rt=nc&LH_ItemCondition=1000
Ebay listings currently (5-23-2012) show over 200 Android 4.0 tablets selling for $83-$107:
http://www.ebay.com/sch/iPads-Tablets-eBook-Readers-/171485/i.html?Operating%2520System=Android%25204%252Ex%2520Ice%2520Cream%2520Sandwich&LH_BIN=1&LH_ItemCondition=1000&Type=Tablet&_pppn=r1&_dmpt=US_Tablets&Internet%2520Connectivity=Wi%252DFi%7CWi%252DFi%2520%252B%25203G%7CWi%252DFi%2520%252B%25204G
What do you think?

A: This question is probably off topic.
But here are my thoughts:
If you want to develop the truth is you should try to have access (be it ownership or just access) to any devices that you intend to support with your applications. This is certainly not possible for everyone, but there are ways that you can maximize your value while building a device collection by aiming to hit the largest swath of different types of devices.
You have no obligation to be locked into a contract (or even any service) for a telephone. If you go to a carrier store you can purchase a device at full price and leave the store without activating any service on it (In general, subject to change at the whim of whatever store you are in =) If you intend to by a phone for full price expect the range of prices to be $380-$600. From what I can tell about your situation I would think that a phone is best route for you to start off with. In addition to being able to buy from a carrier, Google also from time to time directly sells a "Nexus" device which is released with stock(ish) android OS (no skins etc..) The current device in this line is the Galaxy Nexus which is being sold directly through the (former) Android Market That is a good choice because it is more or less the latest generation of hardware, and the newest OS (these Nexus devices tend to receive their OS updates in a more timely manner than carrier tied devices). In fact the first Nexus device was marketed heavily toward developers, this line of phones was meant to be used for development.

Is a tablet PC the type of device I should get?

If you intend to create applications for tablets then yes. If you intend to develop phone applications you should really be testing on a phone.

Should I get a device with Android 2.3 or 4.0?

Ideally both on different devices. If you must pick one, then it depends on your budget 4.0 is only on the newest devices right now so they are likely going to be more expensive than some of the devices you can find with 2.3. (although $399 for the Galaxy Nexus might be hard to beat in price, even for some of the 2.3 devices for sale)

In addition to wifi, what else should I look for?

On phones that can be readily purchased in the US your choices are basically boiled down to only a few things. Screen Size (anywhere from tiny to pretty damn big for a phone), HardwareKeyboard(in a few different shapes and sizes), Camera (if you care about it). In general most of the other features are fairly standard (i.e. bluetooth, gps, accelerometer, etc..) The other thing to consider would be "Oomph", despite being called phones what people are carrying around today are small computers. They have CPU, GPU and RAM just the same as PCs. Battery life is the last major divisor, there is a fairly wide range of battery life expectancy (hint, massive screen and multiple cores need lots of battery). However since you don't seem to want to use this device as your phone some of this stuff may not matter as much to you.

Are there any brands/models I should avoid?

Anything in the list of your first ebay link. In general (in the US) the major phone manufactures are: HTC, Motorola, Sony, LG, Samsung. There are many other devices out there that are nice as well. But these guys are generally the ones consistently pumping out the most used phones. Idealy you should aim for a spread of device's made by different manufacturers. The custom skins and addons they like to use in their versions of the OS tend to like extra testing. Having one of each will help you help the largest chunk of your users.

Is there any point in buying used?

There are good deals to be had on nice but slightly dated phones. If you don't know what you are looking at I'd stay away though, it could be easy to get ripped off.

A: Well it does not seem like you need a very expensive device. Guess you could buy Google's and Samsung's old Nexus S which is not the newest around but still has android 4 because it's Google's "offcial" or something. And since it rolled out with 2.3, you should be able to download the old version somewhere and flash it. That phone should be cheaper, especially second-hand.
I mean since there are so many devices with different screen sizes and all you can't really find one that will reveal what other device-users will think of your apps.

A: *

*Carrier options should be a non-issue for development.  You can buy any Android phone for any
carrier including unlocked, and that should not affect your development flexibility.

*Get the lowest version you can have. 2.3 and 2.2 have the most market shares right now. There is no reason to get 4.0, unless you are developing specifically for Android OS 4.0 and above (meaning that you actually use API that only exist on 4.0 and above and not lower).

*Your development platform also affects what phone model to use.  If you use Windows, get a phone that comes with Windows drivers.  It'd be a bummer to buy one only to find out that Windows can't detect it.  Mac and Linux do not need drivers, as they are both UNIX based.

A: You should get a phone. If you don't want to use it you don't have to... but most likely the majority of your users will be on a device. If you want a device that is always up to date and is great for testing I recommend the Galaxy Nexus.
Since most Android phone users are not on the most up to date os version, I prefer testing on a phone with 2.3

A: If you temporarily need a phone to test your app, Sony Mobile developer program has a phone loaner program in US and Canada where you can borrow a device for up to 30 days.
http://developer.sonymobile.com/wportal/devworld/phones/borrow-a-phone
/Magnus E
Sony Mobile


text:
Q: Qualitative searches in neo4j graph algorithms We have different entities and relationships in our neo4j graph. So there are different types of triangles that can potentially be in the graph,
CITATION -> CITATION -> CITATION
CITATION -> CITATION -> JOURNAL
to name a few. I was able to find all these in the algorithm to find triangles:
CALL algo.triangle.stream(null, null)
YIELD nodeA, nodeB, nodeC

RETURN labels(algo.asNode(nodeA)) AS nodeA, nodeA AS nodeAinfo, labels(algo.asNode(nodeB)) AS nodeB, algo.asNode(nodeB).CITATION AS nodeBinfo, labels(algo.asNode(nodeC)) AS nodeC, algo.asNode(nodeC).CITATION AS nodeCinfo ORDER BY labels(algo.asNode(nodeA))

However, I am wondering if there is a way to specify the type of triangle in as a parameter of the function. I think I am only able to input a node type and a relationship type in the algorithm.
CALL algo.triangle.stream('citation', 'cited_by')
YIELD nodeA, nodeB, nodeC

What if there are a two or more node types and two or more relationships types - is there a way to specify these? Thanks.

A: The first 2 arguments to algo.triangle.stream can be Cypher queries returning the native IDs of the nodes of interest and the end-nodes of the relationships of interest, respectively. To indicate you are using this syntax, the config map must specify a graph property with the value of 'cypher'.
For example, here is a snippet that shows how to get triangles involving CITATION and JOURNAL nodes, and cited_by and referenced_by relationships:
CALL algo.triangle.stream(
  'MATCH (p) WHERE ANY(lbl IN ["CITATION", "JOURNAL"] WHERE lbl IN LABELS(p)) RETURN id(p) as id',
  'MATCH (p1)-[r]->(p2) WHERE TYPE(r) IN ["cited_by", "referenced_by"] RETURN id(p1) as source,id(p2) as target',
  {graph:'cypher'})
YIELD nodeA, nodeB, nodeC
...


text:
Q: In which cases are IEnumerable.Count optimized? Using reflector I have noticed that System.Linq.Enumerable.Count method has a condition in it to optimize it for the case when the IEnumerable<T> passed is in fact an ICollection<T>. If the cast succeeds the Count method does not need to iterate over every element, but can call the Count method of ICollection.
Based on this I was starting to think that IEnumerable<T> can be used like a readonly view of a collection, without having the performance loss that I originally expected based on the API of IEnumerable<T>
I was interested whether the optimization of the Count still holds when the IEnumerable<T> is a result of a Select statement over an ICollection, but based on reflected code this case is not optimized, and requires an iteration through all elements.
Do you draw the same conclusions from reflector? What could be the reason behind the lack of this optimization? I seems like there is a lot of time wasted in this common operation. Does the spec require that the each element is evaluated even if the Count can be determined without doing that?

A: It doesn't really matter that the result of Select is lazily evaluated. The Count is always equivalent to the count of the original collection so it could have certainly been retrieved directly by returning a specific object from Select that could be used to short-circuit evaluation of the Count method.
The reason it's not possible to optimize out evaluation of the Count() method on the return value of a Select call from something with determined count (like a List<T>) is that it could change the meaning of the program.
The selector function passed to Select method is allowed to have side effects and its side effects are required to happen deterministically, in a predetermined order.
Assume:
new[]{1,2,3}.Select(i => { Console.WriteLine(i); return 0; }).Count();

The documentation requires this code to print

1
  2
  3

Even though the count is really known from the start and could be optimized, optimization would change the behavior of the program. That's why you can't avoid enumeration of the collection anyway. That's exactly one of the reasons why compiler optimizations are much easier in pure functional languages.

UPDATE: Apparently, it's not clear that it's perfectly possible to implement Select and Count so that Selects on ICollection<T> will still be lazily evaluated but the Count() will be evaluated in O(1) without enumerating the collection. I'm going to do that without changing the interface of any methods. A similar thing is already done for ICollection<T>:
private interface IDirectlyCountable {
    int Count {get;}
}
private class SelectICollectionIterator<TSource,TResult> : IEnumerable<T>, IDirectlyCountable {
     ICollection<TSource> sequence;
     Func<TSource,TResult> selector;
     public SelectICollectionIterator(ICollection<TSource> source, Func<TSource,TResult> selector) {
         this.sequence = source;
         this.selector = selector;
     }
     public int Count { get { return sequence.Count; } }
     // ... GetEnumerator ...
}
public static IEnumerable<TResult> Select<TSource,TResult>(this IEnumerable<TSource> source, Func<TSource,TResult> selector) {
    // ... error handling omitted for brevity ...
    if (source is ICollection<TSource>)
       return new SelectICollectionIterator<TSource,TResult>((ICollection<TSource>)source, selector);
    // ... rest of the method ...
}
public static int Count<T>(this IEnumerable<T> source) {
    // ...
    ICollection<T> collection = source as ICollection<T>;
    if (collection != null) return collection.Count;
    IDirectlyCountable countableSequence = source as IDirectlyCountable;
    if (countableSequence != null) return countableSequence.Count;
    // ... enumerate and count the sequence ...
}

This will still evaluate the Count lazily. If you change the underlying collection, the count will get changed and the sequence is not cached. The only difference will be not doing the side effects in the selector delegate.

A: Edit 02-Feb-2010:
As I see it, there are at least two ways to interpret this question.

Why does the Select<T,
  TResult> extension method, when
  called on an instance of a class that
  implements ICollection<T>, not
  return an object that provides a
  Count property; and why does the
  Count<T> extension method not
  check for this property so as to
  provide O(1) performance when the two
  methods are chained?

This version of the question makes no false assumptions about how Linq extensions work, and is a valid question since a call to ICollection<T>.Select.Count will, after all, always return the same value as ICollection<T>.Count. This is how Mehrdad interpreted the question, to which he has provided a thorough response.
But I read the question as asking...

If the Count<T> extension method provides O(1)
  performance for an object of a class
  implementing ICollection<T>, why
  does it provide O(n) performance for
  the return value of the
  Select<T, TResult>
  extension method?

In this version of the question, there is a mistaken assumption: that the Linq extension methods work together by assembling little collections one after another (in memory) and exposing them through the IEnumerable<T> interface.
If this were how the Linq extensions worked, the Select method might look something like this:
public static IEnumerable<TResult> Select<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector) {
    List<TResult> results = new List<TResult>();

    foreach (T input in source)
        results.Add(selector(input));

    return results;
}

Moreover, if this were the implementation of Select, I think you'd find most code that utilizes this method would behave just the same. But it would be wasteful, and would in fact cause exceptions in certain cases like the one I described in my original answer.
In reality, I believe the implementation of the Select method is much closer to something like this:
public static IEnumerable<TResult> Select<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector) {
    foreach (T input in source)
        yield return selector(input);

    yield break;
}

This is to provide lazy evaluation, and explains why a Count property is not accessible in O(1) time to the Count method.
So in other words, whereas Mehrdad answered the question of why Select wasn't designed differently so that Select.Count would behave differently, I have offered my best answer to the question of why Select.Count behaves the way it does.

ORIGINAL ANSWER:
Method side effects is not the answer.
According to Mehrdad's answer:

It doesn't really matter that the
  result of Select is lazily evaluated.

I don't buy this. Let me explain why.
For starters, consider the following two very similar methods:
public static IEnumerable<double> GetRandomsAsEnumerable(int N) {
    Random r = new Random();

    for (int i = 0; i < N; ++i)
        yield return r.NextDouble();

    yield break;
}

public static double[] GetRandomsAsArray(int N) {
    Random r = new Random();

    double[] values = new double[N];
    for (int i = 0; i < N; ++i)
        values[i] = r.NextDouble();

    return values;
}

OK, what do these methods do? Each one returns as many random doubles as the user desires (up to int.MaxValue). Does it matter whether either method is lazily evaluated or not? To answer this question, let's take a look at the following code:
public static double Invert(double value) {
    return 1.0 / value;
}

public static void Test() {
    int a = GetRandomsAsEnumerable(int.MaxValue).Select(Invert).Count();
    int b = GetRandomsAsArray(int.MaxValue).Select(Invert).Count();
}

Can you guess what will happen with these two method calls? Let me spare you the trouble of copying this code and testing it out yourself:
The first variable, a, will (after a potentially significant amount of time) be initialized to int.MaxValue (currently 2147483647). The second one, b, will very likely be interrupted by an OutOfMemoryException.
Because Select and the other Linq extension methods are lazily evaluated, they allow you to do things you simply could not do otherwise. The above is a fairly trivial example. But my main point is to dispute the assertion that lazy evaluation is not important. Mehrdad's statement that a Count property "is really known from the start and could be optimized" actually begs the question. The issue might seem straightforward for the Select method, but Select is not really special; it returns an IEnumerable<T> just like the rest of the Linq extension methods, and for these methods to "know" the Count of their return values would require full collections to be cached and therefore prohibit lazy evaluation.
Lazy evaluation is the answer.
For this reason, I have to agree with one of the original responders (whose answer now seems to have disappeared) that lazy evaluation really is the answer here. The idea that method side effects need to be accounted for is really secondary, as this is already ensured as a byproduct of lazy evaluation anyway.
Postscript: I've made very assertive statements and emphasized my points mainly because I wanted to be clear on what my argument is, not out of any disrespect for any other responses, including Mehrdad's, which I feel is insightful but misses the mark.

A: An ICollection knows the number of items (Count) it contains. It doesn't have to iterate any items to determine it. Take for example the HashSet class (which implements ICollection).
An IEnumerable<T> doesn't know how many items it contains. You have to enumerate the whole list to determine the number of items (Count).
Wrapping the ICollection in a LINQ statement, doesn't make it more efficient. No matter how you twist and turn, the ICollection will have to be enumerated.


text:
Q: Error during kivy installation on Windows 10 When I try to install kivy to my computer I get the follow error:
Error executing cmd /u /c "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" x86 && set
Screen with the error as shown below.


text:
Q: Latitude and Longitude showing 0,0 I want to show latitude and longitude through the JSON data but everytime i am getting the value of 0 for both latitude and longitude.I google it and find that i have to add runtime permission to solve but i am not able to solve the issue.How can this issue be solved??
GpsLocation class
public class GpsLocation extends Service implements LocationListener {
    private final Context mContext;
    // flag for GPS status
    boolean isGPSEnabled = false;
    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS status
    boolean canGetLocation = false;
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    double speed, direction;
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GpsLocation(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }

                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if(locationManager != null){
            locationManager.removeUpdates(GpsLocation.this);
        }
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        // return longitude
        return longitude;
    }

    public double getSpeed() {
        return speed;
    }

    public double getDirection() {
        return direction;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will launch Settings Options
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");
        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            speed = location.getSpeed();
            direction = location.getBearing();
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

NearMe
public class NearMe extends Fragment {
    MapView mMapView;
    private GoogleMap googleMap;

    GpsLocation gpsLocation;
    double longitude, latitude;
    private ProgressDialog pDialog;
    ArrayList<MySchool> al_school = new ArrayList<MySchool>();
    ArrayList<MyCollege> al_college = new ArrayList<MyCollege>();
    ArrayList<MyUniversity> al_university = new ArrayList<MyUniversity>();
    private static final String TAG = NearMe.class.getSimpleName();
    private static final String urlSchool = "http://www.myeducationhunt.com/api/v1/schools";
    private static final String urlCollege = "http://www.myeducationhunt.com/api/v1/colleges";
    private static final String urlUniversity = "http://www.myeducationhunt.com/api/v1/universities";

    Context mContext;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View v = inflater.inflate(R.layout.fragment_near_me, container, false);

        final LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        if (isConnected()) {
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                Toast.makeText(getContext(), "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();

                mMapView = (MapView) v.findViewById(R.id.mapView);
                mMapView.onCreate(savedInstanceState);

                mMapView.onResume();

                try {
                    MapsInitializer.initialize(getActivity().getApplicationContext());

                } catch (Exception e) {
                    e.printStackTrace();
                }

                gpsLocation = new GpsLocation(getContext());
                if (gpsLocation.canGetLocation()) {

                    latitude = gpsLocation.getLatitude();
                    longitude = gpsLocation.getLongitude();

                    Toast.makeText(getContext(), "latitude:" + latitude + "Longitude:" + longitude, Toast.LENGTH_LONG).show();
                } else {

                    gpsLocation.showSettingsAlert();
                }

                pDialog = new ProgressDialog(getContext());
                pDialog.setMessage("Loading…");
                pDialog.show();

                mMapView.getMapAsync(new OnMapReadyCallback() {
                    @Override
                    public void onMapReady(GoogleMap mMap) {
                        googleMap = mMap;

                        //     CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(new LatLng(gpsLocation.getLatitude(), gpsLocation.getLongitude()));
                        //     CameraUpdate zoom = CameraUpdateFactory.zoomTo(14);
                        //     mMap.moveCamera(cameraUpdate);
                        //     mMap.animateCamera(zoom);

                        //  mMap.animateCamera(cameraUpdate);

                        LatLng schoollatlng = new LatLng(latitude, longitude);
                        googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
                        CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(10).build();
                        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(gpsLocation.getLatitude(), gpsLocation.getLongitude()), 14.0f));

                        drawSchoolMarker();
                        drawCollegeMarker();
                        drawUniversityMarker();
                    }
                });
            } else {
                showGPSDisabledAlertToUser();
            }
        } else {

            Toast.makeText(getContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
        }

        return v;
    }

    public boolean isConnected() {
        ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    private void drawSchoolMarker() {

        JsonArrayRequest schoolRequest = new JsonArrayRequest(urlSchool,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                MySchool school = new MySchool();

                                school.setId(obj.getInt("id") + " ");
                                school.setName(obj.getString("name"));
                                if (obj.getString("latitude") == "null") {
                                    school.setLatitude(Double.parseDouble("27.6712"));
                                } else {
                                    school.setLatitude(Double.parseDouble(obj.getString("latitude")));
                                }

                                if (obj.getString("longitude") == "null") {
                                    school.setLongitude(Double.parseDouble("85.2865"));
                                } else {
                                    school.setLongitude(Double.parseDouble(obj.getString("longitude")));
                                }

                                al_school.add(school);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        //iterate from arraylist
                        for (MySchool schoolItr : al_school) {

                            View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker, null);
                            TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
                            numTxt.setText(schoolItr.getName());
                            LatLng latlng = new LatLng(schoolItr.getLatitude(), schoolItr.getLongitude());
                            googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(schoolItr.getName()));
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(schoolRequest);
    }

    private void drawCollegeMarker() {
        JsonArrayRequest collegeRequest = new JsonArrayRequest(urlCollege,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                MyCollege college = new MyCollege();

                                college.setId("" + obj.getInt("id"));
                                college.setName("" + obj.getString("name"));
                                //college.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
                                //college.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
                                if (obj.getString("latitude") == "null") {

                                    college.setLatitude(Double.parseDouble("27.6712"));
                                } else {

                                    college.setLatitude(Double.parseDouble(obj.getString("latitude")));
                                }

                                if (obj.getString("longitude") == "null") {
                                    college.setLongitude(Double.parseDouble("27.6712"));
                                } else {
                                    college.setLongitude(Double.parseDouble(obj.getString("longitude")));

                                }

                                al_college.add(college);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        //iterate from arraylist
                        for (MyCollege collegeItr : al_college) {

                            View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_college, null);
                            TextView numTxt = (TextView) marker.findViewById(R.id.txt_college);
                            numTxt.setText(collegeItr.getName());
                            LatLng latlng = new LatLng(collegeItr.getLatitude(), collegeItr.getLongitude());
                            googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(collegeItr.getName()));
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(collegeRequest);
    }

    private void drawUniversityMarker() {
        JsonArrayRequest uniRequest = new JsonArrayRequest(urlUniversity,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                MyUniversity university = new MyUniversity();

                                university.setId("" + obj.getInt("id"));
                                university.setName("" + obj.getString("name"));
                                //university.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
                                //university.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
                                if (obj.getString("latitude") == "null") {

                                    university.setLatitude(Double.parseDouble("27.6712"));
                                } else {

                                    university.setLatitude(Double.parseDouble(obj.getString("latitude")));
                                }

                                if (obj.getString("longitude") == "null") {
                                    university.setLongitude(Double.parseDouble("27.6712"));
                                } else {
                                    university.setLongitude(Double.parseDouble(obj.getString("longitude")));

                                }

                                al_university.add(university);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        //iterate from arraylist
                        for (MyUniversity universityItr : al_university) {

                            View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_university, null);
                            TextView numTxt = (TextView) marker.findViewById(R.id.txt_university);
                            numTxt.setText(universityItr.getName());
                            LatLng latlng = new LatLng(universityItr.getLatitude(), universityItr.getLongitude());
                            googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(universityItr.getName()));

                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(uniRequest);
    }

    public static Bitmap createDrawableFromView(Context context, View view) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
        view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
        view.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

        return bitmap;
    }

    private void showGPSDisabledAlertToUser() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
                .setCancelable(false)
                .setPositiveButton("Goto Settings Page To Enable GPS",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent callGPSSettingIntent = new Intent(
                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(callGPSSettingIntent);
                            }
                        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }

}

Logcat shows the issue of   java.lang.SecurityException: "network" location provider requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.
04-30 14:42:43.089 13948-13948/com.example.user.educationhunt W/System.err: java.lang.SecurityException: "network" location provider requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.
04-30 14:42:43.089 13948-13948/com.example.user.educationhunt W/System.err:     at android.os.Parcel.readException(Parcel.java:1620)
04-30 14:42:43.089 13948-13948/com.example.user.educationhunt W/System.err:     at android.os.Parcel.readException(Parcel.java:1573)
04-30 14:42:43.089 13948-13948/com.example.user.educationhunt W/System.err:     at android.location.ILocationManager$Stub$Proxy.requestLocationUpdates(ILocationManager.java:606)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.location.LocationManager.requestLocationUpdates(LocationManager.java:880)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.location.LocationManager.requestLocationUpdates(LocationManager.java:464)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at com.example.user.educationhunt.pojos.GpsLocation.getLocation(GpsLocation.java:74)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at com.example.user.educationhunt.pojos.GpsLocation.<init>(GpsLocation.java:55)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at com.example.user.educationhunt.fragment.NearMe.onCreateView(NearMe.java:128)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:536)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.os.Handler.handleCallback(Handler.java:746)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5443)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
04-30 14:42:43.090 13948-13948/com.example.user.educationhunt W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)


text:
Q: Listen to UDP Socket in Background using GCDAsyncUdpSocket I have one application that connects to a network device (in LAN) over UDP and listen for new messages using GCDAsyncUdpSocket. It works fine in foreground but in background it is not able to respond.  I want to show a local notification when I receive a message from UDP. Please suggest how we can achieve this by following Apple policies.
Thanks & Regards,
Amit

A: All sockets are set to sleep when the app is in background.
The option you have is to do Fetching Small Amounts of Content Opportunistically
In case your app is a VoIP app, you can keep a TCP socket live and the OS will inform you when data is received. This way you can set a "wake up" message to be sent over TCP and then use UDP for the actual data transfer.


text:
Q: Could not find com.android.tools.build:gradle:4.0.1. - android I'm using Android Studio Dolphin | 2021.3. I want to get gradle 4.0.1 but I got this:
Could not find com.android.tools.build:gradle:4.0.1.
Searched in the following locations:
  - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/4.0.1/gradle-4.0.1.pom
  - https://jcenter.bintray.com/com/android/tools/build/gradle/4.0.1/gradle-4.0.1.pom
Required by:
    project :
Add google Maven repository and sync project
Open File

build.gradle:
buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        maven { url "https://jitpack.io" }

    }
}

gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip


text:
Q: rpm installation fails due to depencency /bin/sh not found i am trying to install a package using rpm, for which i have created a different database using rpmdb --initdb --dbpath $HOME/myrpmdb  and specifying that path in the --dbpath while insatlling.
The error i am getting is
root@jason:su rpm --dbpath $HOME/myrpmdb -ivh XXX.rpm
error: Failed dependencies:
/bin/sh is needed by XXX

and /bin/sh exist
Is there some way that i can specify this to the installer?
Is there something i missed during the creation of different rpm database cause of which now it not able to fine the default commands?

A: error: Failed dependencies:
/bin/sh is needed by XXX

This happens because bash rpm is not available in the new rpmdb path. You would have to use following to get the rpm installed.
# rpm --dbpath $HOME/myrpmdb --nodeps -ivh XXX.rpm

A: Right way install rpm via alien:
alien -i my_rpm_name.rpm

If alien is not installed:
sudo apt-get install alien

A: Because you've told it to use a completely different database, rpm doesn't look at the system database which is where /bin/sh would be found.

A: Why use a different rpm database?  There should be a really good reason to go this route...
If you must have a private rpm db, you can copy the system db into your private one
cp /var/lib/rpm/* ~/myrpmdb/.
installing with --nodeps may be the easiest way... copying the rpm db is really sub-optimal, it will soon be out of date and not reflect the state of the system.


text:
Q: How to replace current page in Ionic? I have this flow:
Contacts page -> navController.push(NewContact) -> navController.push(ContactCreated)
How do I make that on the ContactCreated page the "Back" button return user to root "Contacts" page instead of the NewContact page? So I would like to replace a page in the navigation stack.
I'm using Ionic 3.

A: You can do it as shown below. Here is the doc.
import { Navbar } from 'ionic-angular';

@Component({
  selector: 'your-page',
  template: `
    <ion-header>
      <ion-navbar>
        <ion-title>
           Your Page
        </ion-title>
      </ion-navbar>
    </ion-header>

    <ion-content>
    ...
    </ion-content>
   `
})
export class YourPage {
  @ViewChild(Navbar) navBar: Navbar;
  constructor(private navController: NavController){}

  ionViewDidLoad() {
    this.navBar.backButtonClick = (e:UIEvent)=>{
      this.navController.setRoot('Contacts');
    }
  }
}

A: Simply use popToRoot() function instead of pop().
this.navCtrl.popToRoot ();

A: Do pop immediately followed by push with disabled animation:
this.navCtrl.pop({animate: false});
this.navCtrl.push(ContactCreated, null, {animate: false});

A: This way you add the page on top of the stack, and next remove the actual from the second position, without invoking any other page enter events:
self.navCtrl.push(NextPage, nextParams).then(()=>{
    let index = self.viewCtrl.index;
    self.navCtrl.remove(index);
});

A: If you want to replace the last page in the navigation stack, you can do it like this:
navController.pop()
    .then(() => navController.push(ContactCreated))
    .catch(() => navController.push(ContactCreated));


text:
Q: essentially same code,but different result This is UCB CS61A's firt project hog 's problem5
this is wrong code(my code)
while(score0<goal and score1<goal):
    if who==0 :
        cur_strategy = strategy0
        cur_score = score0
        cur_op_score=score1
        cur_op_strategy = strategy1
    else:
        cur_strategy = strategy1
        cur_score = score1
        cur_op_score=score0
        cur_op_strategy = strategy0
    cur_score=cur_score+take_turn(cur_strategy(cur_score,cur_op_score),cur_op_score,dice)

    if(extra_turn(cur_score,cur_op_score)==False):
        who=other(who)

this is the correct code(I have tested it)
while score0 < goal and score1 < goal:
        if who == 0:
            num_rolls = strategy0(score0, score1)
            score0 += take_turn(num_rolls, score1, dice)
            who = other(who) if extra_turn(score0, score1) == False else who
        else:
            num_rolls = strategy1(score1, score0)
            score1 += take_turn(num_rolls, score0, dice)
            who = other(who) if extra_turn(score1, score0) == False else who

But actually,I think these two codes are essentially same.
I don't know whether this is the problem (the quote from the project)

Only call a strategy function once per turn (or risk breaking the GUI).

A: I think that comes from the fact that in order to update the score0 an score1 variables, you define cur_score and update it instead. The problem is that cur_score is only a copy of the score you want to update, it is not the same object.


text:
Q: Find and replace text in bibentry using macros I want to be able to display a bibliography entry but I want to highlight some part of it, specifically some author, but not all. So far I am able to create the bib entry in the middle of the text, and I am also able to do a find and replace of text (copied from here). However, when I try to do the find and replace the text of the bib entry it does not work.
Here is my example bib tex file:
\begin{filecontents}{mybib.bib}
{

@InProceedings{pcl,
  author    = {Radu Bogdan Rusu and Steve Cousins},
  title     = {{3D is here: Point Cloud Library (PCL)}},
  booktitle = {{IEEE International Conference on Robotics and Automation (ICRA)}},
  month     = {May 9-13},
  year      = {2011},
  address   = {Shanghai, China}
  }
@misc{opencv,
  title={Open Source Computer Vision Library},
  author={Itseez},
  year={2015},
  howpublished = {\url{https://github.com/itseez/opencv}}
  }
@manual{opencv_manual,
  title = {The OpenCV Reference Manual},
  organization = {Itseez},
  edition = {2.4.9.0},
  month = {April},
  year = {2014},
  notes = {See \url{http://opencv.org/}}
  }
}

\end{filecontents}

\documentclass{article}
\usepackage{natbib}
\usepackage{bibentry}
\usepackage{hyperref}
\usepackage{etoolbox}
\nobibliography*

% \patchcmd{<cmd>}{<search>}{<replace>}{<success>}{<failure>}
\newcommand{\searchreplace}[3]{\patchcmd{#1}{#2}{#3}{}{}}
\newcommand{\bibelement}[1]
{
    \begin{NoHyper}% In my real project I need the bibentry package to work with hyperref package.
        \bibentry{#1}
    \end{NoHyper}
}
\newcommand{\bibelementhighlight}[2]
{
    %\searchreplace{\bibelement{#1}}{#2}{\textbf{#2}}
    \newcommand{\auxbibliography}{\bibelement{#1}}
    First time: \auxbibliography \\
    \searchreplace{\auxbibliography}{#2}{\textbf{#2}}
    Second time: \auxbibliography
}

\begin{document}

\newcommand{\afgfgft}{Rusu, R. B. and Cousins, S.}
\afgfgft \\
\searchreplace{\afgfgft}{Rusu, R. B.}{\textbf{Rusu, R. B.}}
\afgfgft

Here are some citations for articles: \cite{pcl} and \cite{opencv} and \bibelement{opencv_manual} and the one which I want to highlight:
\begin{itemize}
    \item \bibelementhighlight{pcl}{Rusu}
\end{itemize}

\bibliographystyle{apalike}
\bibliography{mybib.bib}

\end{document}

When I compile this code I get the following (note that there is also added drawing and text explaining what I want to get):

where everything works fine except for the substitution of Rusu the second time the bibelement is displayed. After messing arround I think that this might be because \bibitem is expanded after the string replace. Can somebody give me a hint on how to solve it?