Plotting large graph in R with igraph

Question: I was trying to plot a network with 200 thousands nodes and 8 millions edges. The code I used was here:
<code>library(igraph)
file.choose()
xlist<-read.graph("/Users/quyao/Desktop/redstar_relation.txt", format="ncol", directed=TRUE)
xlist
png('my_png.png', width = 1600, height =900)
plot(xlist)
dev.off()
</code>
I got this:

It's hard to study the topology with this kind of picture. Do you have any suggestions?
As there are too many nodes and edges, change the layout through the parameter 'layout' may not be so helpful.
Constructing this picture took about one and half hours using my code, how could i make it faster?
Many thanks.
Comment: I dare guessing that visualizing such a large network will not be get you anywhere you want to go. You'd be better off by first defining what you are looking for and what you try to study, then either split your data or make some pre-processing of your data, computing some statistics, or aggregations or whatever - and only then visualize whatever aspect of the graph/analysis that will be intelligible and helpful in making your point. you will also save yourself the wait for the graph to print.
Comment: It's going to be hard to study 200k nodes visually without splitting up/merging the data.
Comment: Could you give us some kind of data to work with?   Currently we can't reproduce your graph.
Comment: Thanks to you all. @amit is right, I'd better to clear what I am looking for and trying to study first and make some pre-processing before plotting.
Answer: Consider using another software for visualization. I generally use Gephi for graphs with a magnitude up to 150 000 nodes.
However it really depends on how much RAM your machine has (mine has 8 GB). There is also the possibility to expand RAM allocation to Gephi by modifying their configuration file (it is not allocated automatically like in RStudio.
Comment: You can either "prune" your data and filter the nodes that are less signifcant based on their betweenness or degree, or you can increase the ram of your laptop. Unfortunately graph computation is very RAM intensive.
Comment: So what do you do with more than 150k nodes?

Plotting large graph in R with igraph


how to combine the common key and join the values in the dictionary python

Question: I have one list which contain a few dictionaries.
   [{u'TEXT242.txt': u'work'},{u'TEXT242.txt': u'go to work'},{u'TEXT1007.txt': u'report'},{u'TEXT797.txt': u'study'}]

how to combine the dictionary when it has the same key. for example:
u'work', u'go to work'are under one key:'TEXT242.txt', so that i can remove the duplicated key.
 [{u'TEXT242.txt': [u'work', u'go to work']},{u'TEXT1007.txt': u'report'},{u'TEXT797.txt': u'study'}]

Answer: The setdefault method of dictionaries is handy here... it can create an empty list when a dictionary key doesn't exist, so that you can always append the value.
dictlist = [{u'TEXT242.txt': u'work'},{u'TEXT242.txt': u'go to work'},{u'TEXT1007.txt': u'report'},{u'TEXT797.txt': u'study'}]
newdict = {}

for d in dictlist:
    for k in d:
        newdict.setdefault(k, []).append(d[k])

Answer: from collections import defaultdict
before = [{u'TEXT242.txt': u'work'},{u'TEXT242.txt': u'go to work'},{u'TEXT1007.txt': u'report'},{u'TEXT797.txt': u'study'}]
after = defaultdict(list)
for i in before:
    for k, v in i.items():
        after[k].append(v)

out:
defaultdict(list,
            {'TEXT1007.txt': ['report'],
             'TEXT242.txt': ['work', 'go to work'],
             'TEXT797.txt': ['study']})

This technique is simpler and faster
  than an equivalent technique using dict.setdefault()


Merge Sort: Are the additional array copies necessary?

Question: In "Introduction to Algorithms" the merge sort algorithm is implemented with a helper function called MERGE(A, p, q, r) - that is merging two previously sorted sequences .
This function introduces two additional arrays L and R .
MERGE(A, p, q, r)
1 n1 ← q − p + 1
2 n2 ←r − q
3 create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
.....

By "create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]" I understand to allocate additional memory for both of them .
Is it possible to re-write this function, so that I won't need the additional memory, and to operate directly to A ?
Answer: Sure. It is called in-place merge sort.
Wikipedia say it is complicated -- but it is not always true. Some are not as complicated as others, if you don't care about the run-time.
There are a few variance, some are stable, some are non-stable. See the "implementation" section under NIST DIAGS for some example.
Comment: see also this question: http://stackoverflow.com/questions/2571049/how-to-sort-in-place-using-the-merge-sort-algorithm
Answer: Yes, it's called in-place merge sort, but as Wikipedia puts it:

Sorting in-place is possible (e.g., using lists rather than arrays) but is very complicated, and will offer little performance gains in practice, even if the algorithm runs in O(n log n) time. (Katajainen, Pasanen & Teuhola 1996)
Answer: That is possible. http://www.diku.dk/hjemmesider/ansatte/jyrki/Paper/mergesort_NJC.ps


How to sum certain columns row-by-row in R?

Question: I have a dataframe that looks like this (with values for all Threads as the frame progresses):
head(icdata)
     Count Thread1 Thread2 Thread3 Thread4 Thread5 Thread6 Thread7 Thread8
1  8543034  555724      NA      NA      NA      NA      NA      NA      NA
2 26632195  730156      NA      NA      NA      NA      NA      NA      NA
3 46332821  730679      NA      NA      NA      NA      NA      NA      NA
4 47491531   22694   16715      NA      NA      NA      NA      NA      NA
5 48939781   62418  114842      NA      NA      NA      NA      NA      NA
6 50397031   63560   38147      NA      NA      NA      NA      NA      NA

I'd like to plot Count against the sum of the various threads, but cannot work out just how to do it - eg the NA values seem to cause me problems in just summing the row. Sorry to ask such a basic question but how can I do this?
(Additionally, I'd like to be able to normalise this total against the difference in the Counts, but that is less essential)
Comment: Have a close look at `?sum`, paying particular attention to its description of the function's `na.rm` argument. Then do something like `cbind(df[1], Threadsum=apply(df[-1], 1, sum, na.rm=TRUE))`
Comment: Thanks, but it looks like nico's answer is just as acceptable. Cheers.
Comment: Josh, please make that an answer and I'll accept it
Answer: Use rowSums to sum the values in the various threads. The na.rm parameters takes care of NAs. Furthermore, you want to exclude the first column from the sum so:
thread.sum <- rowSums(icdata[,-1], na.rm=TRUE)
plot(icdata[,1], thread.sum)


Stability of equilibrium point origin for the equation $x'' + x + x^3(4 + \sin x) = 0$

Question: The question asks to discuss the stability of equilibrium point origin for the equation $x'' + x + x^3(4 + \sin x) = 0$
Attempt: Given equation $x'' + x + x^3(4 + \sin x) = 0$
now taking $x' = y$ and $y' = -x -x^3(4 + \sin x) $
Let $v = (x,y)$
$\dot v = f(v) = f(x,y) = (y , -y -x^3(4 + \sin x))$
Now (0,0) is a critical point of the system $\dot v = f(v)$ as $f(0,0) = (0,0)$
$\ $
What would be the required $C^1$ function '"V" (which is positive in a deleted neighbourhood of the point?) that is to be taken here so that I can use Lyapunov to get a set of conditions then to solve the problem?
Comment: Should be $y' = -x -x^3(4 + \sin x)$ not $y' = -y -x^3(4 + \sin x)$
Comment: @Aryadeva right! fixed
Answer: Your equation is of the form $$x''+P'(x)=0$$ of a conservative mechanical system in one dimension with potential function $P(x)$. All solutions will have constant energy, that is, follow level curves $$\frac12x'^2+P(x)=E.$$ This, along with the linearization $x''+x=0$ close to the zero solution, completely determines the stability of that solution.


"Timeout / unknown" status in an asynchronous process execution

Question: So I have a case where we update user data in an external service in an asynchronous way. We have a table with users - each row gets a separate user with a separate request, is handled separately. We get the async responses from the external service by polling.
However, there can be a case where we don't get a response due to an error in the external service, however, it might have completed the request but just isn't responding properly to our polling which then results in a state where we don't know the actual state (did the data update or not).
Has anybody worked with such a situation and what would you do?

Just show the row as in error (red) state: timeout
Have a new state of "unknown/yellow" - request sent but response unknown;
Also ask the user to manually check and change the status to red or green?
Answer: It depends on the importance of the operation. You don't want to just warn the user and skip it for an important operation, e.g. salary-related matters or important invites.
Assuming it's an insignificant operation, in general, it should be displayed as unknown, briefly explaining what exactly could happen. It should also suggest retrying the operation only for the entries that result wasn't successful.


javascript += operator

Question: In my JSON javascript live pull I have:
    html += "
"+item.site+"	";

The += seems to strip out my tr td values
So I tried amending it to = which just seems to fail.. I tried setting td as a var and still no luck
Any ideas of a way round this, my js is basic so even if you think its silly your answer could help me greatly..
EDIT
to confuse things things further the = alone works in Firefox but on IE the items are loading hidden in the background.. I don't get why the browsers would perform so differently over the use of one + sign...
Comment: You don't seem to be closing the ``
Comment: How are you trying to use this `html` value?  How do you know those things are being stripped?
Comment: You should show us some more of your code. What is the value of `html` before the line you include? What are you doing with it after setting/appending to it?
Comment: EDIT They are displayed table less in the browser.. and viewing the output both tag are missing
Comment: When you say "output" do you mean the **html source**?  Or do you mean the rendered content in the browser?
Comment: The rendered output using firefox view selection source
Answer: try:
html += "
"+item.site+"
";

Your markup generated is invalid (not closing the anchor tag) so it's possible the browser isn't interpreting the html very well.
Comment: You should update your question then as it's misleading. I hope you didn't downvote because of that fact as someone did. You should also consider posting more code than one line as the line in question may not even be the issue at all.
Comment: that was just a mistake when rewriting it here haha
Comment: I didn't down vote you, I appreciate the help.. I'm bad at coding but now quite that bad hahah
Answer: x += y is just a shorthand for x = x + y. If you change it to html = "...", you'd be overwriting anything that already existed in the html variable.
How are your "tr td values" being stripped?
Comment: Clobbered... is that a technical term? ;)
Comment: Heh, I didn't mean to use it twice in my answer.

javascript += operator


MySQL Select the highest from last 50 rows

Question: I want to select the highest won from my last 50 rows.
But why is that not working?
I found that in other questions but i dont know why that doesnt work for me?
This is my query with that what i tried
SELECT max(won) from games WHERE game ='case' ORDER BY id DESC LIMIT 50

I want the highest won from the last 50 rows by DESC so i order by id DESC.
But than i get the highest won of everything won, not only from the last 50 rows.
Comment: Please add sample data.  Your query may already be correct, depending on what your logic is.
Answer: You could do the limit first and then get the max.
SELECT max(won) FROM
(
  SELECT * FROM games
  WHERE game ='case'
  ORDER BY id DESC LIMIT 50
) AS tbl

Answer: Try with subquery:
select max(won)
from
(SELECT * from games WHERE game ='case' ORDER BY id DESC LIMIT 50)a


Javascript : accessing function arguments generically

Question: Here is what I have :
var log = function(arg1, arg2){
    console.log("inside :" + arg1 + " / " + arg2);
};

var wrap = function(fn){
    return function(args){
        console.log("before :");
        fn(args);
        console.log("after :");
    }
};

var fn = new wrap(log);
fn(1,2);

It is wrong, because I'd like to get in the console :
before :
inside :1 / 2
after :

But I get this instead :
before :
inside :1 / undefined
after :

How can I tell javascript that args is all the arguments passed to the function returned by wrap ?
Answer: You can use apply to call a function with a specified 'this' and argument array, so try
var wrap = function(fn){
    return function(){
        console.log("before :");
        fn.apply(this, arguments);
        console.log("after :");
    }
};

Comment: Try fn.apply(this, arguments);
Comment: have made example more closely match what you are attempting


samsung range (fe710drs) is tripping the circuit breaker

Question: My samsung fe710drs electric range is tripping the circuit breaker any time more than two burners are on, or trying to set the oven for more than 350 degrees.
What's going on?

Circuit breaker has "40" on each of the two circuits for the double pole. No test button.
What is odd is that the circuit usually doesn't short until a few minutes after oven or range is on.  We cant figure out if the oven is the problem, or the circuit.
Wanted to add, its a 7 year old range and same circuit breaker. Just a new problem.
***any combo of 3 burners does it.  Or two burners and the oven.  Sometimes just the oven itself will flip the breaker, but only after a few minutes of it being on.
Breaker is warm after tripping
Comment: Tell us more about the circuit breaker. What are the numbers on the handles? (e.g. "15" or "20").  Is there a "TEST" button?
Comment: What kind of circuit breakers (do they have a test button?).  What size is the breaker it should be a double pole? Is this a new problem or a new stove?
Comment: Please use the [edit] link underneath your question to update it with new information and stop posting updates as answers to your question.
Comment: ...that's the main breaker you took a photo of, not the breaker that you indicated was tripping
Comment: Yes, does the breaker for this appliance have a TEST button on it, and what's the breaker amp rating (number on the handle)?
Comment: Is the breaker getting warm when it trips?
Comment: Also, what make and model is your breaker box?
Comment: Yes! Getting warm when it trips
Comment: @LizO'Neill -- can you get us photos of the breaker in question + the label on the inside door of the breaker box please?  Also, is it any trio of burners that trips the breaker, or do specific burners need to be involved?
Comment: The spec plate on our GE 4 burner range states 13.3 kW with 120/240 V. I didn't recheck the installation instructions but IIRC they specify a breaker not less than 40 A. The breaker is a 50 A because that was there originally to supply the builder installed integrated unit of 4 burner stove, double oven, exhaust fan. The current range has a single oven and the exhaust fan is on a separate circuit.
Answer: The 40A breaker is almost definitely the correct size.
The installation manual does not state breaker size but it refers to plug-in installation using ideally a 40A cord but 50A is OK. Plus 2 burners should not be anywhere near 40A. Which means either something is malfunctioning in the range or the breaker is failing.
If you can get an in-use current - clamp meter around one of the hots going to the breaker or to the receptacle then you can see whether it is overcurrent (>40A) or not. If it is overcurrent, range problem. If it is not overcurrent (load <= 40A, except possibly momentary small overage) and the breaker trips then the breaker is failing and tripping at low current (which is better than failing in the other direction, so don't complain).
Replacement breaker should be ~ $10 - $20, depending on manufacturer. Make sure you get the correct breaker for your panel. Standard breaker - no need to upgrade to GFCI or AFCI for a straight replacement (new install depends on locally adopted code).
If you don't have a clamp meter, you may want to just get a new breaker and try it.


Safe to delete the workshop folder in Steamapps?

Question: I don't know what this "workshop" folder does. Its size is 3.34 GB. I want to delete it because I must free up HD space.
Answer: The workshop folder holds content from Steam Workshop - mods and other in-game content that you've downloaded for your games. Just deleting the folder won't solve your problems, because Steam will attempt to re-synchronize your files with your Workshop subscriptions.
If you want to clear out Workshop items to free up space on your computer, you'll want to locate them in the respective games' Workshop pages and choose "Unsubscribe".


SpriteKit multidirectional scrolling

Question: I am developing a space shooter with SpriteKit for testing purposes.
The game field is 700 x 700 pixels/points large. obviously is does not fit into a iPhone screen. That means I need some sort of scrolling that affects players + enemies + bullet + asteroids. I searched google, but most subjects on scrolling refer to Cocos2D and nearly always to Cocos2D specific features, not provided by sprite kit. So the thing is this is my first game so I am not sure what the right way is to implement multidirectional scrolling. I hope you guys can give me a solution and/or hints/tutorials or anything else that helps me :D
Comment: What have you tried? people don't want to program your game for you. I understand you want hints or tuts but show some effort.
Answer: Create your "spaceship", create a camera node and in the updates method make your camera always center on the spaceship.
Something similar to this question: How to make camera follow SKNode in Sprite Kit?
<code>-(void)centerOnNode:(SKNode*)node {
    CGPoint cameraPositionInScene = [node.scene convertPoint:node.position fromNode:node.parent];
    cameraPositionInScene.x = 0;
    node.parent.position = CGPointMake(node.parent.position.x - cameraPositionInScene.x, node.parent.position.y - cameraPositionInScene.y);
}
</code>
Then you'll have to figure out your own game mechanics on how the ship moves but if you simply imply the ship follows your finger you can use SKActions to animate to finger location. Example: https://stackoverflow.com/a/19172574/525576
<code>-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    for (UITouch *touch in touches) {

        for (UITouch *touch in touches) {

            CGPoint location = [touch locationInNode:self];

            CGPoint diff = CGPointMake(location.x - _myPlayer.position.x, location.y - _myPlayer.position.y);

            CGFloat angleRadians = atan2f(diff.y, diff.x);

            [_myPlayer runAction:[SKAction sequence:@[
                                [SKAction rotateToAngle:angleRadians duration:1.0],
                                [SKAction moveByX:diff.x y:diff.y duration:3.0]
                                ]]];
        }
    }
}
</code>
Comment: Hello, this post helped me a lot. I tried to implement my own "camera" function like this:
`float xDisFromCenter = 0.f;
float yDisFromCenter = 0.f;
yDisFromCenter = (world.position.y+player.position.y)-(self.size.height/2);
xDisFromCenter = (world.position.x+player.position.x)-(self.size.width/2);
world.position = CGPointMake(world.position.x-xDisFromCenter,
world.position.y-yDisFromCenter);`
I am just moving the world. I wanted to prevent scrolling over the edge:
`if(newPos.x>0)xDisFromCenter = 0.f;if (newPos.x<-20)xDisFromCenter = 0.f;` But it does not work every time :/
Answer: Solved it, thanks to ray wenderlich
<code>CGSize winSize = self.size;

int x = MAX(player.position.x, winSize.width / 2 );
int y = MAX(player.position.y, winSize.height / 2 );
x = MIN(x, worldSize.width - winSize.width / 2 );
y = MIN(y, worldSize.height - winSize.height/ 2 );
CGPoint actualPosition = CGPointMake(x, y);

CGPoint centerOfView = CGPointMake(winSize.width/2, winSize.height/2);
CGPoint viewPoint = ccpSub(centerOfView, actualPosition);

world.position = viewPoint;
</code>

SpriteKit multidirectional scrolling


Show that the parametric graphs intersects at the point $P=(2,1,3)$

Question: Show that the following graphs intersects at the point $P=(2,1,3)$:
\begin{align}
r_1(t)&=2e^{-t} \hat i+\cos t \hat j+(t^2+3) \hat k \\
r_2(t) &=(1-t) \hat i+t^2 \hat j+(t^3+4)\hat k
\end{align}
We have to do the following
$ 2e^{-t_1}=(1-t_2), \\ \cos t_1=t_2^2, \\ t_1^2+3=t_2^3+4$
If we show, $t_1=0  $ and $t_2=-1$, then we get
$r_1(0)=(2,1,3) \\ r_2(-1)=(2,1,3)$.
How to show that ?
Any help
Answer: That the problem gave you the putative point of intersection makes it very easy; all you had to do was to solve, say, $2e^{-t_1}=2=1-t_2$ to get a value for $t_1$ and $t_2$, then substitute in the other coordinates to see if they match. If the intersection had not been given it would have become much harder.
Comment: Yes I agree to your last sentence. Thanks


Validation Summary for Collections

Question: EDIT: upgraded this question to MVC 2.0
With asp.net MVC 2.0 is there an existing method of creating Validation Summary that makes sense for models containing collections? If not I can create my own validation summary
Example Model:
public class GroupDetailsViewModel
{
    public string GroupName { get; set; }
    public int NumberOfPeople { get; set; }
    public List<Person> People{ get; set; }
}

public class Person
{
    [Required(ErrorMessage = "Please enter your Email Address")]
    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid Email Address")]
    public string EmailAddress { get; set; }

    [Required(ErrorMessage = "Please enter your Phone Number")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "Please enter your First Name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your Last Name")]
    public string LastName { get; set; }
}

The existing summary <%=Html.ValidationSummary %> if nothing is entered looks like this.

The following error(s) must be corrected before proceeding to the next step
  * Please enter your Email Address
  * Please enter your Phone Number
  * Please enter your First Name
  * Please enter your Last Name
  * Please enter your Email Address
  * Please enter your Phone Number
  * Please enter your First Name
  * Please enter your Last Name

The design calls for headings to be inserted like this:

The following error(s) must be corrected before proceeding to the next step
  Person 1
  * Please enter your Email Address
  * Please enter your Phone Number
  * Please enter your First Name
  * Please enter your Last Name
  Person 2
  * Please enter your Email Address
  * Please enter your Phone Number
  * Please enter your First Name
  * Please enter your Last Name

Answer  Based on Pharcyde's answer.
public static MvcHtmlString NestedValidationSummary(this HtmlHelper helper)
{
    if (helper.ViewData.ModelState.IsValid)
        return MvcHtmlString.Empty;

    // create datastructure to group error messages under a given key (blank key is for general errors)
    var errors = new Dictionary<string,List<string>>();
    foreach (KeyValuePair<string, ModelState> keyPair in helper.ViewData.ModelState)
    {
        foreach (ModelError error in keyPair.Value.Errors)
        {
            //determine the 'key' for the group in which this error belongs
            var key = keyPair.Key.Split(']')[0];
            if (key.Contains("People["))
                key = "Person " + key.Split('[')[1];
            else
                key = string.Empty;

            if(!errors.ContainsKey(key))
                errors.Add(key,new List<string>());
            //now add message using error.ErrorMessage property
            errors[key].Add(error.ErrorMessage);
        }
    }

    // generate the HTML
    var ul = new TagBuilder("ul");
    foreach (KeyValuePair<string, List<string>> errorPair in errors.OrderBy(p=>p.Key))
    {
        var li = new TagBuilder("li");
        if(!string.IsNullOrEmpty(errorPair.Key))
            li.InnerHtml += string.Format("
{0}
",errorPair.Key);
        var innerUl = new TagBuilder("ul");
        foreach (var message in errorPair.Value)
        {
            var innerLi = new TagBuilder("li");
            innerLi.InnerHtml = message;
            innerUl.InnerHtml += innerLi.ToString(TagRenderMode.Normal);
        }
        li.InnerHtml += innerUl.ToString(TagRenderMode.Normal);
        ul.InnerHtml += li.ToString(TagRenderMode.Normal);
    }

    return MvcHtmlString.Create(ul.ToString(TagRenderMode.Normal));
}

Comment: I totally just had the same freakin question. Guess then the answer is not so much.....
Answer: You are going to have to extend the HtmlHelper methods and roll your own.  Heres the bit of code that is important for your situation where you need a group by:
//HtmlHelper being extended
if(helper.ViewData.ModelState.IsValid)
{
    foreach(KeyValuePair<string,ModelState> keyPair in helper.ViewData.ModelState)
    {
        //add division for group by here using keyPair.Key property (would be named "Person" in your case).

        foreach(ModelError error in keyPair.Value.Errors)
        {
            //now add message using error.ErrorMessage property
        }
    }
}

Comment: Yep I wrote my own based on your answer, I've included it in the question.

Validation Summary for Collections


Issues with mySQLi and PHP

Question: I'm trying to create a internal messaging system.
My code is below:
$useraccess = $loggedInUser->username;
$sql = "SELECT id, user_name FROM ".$db_table_prefix."users WHERE   user_name='$useraccess'";
$query = $mysqli->query($sql) or die ("Error");

while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$username = $row["user_name"];
}

$query->close();

$sqlCommand = "SELECT COUNT(id) AS numbers FROM ".$db_table_prefix."messages_inbox WHERE userid='$pid'";
$query = $mysqli->query($sql) or die ("Error");
$result = mysqli_fetch_assoc($query);
$inboxMessages = $result['numbers'];
?>

Inbox

<?php
$sql="SELECT * FROM ".$db_table_prefix."messages_inbox WHERE userid='$pid' ORDER by id  DESC";
$result=$mysqli->query($sql);
$count=mysqli_stmt_num_rows($result);
?>

Title
Sender
Actions

<?php
while($rows=mysqli_field_count($result)) {
?>
<?php if ($rows['viewed'] == 0) { // show messages in bold?>

<a href="messages-view-in.php?in=<?php echo $rows['id'];   ?>"><?php echo $rows['title']; ?>
<?php echo $rows['from_username']; ?>
<a href="messages-inbox-delete.php?message=<?php echo    $rows['id']; ?>">Delete

<?php } else if ($rows['viewed'] == 1) { ?>

<a href="messages-view-in.php?in=<?php echo $rows['id'];  ?>"><?php echo $rows['title']; ?>
<?php echo $rows['from_username']; ?>
<a href="messages-inbox-delete.php?message=<?php echo      $rows['id']; ?>">Delete

<?php } ?>
<?php } ?>

<?php if ($inboxMessages > 0) { ?>
<?php } else
{ print "
Currently you do not have messages in your Inbox
";
} ?>

This is the inbox in which I'm trying to show data from the DB.  It connects no problem otherwise it would throw up the Error, so I believe it's my syntax.
I receive the following errors.
Warning: mysqli_stmt_num_rows() expects parameter 1 to be mysqli_stmt, object given in /opt/lampp/htdocs/project/inbox.php on line 28

Warning: mysqli_field_count() expects parameter 1 to be mysqli, object given in /opt/lampp/htdocs/project/inbox.php on line 38

Notice: Undefined index: numbers in /opt/lampp/htdocs/project/inbox.php on line 20

Comment: See http://php.net/manual/en/mysqli-stmt.num-rows.php - quote "The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle."
Answer: Use mysqli_num_rows instead, as follows:
$count=mysqli_num_rows($result);

Reference documentation: http://php.net/manual/en/mysqli-result.num-rows.php
To use mysqli_stmt_num_rows you need to change a few lines from what you have:
$sql="SELECT * FROM ".$db_table_prefix."messages_inbox WHERE userid='$pid' ORDER by id  DESC";
if ($stmt = $mysqli->prepare($sql)) {
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    $count = mysqli_stmt_num_rows($stmt)
    $stmt->close();
}

And here is the documentation for mysqli_stmt_num_rows: http://php.net/manual/en/mysqli-stmt.num-rows.php

Issues with mySQLi and PHP


mysqli_real_connect() often takes around 5 seconds,even on developing environment

Question: <code>mysqli_real_connect($connection, $url['host'], $url['user'], $url['pass'], substr($url['path'], 1), $url['port'], NULL, MYSQLI_CLIENT_FOUND_ROWS);
</code>
What's the reason that it can take much time to make a connection?
Now about 3 out of 8 connections will hang for 5 seconds or even more.
Answer: Maybe you are connecting to the MySQL server using a domain name, and the DNS resolution takes too much time.
There is a similar question that was addressed by using IP for the conection, but the waiting time in that case was in the order of milliseconds, take a look at it at:
Retrieve how long it takes to establish a connection with PHP mysqli_real_connect()
Answer: I think your mysql server is overloaded. you can try raising your 'max_connections' in my.cnf . also check your logs for any helpfull information.
Comment: what about the behaviour of mysql_connect() ?
Comment: That doesn't make sense, there are only 2 connections on the developing mysql server.


How to limit internet speed?

Question: I have 3 accounts in my pc, i would like as the admin of the pc to limit the internet speed (upload/download) for the other 2 accounts, is there a way to do this?
Answer: Wondershaper POWER!!!
Here is a tutorial - http://www.ubuntugeek.com/use-bandwidth-shapers-wondershaper-or-trickle-to-limit-internet-connection-speed.html
Basically you can regulate the speed of any PC that connects.
Here is a WIP for a FrontEnd - http://ubuntuforums.org/showthread.php?t=442200
MasterShaper Web Interface - http://www.mastershaper.org/index.php/Main_Page
Comment: This popped up in a low-quality queue. Maybe update it with some instructions?
Comment: @muru Thank you buddy. Let me update it this weekend. It's a "bit" old... just a bit. ;)
Comment: It is *old*.  And it looks like this question is going to be closed as a dupe and yours is the accepted answer there, so maybe you don't need to do anything at all, except add your vote as well.

How to limit internet speed?


jquery each loop check if at least one field has been filled

Question: Let's say that I have an HTML structure like this:
<input type="text" name="input_1" class="required" value="" />
<input type="text" name="input_2" class="required" value="" />
<input type="text" name="input_3" class="required one" value="" />
<input type="text" name="input_4" class="required one" value="" />
<input type="text" name="input_5" class="required" value="" />

As you can see each text field above has the class required but there are two of them that also have the class one. What I wanna do is to iterate over these text fields and check if they are not empty but for the ones that have the class one, at least one of them is required (not both at the same time). If I iterate over the input with class required, how do I check if at least one of the inputs with class one has been filled (within the same loop)? Thank you
Comment: You can filter out by using hasClass
Comment: `$('.required.one').filter(function(){return this.value.trim().length}).length > 0`
Answer: You can do:
var oneIsFilled = false;
$(":text.required").each(function() {
    if ($(this).hasClass("one") {
        if (this.value.length > 0)
            oneIsFilled = true;
    }
});

Answer: These here will additionally cover the checking of the required fields:
Working example see my fiddle: http://jsfiddle.net/Florian_Loch/A3C5C/1/
function click() {
    var bool = check();

    if (bool) {
        alert("OK!");
    } else {
        alert("NOOOO!");
    }
}

function check() {
    var one = false;
    var res = true;

    $(".required").each(function () {
        if ($(this).hasClass("one") && this.value.length > 0) {
            one = true;
        }

        if ($(this).hasClass("required") && $(this).hasClass("one") == false && this.value.length == 0) {
            res = false;
            return; //We can leave here already
        }
    });

    if (!res) {
        return false;
    }
    else {
        return one;
    }
}

Cheers,
Florian


Where can I find all the Retro Challenges?

Question: There is apparently a challenge which involves finding 25 Retro Challenges (and beating them all too!)
http://www.oxmonline.com/files/u9/runner2-retro1.jpg
Which levels have them, and where can I find them (do I need keys to get there?)
I've found three so far, one on Windy Interlude, one in Cloud 8 1/2, and one in Cloud Nein, but I can't seem to find the rest.
Where are these retro challenges located?
Answer: Here's a Steam guide that explains most of it:
http://steamcommunity.com/sharedfiles/filedetails/?id=129947407


iOS (Swift) Changing a property of a CAEmitterCell after it's been initialised

Question: My aim is to create a fire effect using a CAEmitterLayer, whose strength can be altered via changing the value of the alphaSpeed property of its given CAEmitterCells. A smaller value of the alphaSpeed would result in a "roaring" fire, whilst a larger value would suppress the fire.
So far, I have a subclass of CAEmitterLayer called FireEmitterLayer with an initialiser given by:
convenience init(view: UIView) {
    self.init()
    emitterPosition = CGPoint(x: 0.5 * view.bounds.width, y: view.bounds.height)
    emitterSize = CGSize(width: view.bounds.width, height: 0.05 * view.bounds.height)
    renderMode = .additive
    emitterShape = .line
    emitterCells = fireEmitterCells
 }

The emitter cells are generated for an array of UIImages representing 30x30 images of flames:
private var fireEmitterCells: FireEmitterCells {
    var emitterCells = FireEmitterCells()
    for assetIdentifier in assetIdentifiers {
        let emitterCell = fireEmitterCell(for: assetIdentifier)
        emitterCells.append(emitterCell)
    }
    return emitterCells
}

Each cell is created using this method:
private func fireEmitterCell(for assetIdentifier: UIImage.AssetIdentifier) -> CAEmitterCell {
    let fireEmitterCell = CAEmitterCell()
    fireEmitterCell.contents = UIImage(assetIdentifier: assetIdentifier).resized(to: CGSize(width: 20.0, height: 20.0)).cgImage
    fireEmitterCell.alphaSpeed = -0.3
    fireEmitterCell.birthRate = fireBirthRate
    fireEmitterCell.lifetime = fireLifetime
    fireEmitterCell.lifetimeRange = 0.5
    fireEmitterCell.color = UIColor.init(red: 0.8, green: 0.4, blue: 0.2, alpha: 0.6).cgColor
    fireEmitterCell.emissionLongitude = .pi
    fireEmitterCell.velocity = 80.0
    fireEmitterCell.velocityRange = 5.0
    fireEmitterCell.emissionRange = 0.5
    fireEmitterCell.yAcceleration = -200.0
    fireEmitterCell.scaleSpeed = 0.3
    return fireEmitterCell
}

Is there a way to alter the alphaSpeed value of these cells from an instance of this subclass, called say, fireEmitterLayer within some UIViewController:
var fireEmitterLayer = FireEmitterLayer(view: view)

I've tried adding this method within the FireEmitterLayer class
private func setAlphaSpeed(_ alphaSpeed: Float) {
    guard let emitterCells = emitterCells else { return }
    for emitterCell in emitterCells {
        emitterCell.alphaSpeed = alphaSpeed
    }
}

but this doesn't work ...
Any help is appreciated :-)
Answer: I set my cells dynamically for my emitters whenever I want using a func as follows :
func makeEmitterCell(thisEmitter : CAEmitterLayer, newColor: UIColor, priorColor: UIColor, contentImage : UIImage) -> CAEmitterCell {

    let cell = CAEmitterCell()

    cell.birthRate = lastChosenBirthRate
    cell.lifetime = lastChosenLifetime
    cell.lifetimeRange = lastChosenLifetimeRange
    //cell.color = newColor.cgColor
    cell.emissionLongitude = lastChosenEmissionLongitude
    cell.emissionLatitude = lastChosenEmissionLatitude
    cell.emissionRange = lastChosenEmissionRange
    cell.spin = lastChosenSpin
    cell.spinRange = lastChosenSpinRange
    cell.scale = lastChosenScale
    cell.scaleRange = lastChosenScaleRange
    cell.scaleSpeed = lastChosenScaleSpeed
    cell.alphaSpeed = Float(lastChosenAlphaSpeed)
    cell.alphaRange = Float(lastChosenAlphaRange)
    cell.autoreverses = lastChosenAutoReverses
    cell.isEnabled = lastChosenIsEnabled
    cell.velocity = lastChosenVelocity
    cell.velocityRange = lastChosenVelocityRange
    cell.xAcceleration = lastChosen_X_Acceleration
    cell.yAcceleration = lastChosen_Y_Acceleration
    cell.zAcceleration = 0
    cell.contents = contentImage.cgImage

    //Access the property with this key path format: @"emitterCells.<name>.<property>"
    cell.name = "myCellName"
    let animation = CABasicAnimation(keyPath: "emitterCells.myCellName.color")
    animation.fromValue = priorColor.cgColor
    animation.toValue = newColor.cgColor
    animation.duration = CFTimeInterval(cellAnimationTimeValue)

    if thisEmitter == particleEmitter_1
    {
        particleEmitter_1.add(animation, forKey: "emitterCells.myCellName.color")
    }
    if thisEmitter == particleEmitter_2
    {
        particleEmitter_2.add(animation, forKey: "emitterCells.myCellName.color")
    }

    return cell
} // ends makeEmitterCell

There's a color animation for my design at the end of that func that you get as bonus code in a way.
I keep these variables around to allow me to control the cell features on the fly ;
var lastChosenBirthRate : Float = 300
var lastChosenLifetime : Float = 3
var lastChosenLifetimeRange : Float = 0
var lastChosenEmissionLongitude : CGFloat = 2 * CGFloat.pi
var lastChosenEmissionLatitude : CGFloat = 2 * CGFloat.pi
var lastChosenEmissionRange : CGFloat = 2 * CGFloat.pi
var lastChosenSpin : CGFloat = 1
var lastChosenSpinRange : CGFloat = 0
var lastChosenScale : CGFloat = 1
var lastChosenScaleRange : CGFloat = 0
var lastChosenScaleSpeed : CGFloat = -0.3
var lastChosenAlphaSpeed : CGFloat = -0.1
var lastChosenAlphaRange : CGFloat = 0
var lastChosenAutoReverses : Bool = false
var lastChosenIsEnabled : Bool = true
var lastChosenVelocity : CGFloat = 20
var lastChosenVelocityRange : CGFloat = 0
var lastChosen_X_Acceleration : CGFloat = 0
var lastChosen_Y_Acceleration : CGFloat = 0

I make emitter cells in several places in my code.  Here is one. Part of this func makes the emitter cells and sets them for the desired emitter :
func changeParticlesCellImageRightNow(thisEmitter : CAEmitterLayer, thisContentImage : UIImage, theColor : UIColor)
{
    var priorColorToPassDown = UIColor()

    if thisEmitter == particleEmitter_1
    {
        priorColorToPassDown = lastColorUsedEmitter1
    }
    if thisEmitter == particleEmitter_2
    {
        priorColorToPassDown = lastColorUsedEmitter2
    }

    let color1 = makeEmitterCell(thisEmitter: thisEmitter, newColor: theColor, priorColor: priorColorToPassDown, contentImage: thisContentImage)

    thisEmitter.emitterCells = [color1]

}  // ends changeParticlesCellImageRightNow

Here is a call to that func :
    // Force the change to occur right now, using the existing colors
    changeParticlesCellImageRightNow(thisEmitter : particleEmitter_1, thisContentImage : emitter_1_Image, theColor : lastColorUsedInGeneral)
    changeParticlesCellImageRightNow(thisEmitter : particleEmitter_2, thisContentImage : emitter_2_Image, theColor : lastColorUsedInGeneral)

And here is the emitter layer objects
let particleEmitter_1 = CAEmitterLayer()
let particleEmitter_2 = CAEmitterLayer()

You might be able to cobble together an approach in a similar vein, setting the emitter cells birthrate, velocity, velocity range, alpha speed, scale, scale range, scale speed, etc. as best fits roaring or suppressed.  A lot depends on your flexibility at the top level.


Context Menu/Window in WebView inside PopupWindow crashes the app?

Question: I have an app with PopupWindow containing WebView that opens Facebook's page, any context menu like: the Autocomplete on text fields in the WebView or even the Long Press that should display options for the user to copy/paste/cut crashes the app right away with the follow error:
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W@418cdab0 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:700)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:345)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
at android.view.Window$LocalWindowManager.addView(Window.java:554)
at android.widget.PopupWindow.invokePopup(PopupWindow.java:1013)
at android.widget.PopupWindow.showAtLocation(PopupWindow.java:856)
at android.widget.PopupWindow.showAtLocation(PopupWindow.java:820)
at android.webkit.WebViewClassic$PastePopupWindow.show(WebViewClassic.java:971)
at android.webkit.WebViewClassic.showPasteWindow(WebViewClassic.java:7037)
at android.webkit.WebViewClassic.access$10300(WebViewClassic.java:235)
at android.webkit.WebViewClassic$PrivateHandler.handleMessage(WebViewClassic.java:11376)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)

Notice: my understanding of the problem is that the context menu/window are shown actually in the scope of the app itself not inside the WebView using another PopWindow (Auto generated by the Core WebView Class) this class references the context incorrectly.
My Code is as follows:
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/openpopup"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Open Popup Window" />

</LinearLayout>

Popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/background_light"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_margin="1dp"
        android:background="@android:color/darker_gray"
        android:orientation="vertical" >
     >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_margin="20dp"
            android:orientation="vertical" >

            <WebView
                xmlns:ptr="http://schemas.android.com/apk/res-auto"
                android:id="@+id/webviewActionView"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:minHeight="200dp"
                android:minWidth="200dp"
                android:scrollbars="none" >
            </WebView>

            <Button
                android:id="@+id/dismiss"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Dismiss" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

MainActivity.java
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.PopupWindow;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
        btnOpenPopup.setOnClickListener(new Button.OnClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onClick(View arg0) {

                LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                View popupView = layoutInflater.inflate(R.layout.popup, null);
                final PopupWindow popupWindow = new PopupWindow(popupView,
                        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

                popupWindow.setTouchable(true);
                popupWindow.setFocusable(true);

                WebView popupWebview = (WebView) popupView.findViewById(R.id.webviewActionView);
                popupWebview.loadUrl("https://m.facebook.com");
                Button btnDismiss = (Button) popupView
                        .findViewById(R.id.dismiss);
                btnDismiss.setOnClickListener(new Button.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        // TODO Auto-generated method stub
                        popupWindow.dismiss();
                    }
                });
                popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
            }
        });
    }
}

Comment: on which line you getting force close ?i tried and its work.
Comment: did you try this on JB? it only happens on JB 4.1+ doesn't happen on ICS or GB.
Comment: ya.i also tried in JB 4.2 and its working fine..
Comment: It worked with u on JB 4.1  and 4.2 ?  How come ? I tried this on 2 phones cyanogenmod and stock rom and it crashed and I even saw crash reports in google play as this is a part of a live app that I have.
Comment: ya i test on 4.2 and its running no any crash...also running in 2.3.3 but still m not getting any crash.
Comment: I am just asking about 4.1.x
Comment: i'm facing same issue! when i click on Edittext inside webview and type my app crashes with the above exception
Answer: As commented above in my answer you can use Custom dialog for your requirement.. i have created a sample PopupDialog.. please check and let me know..if it solve your purpose.. Autocomplete and ContextMenus will work as expected..
MyActivity.java
package com.example.testapp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

public class MyActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
    btnOpenPopup.setOnClickListener(new Button.OnClickListener() {

        @SuppressLint("NewApi")
        @Override
        public void onClick(View arg0) {

            final PopupDialog popupDialog = new PopupDialog(MyActivity.this);
            popupDialog.setContentView(R.layout.popup);

            WebView popupWebview = (WebView) popupDialog.findViewById(R.id.webviewActionView);
            popupWebview.setWebChromeClient(new WebChromeClient());
            popupWebview.setWebViewClient(new WebViewClient());

            popupWebview.loadUrl("http://m.facebook.com");
            Button btnDismiss = (Button) popupDialog
                    .findViewById(R.id.dismiss);
            btnDismiss.setOnClickListener(new Button.OnClickListener() {
                @Override
                public void onClick(View v) {

                    // TODO Auto-generated method stub
                    popupDialog.dismiss();
                }
            });
//                popupDialog.showAtLocation(50,50);
            popupDialog.showAsDropDown(findViewById(R.id.openpopup));
        }
    });
}
}

PopupDialog.java
package com.example.testapp;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class PopupDialog extends Dialog{
private final Context mContext;

public PopupDialog(Context context) {
    super(context);
    mContext=context;
    requestWindowFeature(Window.FEATURE_NO_TITLE);
}

public void showAtLocation(int x,int y)
{
    WindowManager.LayoutParams wmlp = getWindow().getAttributes();
    wmlp.gravity = Gravity.TOP | Gravity.LEFT;
    wmlp.x = x;
    wmlp.y = y;
    show();
}
public void showAsDropDown(View view)
{
    float density = mContext.getResources().getDisplayMetrics().density;
    WindowManager.LayoutParams wmlp = getWindow().getAttributes();
    int[] location = new int[2];
    view.getLocationInWindow(location);
    wmlp.gravity = Gravity.TOP | Gravity.LEFT;
    wmlp.x = location[0]+(int)(view.getWidth()/density);
    wmlp.y = location[1]+(int)(view.getHeight()/density);
    show();
}
}

edit: added popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:minHeight="400dp"
          android:minWidth="200dp"
          android:background="@android:color/background_light"
          android:orientation="vertical" >

<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_margin="1dp"
        android:background="@android:color/darker_gray"
        android:orientation="vertical" >
    >

    <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_margin="20dp"
            android:orientation="vertical" >

        <WebView
            xmlns:ptr="http://schemas.android.com/apk/res-auto"
                android:id="@+id/webviewActionView"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:minHeight="200dp"
                android:minWidth="200dp"
                android:scrollbars="none" >
        </WebView>

        <Button
                android:id="@+id/dismiss"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Dismiss" />
    </LinearLayout>
</LinearLayout>

Answer: yes i think you should use your activity name in place of "getBaseContext()". i am just created one demo with your code. its working fine in my pc. and when you are getting this exception?
Comment: It crashes when u long press on the user field in fb login, and changing getBaseContext doesn't help either; try this on JB 4.1+
Comment: ok now please download my code from below link and check what happen and inform me.. http://www.mediafire.com/?ypp5cq22p7n66pq
Comment: Well it crashes, you didn't change anything in the code already.
Comment: ok friend, you give me -1, but its working fine in my so i have given you this link.. but its ok :)
Comment: I didn't, and generally you didn't change anything in the code,just for you information (posting an answer meaning that you got a solution if you want to say that it's working on your device then just add a comment)
Answer: Nothing wrong in your code..seems to be Android 4.1+ specific issue..
Webview is also using PopupWindow for showing Paste context menu in input box..Nested popupwindows through webview is causing WindowManager crash, while adding new view to it.
I have tried Custom Dialog(in place of Popupwindow) with embedded Webview, Paste context menu is coming fine in Android 4.1+..
If you are not so specific about this paste context menu you can disable it for particular android version using below code..i have tried it.. it will stop app from being crash..
  popupWebView.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (Build.VERSION.SDK_INT >= 16)
                  return true;
              return false;
        }
    });

Also you can look at Webview HitTestResult class for displaying some custom made Context menus, according to your needs..
Comment: It's not just on click/longClick, it happens also on autocomplete in forms, I don't wanna disable it; instead I wanna fix it even if I'll have to extend the default popupWindow class and override some methods.
Comment: Extending PopupWindow will not solve problem.. As for drawing PopupWindow Window is needed from parent activity.. In case of nested Popupwindow parent is popupwindow for child popupwindow.. I will recommend creating custom Dialog with x,y coridinates of your choice.. that will solve the purpose. e.g. [See here](http://stackoverflow.com/questions/5469005/show-alertdialog-in-any-position-of-the-screen)..


How to add items to array in a function using pointers?

Question: I am trying to write this function that takes an array input and assigns random numbers between 1-52 to the array. Then prints back the numbers. I get an error message on the 4th line that says expression is not assignable. Is my use of pointers incorrect or is it not possible to add content to array with pointers?
void shuffleDeck(int *deck[]) {
    int i;
    for(i=0;i<=52;i++)
       rand()%53 = deck[i]; // I get an error message on this line
}
int main() {
    srand(time(NULL));

    int deck[2000];

    shuffleDeck(deck);

    int i;
    for(i=0;i<=52;i++){
        printf("%d", deck[i]);
    }

    return 0;
}

Comment: How are you learning C? Your assignment is the wrong way round.
Comment: Also, note that `%53` will return numbers in the range `0 to 52` not `1 to 52`. Better to work `%52` and add 1 -- or just use 0 to 51. Along the same lines, you seem to be trying to add 53 cards to the deck rather than 52. Finally, declaring it to have room for 2000 cards is pointless.
Comment: `rand()%53 = deck[i]` doesn't make sense, but `deck[i] = rand()%53` does
Comment: 1) `int *deck[]` --> `int deck[]` 2) `rand()%53 = deck[i];` --> `deck[i] = rand()%53;`
Comment: This `int *deck[]` should be `int *deck`. Also take your compiler's *warnings* serious.
Answer: Assigment direction is from right to left
So in this expression
deck[i] = rand()%52 + 1;

First is called function rand()
Then the result of function %52
Then 1 is added
And finnally its assigned to deck[i]

Array (what you have in main) is
  0   1   2   3   4
+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+
  ^-------------------------- arr[0]

While Array of pointers (what your function expects) is
      0   1   2   3   4
    +---+---+---+---+---+
    | 0 | 0 | 0 | 0 | 0 |    0
    +---+---+---+---+---+
------^
|   +---+---+---+---+---+
|   | 0 | 0 | 0 | 0 | 0 |    1
|   +---+---+---+---+---+
|   +---+---+---+---+---+
|   | 0 | 0 | 0 | 0 | 0 |    2
|   +---+---+---+---+---+
|
----------------------------- arr[0][0]

When array is passed to function, then arr[] and *arr are the same. But only as function arguments!

%53 returns 0-52,so if you need 1-52, use %52 + 1 (0-51 + 1 = 1-52)

If you cant solve it, here is code with fixed bugs.
void shuffleDeck(int deck[]) {
    int i;
    for(i=0;i<=52;i++)
       deck[i] = rand()%52 + 1;
}
int main() {
    srand(time(NULL));

    int deck[2000];

    shuffleDeck(deck);

    int i;
    for(i=0;i<=52;i++){
        printf("%d", deck[i]);
    }

    return 0;
}

Comment: *Some* bugs are fixed (enough for a +1), but it still doesn't make a lot of sense. For one thing, if the numbers 1-52 are supposed to be the 52 cards in the deck, then OP needs a *permutation* of these numbers, something which the code doesn't give. Instead, some cards will be repeated multiple times and other cards will be missing.
Comment: @JohnColeman Which bugs? Which permutation ? OP didnt even mention any permutation or cards. Q is _How to add items to array in a function using pointers?_ and why he gets an error.
Comment: For one thing, I think that `<=52` rather than `<52` is a bug. For another thing -- the names `deck` and `shuffleDeck` suggest cards and an intended application, one for which the code doesn't make sense. To shuffle a deck is to *permute* it. I think that OP needs to do something like initialize an array with the numbers 1-52 and then do something like a fisher-yates shuffle on it. It isn't your fault that OP's code has multiple issues.
Comment: Sure, it suggest that its app for cards and it should be `<52`, but still we arent mind-readers and OP didnt actually asked for that, so why would one creates algorihms for OP? Iam just explaining & fixing _syntax_ errors which is that Q about :-)
Comment: @johnColeman you're right a permutation would be a better way to realistically simulate a card deck. I'm just in the process of learning C (my first language) right now, so I'm starting projects and learning on the go. Thank you for the help everyone.


'Invalid parameter number: number of bound variables does not match number of tokens' Symfony

Question: I'm working on a symfony project entity with query builder. When I try to run this function I get this issue.

Invalid parameter number: number of bound variables does not match number of tokens

<code>public function json_filterAllproductsAction() {

    $search = "";
    $category = 1;

    //Combine tables and create the query with querybuilder
    $em = $this->container->get('doctrine.orm.entity_manager');

    $qb = $em->createQueryBuilder();

    $qb->select('p')
            ->from('EagleAdminBundle:Products', 'p')
            ->orderBy('p.id', 'DESC');
    if ($category != 0) {
        $qb->where($qb->expr()->in('p.category', '?1'))
                ->setParameter(1, $category);
    }
    $qb->where('p.productTitle LIKE :title')
            ->setParameter('title', "$search%");

    //convert to json using "JMSSerializerBundle"
    $serializer = $this->container->get('serializer');
    $jsonproducts = $serializer->serialize($qb->getQuery()->getResult(), 'json');
    return new Response($jsonproducts);
}
</code>
I think error is in

$qb->where($qb->expr()->in('p.category', '?1'))
                  ->setParameter(1, $category);

It would be great help someone can help me.
Comment: Possible duplicate of [Invalid parameter number: number of bound variables does not match number of tokens](http://stackoverflow.com/questions/2154119/invalid-parameter-number-number-of-bound-variables-does-not-match-number-of-tok)
Answer: You have two issues here.  The first is that your last where clause overwrites the first one.  This can be fixed by using andWhere.  The second is that your mixing named parameters (:title) with positional parameters (?1).  Mixing is a no no.  And you don't really need the expr object.  Try:
<code>$qb->select('product')
  ->from('EagleAdminBundle:Products', 'product')
  ->orderBy('product.id', 'DESC');
if ($category) {
    $qb->andWhere('product.category IN (:category)');
    $qb->setParameter('category', $category);
}
$qb->andWhere('product.productTitle LIKE :title');
$qb->setParameter('title', "$search%");
</code>


How to make CSS style work in Safari browser?

Question: I'm building my first website, trying to adapt it to the most popular browsers, and the css style works correctly in all browsers except Safari. In this browser, almost everything does not work for me: the hover effect is not linear, flexbox is not displayed correctly (1,2,3 screen - as displayed in safari; 4,5,6 screen - as should be in all browsers), in the mobile version the menu by the span button does not open. I threw the code in https://autoprefixer.github.io/ru/, because I understand that there are not enough prefixes, but it did not help me, after saving the code and updating the page, everything remained in its place. Tell me, please, what to do then?

html {
  overflow: scroll;
  overflow-x: hidden;
  height: 100%;
}
::-webkit-scrollbar {
  width: 0px;
}
body {
  margin: 0;
  width: 100%;
  display: -webkit-box;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
          flex-direction: column;
  min-height: 100%;
}
a {
  text-decoration: none;
  color: black;
}
.wrapper {
  display: block;
  max-width: 2560px;
  flex-grow: 1;
  margin-top: 10px;
  margin-left: 20%;
  margin-right: 20%;
  position: relative;
  z-index: 7;
  text-align: center;
}
.content span {
  font-family: 'PT Serif', serif;
  font-family: 'PT Sans', sans-serif;
  font-size: 26px;
}

header, nav, section, footer {
  font-family: 'Merriweather', serif;
  color: rgb(0, 0, 0);
}
.header {
  background-image: url(../img/12321.jpg);
  background-position: top right;
  background-size: cover;
  max-height: 250px;
  width: 100%;
}
.nav li a {
  display: block;
  text-align: center;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.logo-header {
  height: 40px;
  position: relative;
  float: right;
  margin: 200px 10px 0 0;
}
.nav {
  height: 100vh;
  margin-left: calc(20% - 100px);
  position: relative;
  outline: none;
}
.nav ul {
  list-style: none;
  padding: 0.5em 0;
  margin: 0;
}
.nav ul li {
  margin: 10px;
  height: 40px;
  line-height: 40px;
  background-color: white;
  padding: 0.5em 1em 0.5em 1em;
  font-size: 24px;
  background-repeat: no-repeat;
  background-position: left 15px center;
  background-size: auto 40px;
  transition: all 0.15s linear;
  border-radius: 5px;
  border: 1px solid black;
  opacity: 0.75;
}
.menu {
  display: grid;
  grid-template-areas:
    "home home"
    "gallery ut"
    "journal contact";
 grid-template-rows: 65px 65px 65px;
 grid-template-columns: 350px 350px;
 grid-gap: 10px;
  height: 100vh;
  position: relative;
  z-index: 5;
}

.home {
 grid-area: home;
}

.gallery {
 grid-area: gallery;
}
.ut {
 grid-area: ut;
}
.journal {
 grid-area: journal;
}
.contact {
 grid-area: contact;
}
.nav img {
  float: left;
}
.menu li:hover {
  background-color: #ffffff;
  opacity: 1;
}
@media screen and (max-width: 1024px) {
  body {
    min-height: 99vh;
  }
    .wrapper {
      -webkit-box-orient: vertical;
      -webkit-box-direction: normal;
              flex-direction: column;
    }

/* MENU STYLE */
.menu {
  display: none;
  background-image: url(../img/Фон.png);
  height: 100%;
  position: relative;
  z-index: 5;
}
.nav {
  margin-left: 0;
}
div.burger {
 height: 30px;
 width: 40px;
 position: absolute;
 top: 11px;
  left: 21px;
  z-index: 30;
}
 div.x,
 div.y,
 div.z {
  position: absolute; margin: auto;
  top: 0px; bottom: 0px;
  background: #fff;
  border-radius:2px;
  -webkit-transition: all 200ms ease-out;
     -moz-transition: all 200ms ease-out;
      -ms-transition: all 200ms ease-out;
       -o-transition: all 200ms ease-out;
          transition: all 200ms ease-out;
 }
 div.x, div.y, div.z { height: 3px; width: 26px; }
 div.y {top: 18px;}
 div.z {top: 37px;}
 div.collapse {
  top: 20px;
  -webkit-transition: all 70ms ease-out;
     -moz-transition: all 70ms ease-out;
      -ms-transition: all 70ms ease-out;
       -o-transition: all 70ms ease-out;
          transition: all 70ms ease-out;
 }

 div.rotate30 {
  -ms-transform: rotate(30deg);
     -webkit-transform: rotate(30deg);
     transform: rotate(30deg);
  -webkit-transition: all 50ms ease-out;
     -moz-transition: all 50ms ease-out;
      -ms-transition: all 50ms ease-out;
       -o-transition: all 50ms ease-out;
          transition: all 50ms ease-out;
 }
 div.rotate150 {
  -ms-transform: rotate(150deg);
     -webkit-transform: rotate(150deg);
     transform: rotate(150deg);
  -webkit-transition: all 50ms ease-out;
     -moz-transition: all 50ms ease-out;
      -ms-transition: all 50ms ease-out;
       -o-transition: all 50ms ease-out;
          transition: all 50ms ease-out;
 }

 div.rotate45 {
  -ms-transform: rotate(45deg);
     -webkit-transform: rotate(45deg);
     transform: rotate(45deg);
  -webkit-transition: all 100ms ease-out;
     -moz-transition: all 100ms ease-out;
      -ms-transition: all 100ms ease-out;
       -o-transition: all 100ms ease-out;
          transition: all 100ms ease-out;
 }
 div.rotate135 {
  -ms-transform: rotate(135deg);
     -webkit-transform: rotate(135deg);
     transform: rotate(135deg);
  -webkit-transition: all 100ms ease-out;
     -moz-transition: all 100ms ease-out;
      -ms-transition: all 100ms ease-out;
       -o-transition: all 100ms ease-out;
          transition: all 100ms ease-out;
 }
div.menu-bg {
 width: 100%;
 height: 100%;
 position:absolute;
  top:0;
  left:0;
 -webkit-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
    -moz-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
     -ms-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
      -o-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
         transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
}
ul.menu {
  padding-top: 5em;
}
ul.menu li {
 width:300px;
  margin: 0 auto;
}
ul.menu span {
  text-align: right;
}
ul.menu li a {
  background-color: white;
 color:rgb(0, 0, 0);
  opacity: 0.75;
}
section > div {
  transition: transform 1s;
  transform: translateX(0px);
}
}
footer {
  position: relative;
  flex-shrink: 0;
  height: 10px;
  width: 100%;
  bottom: 0;
  z-index: 6;
}

/* MAIN CONTENT */
.box-image {
  width: 30%;
  min-width: 120px;
  height: 120px;
  background-size: 120px 120px;
  background-position: center;
  position: relative;
  float: left;
  margin: 5vh 10px 10px 10px;
}
@media screen and (max-width: 1024px) and (min-width: 381px) {
  .box-image {
    width: 33,3333%;
  }
}
@media screen and (max-width: 380px) {
  .box-image {
    width: 50%;
    height: 100px;
    background-size: 100px 100px;
  }
}
.vkontakte {
  background-image: url(../img/vk.svg);
  background-repeat: no-repeat;
}
.instagram {
  background-image: url(../img/instagram.svg);
  background-repeat: no-repeat;
}
.whatsupp {
  background-image: url(../img/whatsapp.svg);
  background-repeat: no-repeat;
}
.mail {
  background-image: url(../img/mailru.svg);
  background-repeat: no-repeat;
}
.link-image {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}
.ContactWithMe {
  display: inline-block;
  position:relative;
  text-align: center;
  width: 100%;
}

.ContactWithMe a {
  position: relative;
  display: inline-block;
  text-align:center;
  width:120px;
  height:120px;
}

/* FOOTER */
.social-block {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    align-content: center;
    justify-content: center;
    width: 100%;
    }
.social-block a {
    color: #000000;
    width: 40px;
    height: 40px;
    font-size: 20px;
    overflow: hidden;
    padding: 10px;
    }
a {
    text-decoration: none;
    transition: 0.3s linear;
}
.vk a:hover {
    color: #45668e
}
.inst a:hover{
    color: #e4405f;
}
.wa a:hover {
    color: #25D366
}

Главная

Галерея

Полезные советы

Журнал

Контакты

Comment: Just to make sure: after you updated your code and reloaded your page did you make sure it did not load any old cached files?
Comment: Do a hard refresh (on Mac OS using CMD+SHIFT+R) instead of just refreshing the page in order to make sure it gets reloaded correctly. CSS does not get reloaded every time you refresh.
Comment: After resetting the safari, only footer fell into place. Everything else does not work correctly.
Answer: Seems to me that some elements get display: block which is the default.
Did you try adding all prefixes for display: flex ?
display: -webkit-box;      // OLD - iOS 6-, Safari 3.1-6
display: -moz-box;         // OLD - Firefox 19- (buggy but mostly works)
display: -ms-flexbox;      // TWEENER - IE 10
display: -webkit-flex;     // NEW - Chrome
display: flex;             // NEW, Spec - Opera 12.1, Firefox 20+

For Safari try adding -webkit- prefix to all flexbox properties.
Comment: I have this line in the code, if you go over your eyes more carefully, thanks :)
I figured out how to fix main content, but the question remains how to fix the site's navigation, it's not made as flexbox, but as grid. And what to do, here I do not understand at all.
Comment: I went over the code carefully and you do not use -webkit-flex.
You use -webkit-box which is for old safari.
Answer: Safari still requires the -webkit- prefix to use flexbox.
Just try -webkit-flexbox. it's working for safari., webkit-flex safari will not taking.
I advise you to see that:
How do I make flex box work in safari?
sorry for google translate
Comment: No, Safari does not require the `-webkit-` prefix.
Comment: Thank you, I have this line in the code. My menu doesn't work correctly, but it is made up using a grid, and I can't fix it.


Is there a common design pattern or object oriented approach used to encapsulate thread behaviour?

Question: I have recently been using pthreads on Linux and want to start looking into using boost threads in the near future. I have never used MS visual studio so I don't know the approach there but I (have to) use Embarcadero C++ Builder (formerly Borland) one of the few good things I find with it is that is has a built in class TThread. This is a class that you can derive from to give nicely encapsulated data and start and terminate functions.  I prefer this approach than the pthread way of passing functions and void* being passed into the thread create function. I was wondering if there is some kind of design pattern or structure that is commonly used to provide a more object oriented that encapsulates the functionality of threads in this way? I can try and create it myself, but I cannot be the first person to desire this kind of approach and wondered if there was a "standard" way of achieving it.
Edit: Alternatively, if this is a very bad idea perhaps an illustration of why?
Comment: Note that the approach you mention in Embarcadero (which is the same as deriving from `Thread` in Java) is not a good approach and is in many cases prone to errors. Currently the trend is to have a `Thread` class that just manages the thread, and takes a *job* to run as an argument (Boost, C++11, Java Runnable approach)
Comment: _Why_ do you want an OOP threading framework? Threads by their very nature are action-driven (they execute code), so a functional approach makes more sense to me.
Comment: I would like to be able to create an instance of a class, pass it data, start it when I like and terminate it when I like as an object with all internal functionality hidden from the code that uses it. It is not *that* controversial an idea is it??
Comment: But how is that better than calling a function with arguments? What is a class buying you other than potential shared-state trouble?
Comment: @mathematician1975 - it is somewhat controversial.  I have spend 30+ years trying to stop Delphi developers from doing exactly that - continually starting and terminating threads.  TThread is just fine for implementing thread pools and lifetime-of-app threads that never require termination.  Attempting to encapsulate thread termination will cause you pain, eventually - try very hard indeed to not do it.  There is no inherent shared-state problem with TThread or any C++ implementation of a 'TThread-like' class - each instance would have its own instance vars and stack - no problemo.
Comment: Well with any luck I will soon be removed from ever needing to use embarcadero environment ever again. From the responses hear I will forget the idea completely.
Comment: ..and now, newer languages seem to teach developers to use join(), (AKA TThread.waitFor), for 'returning' results from threads, the very thing I have not touched since D3 and have tried to stop others using, .  Use thread pools and/or app-lifetime threads and you will have few problems.
Comment: @mathematician1975 - there is nothing wrong with the Borland/Embarcadero TThread model except that is so often misused, ably assisted by the Borland TThread examples that are just dire.  A producer-consumer queue takes 22 lines of TObjectQueue descendant and making a thread pool is then just trivial - two lines of code.
Comment: Oh dear. TThread class was my first introduction to multithreading as were those examples that you mention. Seems I will have learned some bad habits then....
Answer: I would consider that the most standard approach would be using the standard thread library (closely related to boost::thread, not 100% the same). I would avoid redesigning what has already been designed, reviewed and verified by a committee of experts.
Also note that for the kind of operations that you mention in the comment you might want to take a look at the future part of the standard library (again similar to the boost counterpart), and in particular to the std::asynch function.
Comment: @mathematician1975: Just use `boost::thread`, `boost::future`... whenever you get to use C++11 the changes in code will be minimal.
Comment: This is part of C++11 I presume? I am not actually able to use that at present which I probably should have specified. Perhaps my question is outdated then with the advent of C++11
Answer: I like the way boost::thread is designed (I saw a similar design in the threading library from Rouge Wave). Basically a thread is started by passing a function to be executed and latter that thread object can be used to join that thread. pthread is very similar in design, but boost::thread is much easier to use.


Can I use 10/3 cable to feed two 15 amp circuits?

Question: At my request a few years ago an electrician pulled a 30amp 2 pole breaker out of the panel and replaced it with two single pole 15 amp breakers and connected them to the existing 10/3 cable.
10/3 runs from the two 15amp breakers to a jbox. Is it still code (NEC) to construct two separate 15 amp circuits from the jbox in this scenario? if so any suggestions for labeling the jbox?
Thanks.
Answer: Under current (and quite a few years back, now) code, the handles of the two 15A breakers should be tied together, so when you shut off one half of the MultiWire Branch Circuit you shut off both halves of it.
Otherwise, yes, you can split that out into two separate 15's from a junction box.
Labeling? The numbers of the slots for the breakers that feed it, and MWBC, I suppose. No label is required by code there. But I'm quite fond of disambiguating what breaker(s) feeds what box.
Comment: Common shutoff for maintenance safety is only half the picture. It is also absolutely critical (for "not burning down your house" purposes) to ensure that the breakers are on separate phases when there is a shared neutral, so that the neutral doesn't get overloaded. Generally a listed handle tie ensures proper phasing, but it's important to be aware.
Comment: Question states that a two pole breaker was removed and replaced with two single poles, so that's a given here. Me, I prefer dual pole breakers for MWBCs, but that's me, not a code requirement, unless it serves 240 as well as 120V loads.
Comment: "so that's a given here" - what is?
Comment: Check your reading comprehension. You take out a two pole, you insert two one poles in the same place, you have two one poles on opposite phases so your original comment is inappliacable in this case. That's a given.
Comment: additionally, here in florida I have an outdoor breaker box and I was trying to avoid adding another conduit up the wall.  otherwise it would be more user friendly to add 2 14/2 w/g cables if the panel was inside. the electrician validated the breakers were on different phases.


C++ application fails - no errors

Question: I have started to learn C++ and this is causing me a headache. I have written a simple person "database" application and for some reason it fails when listing persons.
string search;
cout << "Give the name: ";
cin >> search;

vector<Person> foundPersons;
for(vector<Person>::iterator it = persons.begin(); it != persons.end(); it++) {
    Person p = *it;

    if(search == p.getFirstname() || search == p.getSurname()) {
        foundPersons.push_back(p);
    }
}

if(!foundPersons.empty()) {
    cout << "Found " << foundPersons.size() << " person(s).\n\n";
    cout << "Firstname\tSurname\t\tBirth year\n";
} else {
    cout << "No matches.";
}

for(vector<Person>::iterator it = foundPersons.begin(); it != persons.end(); it++) {
    Person p = *it;
    cout << p.getFirstname() << "\t\t" << p.getSurname() << "\t" << p.getBirthYear() << "\n";
}

cout << "\n";

persons is type of vector<Person>. I go through all the entries and compare the name against the given search value. If found, I add the person in the foundPersons vector. Then I print either No matches or the number of found persons and the table header. Next I will go through all the found persons and print them in to the console.
If I add two persons, eg "Jack Example" and "John Example" and I search for "Jack", it will find the "Jack" and print it. But then the program stops. Windows says "The program has stopped working". No errors are shown during the compile or when the program stops.
What's wrong?
Comment: There's always a reason.
Comment: I suggest you run the program through a debugger - that should at least indicate where the program stops.
Comment: How is `Person` defined?
Comment: Of course there's a reason for it not to work. It just doesn't show up anywhere...
Answer: You're for loop isn't quite right, it looks like you've made a typo and are referencing iterators from two different lists.  Change:
for(vector<Person>::iterator it = foundPersons.begin(); it != persons.end(); it++) {

to
for(vector<Person>::iterator it = foundPersons.begin(); it != foundPersons.end(); it++) {

Comment: +1 for amazing eyes :)
Comment: @Bill his first loop looks ok to me.  I've referenced the incorrect loop in my answer to show where the error is.
Comment: the same error is also in the first `for` loop.
Comment: I know that..I dnt see any `vector` for `persons`, so not sure if that is intentional or a typo. This is the only vector defined in code `vector foundPersons;` ...may be the code does not show that.
Comment: Thanks Steve! Good and fast.

C++ application fails - no errors


Align Divs at Top and create space between Divs

Question: How do I align my three divs to be at the top?
- See how Google Mail and Google Maps dropdown since they have less content? I'd like them to be aligned at the top no matter how little text is below them
Also, I have three divs at 33.3333%.
- If I wanted to put more space inbetween the divs (say like 5px, how would I do that?
Here's my Jsfiddle: http://jsfiddle.net/huskydawgs/Z7dZR/
Here's my code:

Google Mail

Gmail's inbox helps you stay organized by sorting your mail by type. Plus, you cannot work correctly.

Google

Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.

Google Maps

Find local businesses, view maps and get driving directions in Google Maps.

Here's my CSS:
#wrapper-threecol {
    position:relative;
    width:100%;
    border: none;
    margin: 20px 0 0 0;
}

    #threecol_row {
    height:100%;
    white-space:nowrap;
    }

    .threecol_cell1, .threecol_cell2, .threecol_cell3 {
    height:100%;
    width:33.3333%;
    display:inline-block;
    white-space:normal;
    }

.summary-headline {
    color: #232323;
    font-family: 'SegoeRegular', Helvetica, Arial, sans-serif;
    font-size: 20px;
    line-height: 24px;
    margin:0;
    text-align: center;
}

.summary-description {
    color: #232323;
    font-family: 'SegoeRegular', Helvetica, Arial, sans-serif;
    font-size: 13px;
    line-height: 23px;
    margin: 0;
    text-align: center;
}

Comment: To align them at the top `vertical-align: top;` on the cells
Answer: I put 5% spacing
http://jsfiddle.net/Z7dZR/1/
.threecol_cell1, .threecol_cell2, .threecol_cell3 {
    height:100%;
    width:30%;
    display:inline-block;
    white-space:normal;
    vertical-align: top;
    margin-left: 5%;
}
.threecol_cell1{
    margin-left: 0;
}

You need to vertically align the inline-block elements to the top vertical-align: top;
For spacing, I made your blocks width 30%,  which means you have 10% left of the 100%. So I set 5% to margin left for each block then set the first block margin-left to 0 so you have a perfect 100%. Since you have width in %, it would be wise to set the margin in % as well
Answer: .threecol_cell1, .threecol_cell2, .threecol_cell3 {
   vertical-align: top;
}

that should do it.
Comment: Thanks.How would I add space between the divs? Say like 5px?


Call http using Angular JS

Question: I don't understand how to use Angular JS to make an API call.
I can make a post call using Ajax, but I would like to make the same call using the Angular syntax.
Using Ajax it looks like this:
<code>$.ajax({

        url: "url",
        contentType: "application/json",
        type: "POST",
        dataType: "json",
        data: JSON.stringify(data),
        success: function (result) {
            alert(JSON.stringify(result));
        }
    });
</code>
and this code works, however when I try to do the same thing with a http call:
<code>$http({

    method: "POST",
    url: "url",
    headers: {'contentType': "application/json"},
    data: JOSN.stringify(data)
  }).success(function(account){
    alert("You logged in!");
  }).error(function(){
    alert("Incorrect Information");
  });
</code>
Neither the success nor the error alert triggers.
I have looked over other http calls in Angular and am unable to find a difference between my code and the other calls. What is causing my code to fail?
Thanks!
Comment: that is because of your typo 'Content-Type':
Comment: have you tried $http.post.... as per angular $http service[https://docs.angularjs.org/api/ng/service/$http]?
Comment: @maurycy, I'm not too well versed. What does CORS refer to? How would I use jsonp? I know that the API is setup as I am able to access it using AJAX already.
Comment: other typo : ``JOSN.stringify``
Comment: any error in console?
Comment: Open your network tab and check the status of the request.
Comment: why you stringify your data since you always have {'contentType': "application/json"}?
Comment: I receive the error XMLHttpRequest cannot load 'url' Request header field contentType is not allowed by Access-Control-Allow-Headers.
Comment: @ABOS please add answer..Nice catch
Comment: It was the Content-Type, thanks so much everyone!
Answer: Have you tried these examples? https://docs.angularjs.org/api/ng/service/$http
I'd recommend doing it like this, if data is an object:
<code>$http.post('url', data)
    .success(function(account){
        alert("You logged in!");
    })
    .error(function(){
        alert("Incorrect Information");
    });
</code>
Your object will already be appropriately formatted and stringified for you.
Comment: I tried this method and received the following error: POST url 401 unauthorized
Comment: A 401 error suggests that you are required to be logged in before you can access that URL and you are not logged in, as can be seen here: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error  Is there a form of authentication that might prevent a not-logged-in user from accessing this method? It looks like you're trying to log them in, so, naturally they're not logged in at this stage.
Comment: The issue appears to be that the server does not recognize the data inputted for the user to login. Is there a reason that this form of data is not recognizable?
Comment: ... Try $http.post('url', data)[...] I think I accidentally asked you to pass in an object that had 'data' as a property. But if data is an object and has the properties that your API expects of an input object, then just 'data' is what you need.

Call http using Angular JS


28V at furnace, 0V at previously working thermostat

Question: This is a followup to an earlier question I posted where it appeared that the previously unused Common wire on my HVAC system was damaged. All of the other wires read 28V between them and R, and the Common wire alone was only reading phantom voltage at the thermostat. Now that I need the Common wire for my new Nest thermostats, I swapped the terminals the G and C wires were hooked up to at the furnace since I don't care for manual fan control. Now the green wire was Common, and the blue wire (broken) was hooked up to the fan.
After turning the power back on at the breaker though, I was reading 0V on all of the wires at the two thermostats (the furnace still read 28V across all of them). I turned the power off again, reverted the furnace to its original configuration, flipped the power back on, and am still getting 0V across all wires at the thermostats.

(in the image above, I had temporarily hooked up Y/R alone to the old thermostat so the AC would work while I figured this out. G/C were not connected to it at all)
Everything is flipped on at the breaker:

(granted, I haven't checked the left side of the breaker, but it seems locked, so I assume that it does not have anything I need to access)
I also checked the voltage across the wires at the thermostat at the same time as the furnace with a helper to verify that it wasn't an issue where e.g. there was power for a few seconds & by the time I had moved from the furnace to the thermostat it had already shut off, but that wasn't the issue. Even at the exact same time the furnace is reading 28V, the thermostat wires are reading 0V.
My understanding is that if a continuous wire has voltage on one end (furnace), it will have voltage on the other end (thermostat), so I don't understand how a wire that was working fine just a few minutes prior is suddenly not working. My only thoughts are that whatever was used to splice the wire so that it goes to both the upstairs and downstairs thermostat has tripped / blown, and the connection is no longer continuous. If this is likely the issue, how can I verify it / locate where the splice is? Or are there other potential problems that could cause these symptoms?
Comment: The thing at the bottom left of your panel is a utility pull compartment, so no, there's nothing interesting in there
Answer: The C wire is one side of the transformer and the R wire is the other. The R wire feeds the signal into the thermostat where relays connect that voltage to G (fan), Y (cool) and W (heat). In the furnace control board, G, Y and W are sinks not sources, so you should get a small voltage reading or zero, depending on your meter from R to any of those three. You should get 24-28 from R to C, which are the two terminals on the control transformer.


Design pattern for copy and paste on table cell

Question: I need to copy user's address from one row and apply to all or individuals. Is there any design pattern for it.
My problem is how to select the rows? should it be contextual? is there any working tool?
Comment: In what way does your application differ from a regular spreadsheet program such as Excel? Sounds very similar to me. It would definitely help if you could show a mockup of the layout.
Comment: It is a web application so there wont be any right click menu option.
Answer: I would go with a SHIFT or CTRL select to select multiple cells. I have only seen batch select on rows of data in a table, so I would refrain from adding checkboxes everywhere to select cells.
For copying/pasting you can use a keyboard shortcut, right-click context menu, a floating action menu that appears only on selected cell or a menu bar where you place the actions.
Comment: Copying Text? Isn't that what you want to do? Google sheets and other web applications use a right click context menu, so I think it is not such a big No-Go as a lot of people think.
Checkboxes: Why I would refrain from using checkboxes. 1. You already have a selection in a spreadsheet. The blue borders. Not that obvious but they work. 2. To make a flexible cell selection you would have to put a checkbox in every cell which clutters the UI.
Comment: Thanks Nash, but i don't want to override right click as it has different purpose on web, such as coping text. Also, Why did you say that you will refrain from using check boxes? It allows users to select all or a random order. (I am more inclined towards check boxes as it is widely used pattern and mental modal as well.


Ubuntu login screen seems like 22.04 after updating to 23.04

Question: I updated Ubuntu 22.04 to 23.04. But after booting up. The login screen seems like it is from 22.04. When I suspend and see the login page it seems like 23.04. And the graphics of buttons at login screen is a little bit broken too when I first booted up not suspended.
When suspended:

Login screen:
Answer: Reinstall gnome-shell-common package. And if you are using gdm-settings, change shell theme to Default.
Comment: Reinstalled gnome-shell-common and I am not using gdm-settings to. But issue is not resolved.
Comment: sudo update-alternatives  --auto gdm-theme.gresource

Or

sudo update-alternatives  --auto gdm3-theme.gresource


Rancher - check from the CLI if a cattle port is taken

Question: I have a script that deploys database instances on a dynamic principle by using the rancher CLI commands. Is there a way to check whether a certain port is taken?
F.e. I want to spin up a Postgres server on port 8001 on my cattle. Therefore, first check if the port is taken. If not - start the DB server. Otherwise, try 8002, and so on.
Is there a way for that through the CLI?
Answer: When creating a service, if you leave out the "Public Host Port" and just specify the "Private Container Port" a random port is assigned for the service. You can later query for this service and fetch the port assigned for this service. For your use case this might be a easier approach than figuring out which port has been consumed.
Find screenshots for UI approach attached:


How to fix: Build Monitor View deletes itself randomly

Question: Im using the build monitor plugin (https://wiki.jenkins.io/display/JENKINS/Build+Monitor+Plugin v. jan'17) to create a Jenkins view on a big screen in the breakroom to display current builds. Unfortunately the view gets deleted for no reason after a few days. Then I have to manually recreate the view. I'm using Jenkins 2.176.3.
I had a look in the config.xml file in the jenkins directory on the server. There in the  property the build monitor view is gone. When I recreate the view the config.xml isn't updated. The new view does not appear in the config.xml file. How often is Jenkins updating the config.xml file? A cheap workaround would be to copy the build monitor view xml configuration back into the config.xml file when it's gone, but I want to know the source of this strange behaviour and get rid of it properly. Has somebody experienced the same issue with the build monitor plugin and knows the cause and a solution?
Answer: I still don't know the reason why its deleting itself, but I found a workaround. If you create the view in the top folder and filter it down to fit your purpose it stays. If you create it it in a subfolder it deletes itself.


Unable to detect GPU via Tensorflow/Pytorch after restart DLVM

Question: This issue happened when I restarted my cloud notebook server today.
Can be reproduced using the steps below:

Create a Google Cloud Notebook server with Tensorflow or Pytorch and GPU

After start the server, open the python console:

>>> import torch
>>> torch.cuda.is_available()
True

CUDA device is available until now.

Restart the server, and open the notebook again.

>>> import torch
>>> torch.cuda.is_available()
/opt/conda/lib/python3.7/site-packages/torch/cuda/__init__.py:52: UserWarning: CUDA initialization: CUDA unknown error - this may be due to an incorrectly set up environment, e.g. changing env variable CUDA_VISIBLE_DEVICES after program start. Setting the available devices to be zero. (Triggered internally at  /opt/conda/conda-bld/pytorch_1614378098133/work/c10/cuda/CUDAFunctions.cpp:109.)
  return torch._C._cuda_getDeviceCount() > 0
False

nvidia-smi command works fine.
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 450.80.02    Driver Version: 450.80.02    CUDA Version: 11.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |
| N/A   43C    P0    16W /  70W |      0MiB / 15109MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2020 NVIDIA Corporation
Built on Thu_Jun_11_22:26:38_PDT_2020
Cuda compilation tools, release 11.0, V11.0.194
Build cuda_11.0_bu.TC445_37.28540450_0

This issue can also be reproduced by using TensorFlow. How to fix this kind of case?
Comment: You can follow this public issue tracker (https://issuetracker.google.com/191612865) with regards to this issue. You can [click the "star"](https://cloud.google.com/support/docs/issue-trackers#feature_requests) to raise the priority of the issue.
Comment: Issue should be solved in GPU images now. Image version m74
Comment: Same issue. I ended up making a new VM and it worked again. Reset that VM and the same issue happened.
Comment: I am also facing this problem, for me `nvidia-smi` didn't work. So I installed drivers first and then pytorch. `sudo /opt/deeplearning/install-driver.sh` and for pytorch `conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia`.
Answer: Option-1:
Upgrade a Notebooks instance's environment. Refer the link to upgrade.
Notebooks instances that can be upgraded are dual-disk, with one boot disk and one data disk. The upgrade process upgrades the boot disk to a new image while preserving your data on the data disk.
Option-2:
Connect to the notebook VM via SSH and run the commands link.
After execution of the commands, the cuda version will update to 11.3 and the nvidia driver version to 465.19.01.
Restart the notebook VM.
Note: Issue has been solved in gpu images. New notebooks will be created with image version M74. About new image version is not yet updated in google-public-issue-tracker but you can find the new image version M74 in console.


How to use a string in order to call and assign a value which is already defined ? (In VBA)

Question: I have an integer variable named MaxChart and it has already a value of 1024. Now i want to call this value with a string variable with the same name MaxChart and assign a new value to that.
How do I go about this ?
For i = 1 To 20

    A = "MaxChart"& Cstr(i)

Next i

and then to use A as the name of the variable and assign a new value to it!
This Function exist in MATLAB with name of assignin:
http://de.mathworks.com/help/matlab/ref/assignin.html
I don't know how to use it in VBA?
Comment: So `"MaxChart" = 1024`? - There is no direct equivalent, you would use an `array(numeric_index) =` or a `collection(key_name) =`
Answer: Assigning variable names at runtime is not possible in VBA. If you really need to work with those variable names you can use a dictionary though.
First you have to make a reference to the Microsoft Scripting Runtime:
"Extras - References" => Check "Microsoft Scripting Runtime".
After that you can use a dictionary and reference the keys like this:
Sub Main()

    Set MaxChartDict = CreateObject("Scripting.Dictionary")

    'Create the entries with the appropriate keyname => change the second "i"
    'to whatever value you would like
    For i = 1 To 20
        MaxChartDict.Add "MaxChart" & i, i
    Next

    'Get the values for the key "MaxChart3" and "MaxChart14"
    MsgBox (MaxChartDict("MaxChart3"))
    MsgBox (MaxChartDict("MaxChart14"))

    'Change the value for key "MaxChart3"
    MaxChartDict("MaxChart3") = "foobar"
    MsgBox (MaxChartDict("MaxChart3"))

    Set MaxChartDict = Nothing

End Sub