Parse -0 string as -0.0f

I'm learning C++ using Visual Studio 2015.

I have this method:

double ConvertDegreesToDecimal(std::string value)
{
    using namespace std;
    vector<float> values;
    string item;

    istringstream in(value);

    while (getline(in, item, ' '))
        values.push_back(atof(item.c_str()));

    DegreesCoordinate* coord = new DegreesCoordinate((short)values[0], (unsigned char)values[1], (double)values[2], NotSet);

    return DegreesConverter::convertDegressToDecimal(coord);
}

It works fine with all cases except with this one: -0 17 25. This number is a coordinate in degrees -0 degrees 17 minutes 25 seconds.

I have thought to check inside while (getline(in, item, ' ')) if item is -0 and then multiply atof(item.c_str()) by -1. But, what happens if item is -00 or -000.

Do you know a better approach to parse a negative zero?


Click here view more answers http://ift.tt/1Jfjfzl

getting first array item in angular js service array

i have 2 services. 1 uses the other to fetch data, this works... After that the service provides a getter and setter for a variable

` .service('ClickHandlers', ['$firebase','FirebaseData',function ($firebase,FirebaseData) { var lastClickedVisitedPlace;

    return {

        getLastClickedVisitedPlace: function () {
            console.log('getLastClickedVisitedPlace service function triggered');
            var destinations = FirebaseData.getDestinations();
            console.log('service destinations',destinations);

            **var defaultVisitedplace = destinations[0];
            console.log('service defaultVisitedplace',defaultVisitedplace);
            lastClickedVisitedPlace = defaultVisitedplace.id;**
            console.log('service lastClickedVisitedPlace',lastClickedVisitedPlace);
            return lastClickedVisitedPlace;
        },
        setLastClickedVisitedPlace:function(id){
            console.log('service id',id);
            console.log('setLastClickedVisitedPlace service function triggered');
            lastClickedVisitedPlace = id;
            console.log('service lastClickedVisitedPlace',lastClickedVisitedPlace);
        }

    };
}])`

the following lines: var defaultVisitedplace = destinations[0]; console.log('service defaultVisitedplace',defaultVisitedplace); lastClickedVisitedPlace = defaultVisitedplace.id; don't seem to work, destinations[0] is undefined, but in the line above saying: var destinations = FirebaseData.getDestinations(); console.log('service destinations',destinations);

i get this as return data in console: destinations [] 0: Object 1: Object 2: Object

so how can i get the first array object .id value like you would normally do with destinations[0].id ??


Click here view more answers http://ift.tt/1VpgpcL

Disable Gradle build running

I have using Android Studio build project I click Run(Shift + F10) in Android Studio. Gradle build running ... Create in Background Tasks enter image description here

How to disable gradle build running when Run(Shift + F10) project ??? Thanks.


Click here view more answers http://ift.tt/1YSol6t

.prop() returns object rather than value

I'll try to make my question as simple and clear as possible. So i recently read the .prop() vs .attr() page on the stackoverflow, and decided i'd start using prop() instead of attr().

HTML

<form action="php/select.php" method="POST" class="ajax">
    <fieldset>
        <legend>Show</legend>
        <div>
            <input type="submit" value="Show Servers"/>
        </div>
        <div id="output"></div>
    </fieldset>
    <input type="hidden" name="action" value="SHOW_SERVERS"/>
</form>

JQuery

$(document).ready(function(){
    $("form.ajax").on("submit",function(e){
        e.preventDefault();
        var t=$(this);
        var form=t.serialize();
        var method=t.prop("method");
        var url=t.prop("action");//Before: t.attr("action");
        console.log(url);
    });
});

Here comes the weird part, when i submit that form, what it prints in the console is this

enter image description here

My question is then:

Why does JQuery return an input element rather than the value of the form action property?

Why can .prop() get the value of the method attribute, but not the action attribute

PS: I already know the input has the property name="action".


Click here view more answers http://ift.tt/1Jfjevm

Internet check with volley

I have a static method , which returs boolean value by cheking if internet available or not. I am able to catch "NoerrorConnection" but can't return boolean false to calling function. How to send boolean value from ErrorListener ?

public static boolean isConnectingToInternet()
        {
            JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, "www.google.co.in", new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {


                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (error instanceof NoConnectionError) {


                    }
                }
            });
            AppController.getInstance().addToRequestQueue(req);
            return false;
        }


Click here view more answers http://ift.tt/1IDa5N6

For loop confused as to which value to consider

I have this loop here:

while(n != 0)
    {
        ld = n % 10;
        System.out.println(ld);

        for ( i=1; i <= ld; i++)
        {
            f = f * i;
        }

        System.out.println(f);

        n /= 10;
    }

Let us consider a number, say 123. Now, this loop calculates the factorial of 3 accurately, but when it restarts to calculate the factorial of 2, the for loop gets confused as to which value to take for the variable ld. Is there any solution to this?


Click here view more answers http://ift.tt/1QXwsQi

array numbers wich summ is deviding on 4

I want to print numbers on label from 1-to 100

The number's sum must be dividing on 4.

Example:
print 35. because 3+5 = 8 .
8 dividing on 4.

This is code
from loop printing numbers. but how choose those numbers?
print those numbers from 1 to 100 ;

for (int i = 1; i < 100; i++)
{
     //select numbers wich sum is dividing on 4
     label3.Text += Convert.ToString(i) + " | ";
}


Click here view more answers http://ift.tt/1VpgqNW

How to understanding the expression "{} == true"?

I try to understanding the expression {} == true following the section 7.2.12 of doc Ecma-262.

  1. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y)

The result of ToNumber(true) is 1, then

{} == 1

  1. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison ToPrimitive(x) == y.

I am confused at the ToPrimitive({}) now.

  1. If hint is "string", then

    a. Let methodNames be «"toString", "valueOf"».

  2. Else,

    a. Let methodNames be «"valueOf", "toString"».

Should ToPrimitive({}) be interpreted as {}.toString() or {}.valueOf()?

Suppose the toString() is called.

If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y

So {} == true could be ToNumber(ToPrimitive({})) == ToNumber(true)?


Click here view more answers http://ift.tt/1RQXrg2

How to write extension method that work with base class

Idea is to have extension method that extend my functionality.

So instead of having something like this:

 return Add(Add(storage.GetFirst(), 3), 7);

I want have something like this:

return storage.GetFirst().Add(3).Add(7);

Problem with extension methods is that they have to be static in static class. This is simplify example of what I want to do.

 public class Storage
    {
        public int GetFirst()
        {
            return 100;
        }
        public int GetAll(int x, int y)
        {

            // ... 
            return x + y;
        }
    }
    public abstract class MyBase
    {
        protected Storage storage;
        protected MyBase()
        {
            storage = new Storage();
        }

        public int Add(int what, int howMuch)
        {
            return storage.GetAll(what, howMuch);
        }

    }

    public class MyClass : MyBase
    {
        public int method1()
        {
            return Add(Add(storage.GetFirst(), 3), 7);

            //I want have something like this:
            // return storage.GetFirst().Add(3).Add(7);
        }
    }

Off course classes Storage, MyBase and MyClass must not be static. Logic is simplify to have clean and simple example so relation between classes must stay same. What I want to do is to make Add method to be extension method, but leave everything else "more less same".

Is this possible to do and how?


Click here view more answers http://ift.tt/1VpgoWj

Second element in each loop returns undefined

From fields with the class .edit-links i´m able to retrieve the values but $(this).next(".edit-url").val(); only returns the first found element then only returns undefined. In the console i can see that "this" is targeting the first element as expected but the second .edit-url is not found and returning prevObject.

$('#edit').click(function() {
  edit.revertLink();
});

var edit = {};
edit.revertLink = function() {

  $('.edit-link').each(function(index) {

    var currentName = $(this).val();
    var url = $(this).attr('data-tempurl');
    var meta = $(this).attr('data-meta');
    //edit.changeLiOrgname(this, currentName);

    if (meta === "external") {
      //url = $(this).next(".edit-url").val();
      currentName = $(this).next(".edit-url").val();
      //edit.changeLiOrgURL(this, url);
      $(".edit-url").remove();
    }

    var linkStr = [
      '<a href="' + url + '" class="aktiv">',
      '' + currentName + '',
      '<span class="type float-r">',
      '' + meta + '',
      '</span>',
      '</a>'
    ];

    $(".removeBtn").remove();
    $(this).replaceWith(linkStr.join(''));

  });
}
<button id="edit">Edit</button>
<li data-identifier="4.3e43f44714869abce3fabc5">
  <input class="edit-link" data-meta="internal" data-tempurl="/internal-page.html" type="text" value="Stöd">
</li>
<li>
  <input class="edit-link" data-meta="external" type="text" value="Link">
  <input class="edit-url" type="text" data-tempurl="www.link.se" value="www.link.se">
</li>
<li>
  <input class="edit-link" data-meta="external" type="text" value="link2">
  <input class="edit-url" type="text" data-tempurl="www.link2.se" value="www.link2.se">
</li>
<li>
  <input class="edit-link" data-meta="external" type="text" value="link3">
  <input class="edit-url" type="text" data-tempurl="www.lin3k.se" value="www.link3.se">
</li>

Click here view more answers http://ift.tt/1Jfjeva

Singleton Overlaps?

I have two classes using as singletons.

class Boss {
    static let sharedInstance = Boss()
    private init() {} 

    var user_id : String?
    var username : String?
}



class Job {
    static let sharedInstance = Job()
    private init() {} 

    var job_id : String?
    var JobType : String?
}

But after populating the Boss.sharedInstance first, Job.sharedInstance also containing Boss' class variables. But after replacing the sharedInstance with other name (for eg. job_sharedInstance and boss_sharedInstance) respectively, things are working fine. It's quite weird. Can anybody explain me the reason why it would happen like this. Thanks in advance.


Click here view more answers http://ift.tt/1YSl1Zb

Should every class that is only used once be static?

I've seen various discussions about this and I suppose it may be a bit opinion based, but what I'm trying to find out is if I know I will only use a class once (one instance), should I just make it static for convenience? Is that bad practice or will it create a problem?

For example. If I make a single player game, there will only be one player at all times. So do I make public static class Player{} or do I stick with public class Player{} Player player = new Player();

The idea is that this would save time by not needing to pass around references.


Click here view more answers http://ift.tt/1VpgqNI

Why Fragment closes after closing FragmentActivity

i have to do something like this

i have a fragment that reside in an activity and call fragment activity from the fragment like

Intent in = new Intent(getActivity(), ActivityShowGallery.class);
            in.putExtra(ActivityShowGallery.Gallery, m);
            in.putExtra(ActivityShowGallery.position, 0);
            getActivity().startActivity(in);

but main problem occur when i close the fragment activity then my fragment also closes automatically, i don't know why this happen???


Click here view more answers http://ift.tt/1VpgoW5

Count how many times a conditional is true inside for loop with javascript

I have a for loop that runs over a range of cell values in a Google Apps script I'm trying to write, and each time it loops, it checks to see if a certain condition is true. If it's true, for the time being, it's logging the results to Logger.log().

I need the total number of results that show up in Logger.log() (in this case, it would be 10) and the best way I was able to think of doing that would be to count up by 1 each time that conditional is true in the for loop. It should be very simple to get a numerical value of how many results.

Here's the code I'm using:

var currentsheet = SpreadsheetApp.getActiveSheet();
var values = currentsheet.getRange("A28:E").getValues();

for (i=0; i<values.length; i++) {
if (values[i][3] === "Section 179 Depreciation") {
  var date = values[i][0];
  var amount = values[i][1];
  var desc = values[i][2];
  var expType = values[i][3];
  var notes = values[i][4];

 }
}

What am I missing?


Click here view more answers http://ift.tt/1NQ8jqT

Retrieving rows that have 2 columns matching and 1 different

Below is my table called 'datapoints'. I am trying to retrieve instances where there are different instances of 'sensorValue' for the same 'timeOfReading' and 'sensorNumber'.

For example:

 sensorNumber sensorValue timeOfReading

      5            5           6
      5            5           6
      5            6           10   <----same time/sensor diff value!
      5            7           10   <----same time/sensor diff value!

Should output: sensorNumber:5, timeOfReading: 10 as a result.

datapoints table

I understand this is a duplicate question, in fact I have one of the links provided below for references - however none of the solutions are working as my query simply never ends.

Below is my SQL code:

SELECT table1.sensorNumber, table1.timeOfReading
FROM datapoints table1
WHERE (SELECT COUNT(*)
        FROM datapoints table2
        WHERE table1.sensorNumber = table2.sensorNumber
        AND table1.timeOfReading = table1.timeOfReading 
        AND table1.sensorValue != table2.sensorValue) > 1
        AND table1.timeOfReading < 20;

Notice I have placed a bound for timeOfReading as low as 20. I also tried setting a bound for both table1 and table 2 as well but the query just runs until timeout without displaying results no matter what I put...

The database contains about 700mb of data, so I do not think I can just run this on the entire DB in a reasonable amount of time, I am wondering if this is the culprit?

If so how could I properly limit my query to run a search efficiently? If not what am doing wrong that this is not working?

Select rows having 2 columns equal value

EDIT: Error Code: 2013. Lost connection to MySQL server during query 600.000 sec

When I try to run the query again I get this error unless I restart Error Code: 2006. MySQL server has gone away 0.000 sec


Click here view more answers http://ift.tt/1JfjeeR

How/where to import Angular and Bootstrap .js files in my index.html?

I'm new to web front-end programming and am teaching myself AngularJS.

I have created a very simple webapp that just lets users login and logout. I am running it locally on my Mac OSX.

Below is my index.html file. Although it works, I'm not sure if I'm doing it right. I need to know how and where to import the angular.js files and the bootstrap.js files.

My questions are as follows. I haven't been able to figure this stuff out by googling. I need someone to explain this stuff to me please.

  1. I'm currently importing the angular.js file from http://ift.tt/Q55qZD. Is that correct? Or should I download it and store that file in the same directory as index.html? Why? When should I use the non-minified file? What is the benefit of using non-minified?
  2. I'm currently not importing any bootstrap file(s). Which file(s) should I import? Should I import it/them as a URL or as a file from the same directory as index.html
  3. For both Bootstrap and AngularJS, please tell me which line numbers I should put the script src lines in my HTML.
  4. Should I check the Angular and Bootstrap files into my Github repository?

index.html:

 1     <html ng-app="app">
 2       <head>
 3       </head>
 4       <body ng-controller="Main as main">
 5         <input type="text" ng-model="main.username" placeholder="username"><br>
 6         <input type="password" ng-model="main.password" placeholder="password"><br>
 7         <br>
 8         <button ng-click="main.login()" ng-hide="main.isAuthed()">Login</button>
 9         <button ng-click="main.logout()" ng-show="main.isAuthed()">Logout</button>
10         <br/>
11         {{main.message}}
12         <script src="http://ift.tt/1VpgoFJ"></script>
13         <script src="app.js"></script>
14       </body>
15     </html>


Click here view more answers http://ift.tt/1NQ8lyK

Find biggest value in a python dict

I have a python dict like below:

{    '1': {'a': '0.6', 'b': '0.8', 'c': '2','d': '0.5'},
     '2': {'a': '0.7', 'b': '0.9', 'c': '0.1','d': '0.2'},
     '3': {'a': '0.5', 'b': '0.8', 'c': '3'},
}

How could I get the following result?

('2','a','0.7') ('2',b','0.9') ('3','c', '3') ('1','d', '0.5')


Click here view more answers http://ift.tt/1Vpgqxl

dplyr - how to select columns of certain type

Is there a concise way to select columns of certain type in dplyr? For example, how to select all character columns within a dplyr chain?


Click here view more answers http://ift.tt/1Jfjf2m

Check is user inputs Black, Green or Red. C#

I'm working on a program where I want my user to enter one of the following Colors (Red, Green or Black). But I am stuck.

What I have done so far is this

Console.Write("Color To Bet on: ");
string tempColor = Console.ReadLine();

while (String.IsNullOrWhiteSpace(tempColor))
{
    Console.Write("The color can't be null.");
    tempColor = Console.ReadLine().ToLower();
}

But how can I make sure my users puts in the color I want, I've tried fiddling around with string. Contains method but haven't had any success so far.


Click here view more answers http://ift.tt/1VpgoFB

How to implement a closure in jQuery [on hold]

I don't know much about jQuery. Here I am trying to implement a closure to attach a click event to each anchor tag so that each of them will alert a certain number once blicked. But I am getting the following error:

SyntaxError: missing ) after argument list


};})(i);

can anyone help me with this problem?thanks :)

Code:

<div id='pageBox'>
    <ul id='pageContainer'>
        <?php for($i=1;$i<=$pagenum;$i++){?>
           <li><a href=''><?php echo $i;?></a></li>
        <?php }?>
    </ul>
 </div>
<script>
for(i=1;i<=<?php echo $pagenum;?>;i++){

      $('#pageContainer li a').click((function(i){return function(event){
               event.preventDefault();
               alert(i);
            };})(i);
      );

}  


Click here view more answers http://ift.tt/1QXmsX9

PHP Bug or my misunderstanding of the language?

This is the code that I don't understand (as the output).

<?php
$x = ['test1', 'test2', 'test3', 'test4'];
echo "First FOREACH\n";
foreach ($x as &$y)
{
    echo $y."\n";
}
echo "\n\nSecond FOREACH\n";
foreach ($x as $y)
{
    echo $y."\n";
}

?>

Output:

First FOREACH
test1
test2
test3
test4

Second FOREACH
test1
test2
test3
test3

PS: I'm running it under:

php -v
PHP 5.6.11-1ubuntu3.1 (cli) 
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies


Click here view more answers http://ift.tt/1Vpgopj

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login.php

i'm getting the following error

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login.php

everything else work fine... except for this !

Here's my query :

<?php

$inputuser = $_POST["user"];
$inputpass = $_POST["pass"];

$user = "root";
$password = "";
$database = "share";

$connect = mysql_connect("localhost:3306",$user,$password);
@mysql_select_db($database) or ("Database not found");

$query = "SELECT * FROM 'users' WHERE 'username'= '$inputuser'";
$querypass = "SELECT * FROM 'users' WHERE 'password'= '$inputpass'";

$result = mysql_query($query); 
$resultpass = mysql_query($querypass); 

$row = mysql_fetch_array($result);
$rowpass = mysql_fetch_array($resultpass);

$serveruser = $row['user'];
$serverpass = $row['password'];

if ($serveruser && $serverpass) {
    if (!$result) {
       die ("Invalid Username/Password");

 }
        header('Location: Fail.php');
        mysql_close();


if ($inputpass == $serverpass) {

        header('Location: Home.php');

} else {


}
}

?>


Click here view more answers http://ift.tt/1QXmsGN

Decode HTML string where ampersands are encoded as \\x26

I got a string from html like:

var htmlStr = " \\x26lt;span\\x26gt; \\x26lt;/span\\x26gt;";

I can't decode it to C# string like:

 <span> </span>

If I modify the string to

var htmlStr = " \x26lt;span\x26gt; \x26lt;/span\x26gt;";

It works good. But how can I do it by replacing string or others way?

BTW, I use Encoding.UTF8.


Click here view more answers http://ift.tt/1Jfjf2f

Pointers to elements of a C++ class

I have a C++ class c_image which contains a vector of pointers to elements of class c_pixel:

class c_image {

    public:
        vector<shared_ptr<c_pixel>> pixel;
    ...
};

Class c_pixel elements contain an element Z of type double:

class c_pixel {

    public:
        double Z;
    ...
};

However, they are extended with class c_pixel_pv, which contains pv, an array of three elements of type double:

class c_pixel_pv : public c_pixel {

    public:
        double pv[3];
    ...
};

Class c_image also has a function filter

vector<double> c_image::filter(???) {
        ...
    };

which will take as input a pointer to the elements Z or pv[0] or pv[1] or pv[2].

But I have no idea how to point to these elements. I don't even know if it is possible to point, for example, only to pv[0] elements. I have no clue how to begin with this problem. Can anybody help me?


Click here view more answers http://ift.tt/1Vpgopd

How to add space at the start and end of eachline

I have created a custom textview class and I am using BackgroundColorSpan to apply color in the background. How can I add blank space before and after each line. I really appreciate any help.

final String test_str1 = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";


public class CustomTextView extends TextView {
    public CustomTextView(Context context) {
        super(context);
        setFont();
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setFont();
    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setFont();
    }

    private void setFont() {
        Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/TEXT.ttf");
        setTypeface(font, Typeface.NORMAL);

        Spannable myspan = new SpannableString(getText());
        myspan.setSpan(new BackgroundColorSpan(0xFF757593), 0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        txtview.setText(myspan);
    }
}


Click here view more answers http://ift.tt/1Os7Vfn

DATEDIFF - Replace NULL with NOW()

I got following SQL Query

SELECT
    e.id,
    c.name,
    e.location,
    e.designation,
    e.time_period_from,
    e.time_period_to,
    DATEDIFF(e.time_period_to, time_period_from) AS tenure_in_days
FROM
    employment e
LEFT JOIN
    company c ON (c.id = e.company_id)
LIMIT
    0, 10

This is working perfectly, i have a scenario where time_period_to can have NULL values, in this case, i want to replace it with current date.

Here is what i tried.

SELECT
    e.id,
    c.name,
    e.location,
    e.designation,
    e.time_period_from,
    e.time_period_to,
    DATEDIFF(IF(ISNULL(e.time_period_to), NOW(), e.time_period_from)) AS tenure_in_days
FROM
    employment e
LEFT JOIN
    company c ON (c.id = e.company_id)
LIMIT
    0, 10

This gives me the following error

ERROR 1582 (42000): Incorrect parameter count in the call to native function 'DATEDIFF'

Where am i going wrong?


Click here view more answers http://ift.tt/1Jfjf29

Divide and conquer for function compositions

I was searching the algorithm for finding the composition of 2 linear functions n times (where n can be as large as 10^18) in O(log n) time. I just got a pdf ( http://ift.tt/1JfjeLV ) containing polynomial composition of 2 functions with large degrees using divide and conquer algorithm.

I was wondering whether my problem for composition of linear function n times can also be solved using divide and conquer algorithm in O(log n) complexity?

If yes, please explain the algorithm.

Thanks, in advance.

EDIT 1: The composition of function f(x) n times is fofof...n-times. Here the function is to be composed to itself n times. There are no 2 functions.


Click here view more answers http://ift.tt/1Vpgopb

use for each to get each input value [on hold]

I'm expecting value 1 and 2 but it returned null instead. Any idea why is this happening?

$(function() {

  $('.agent_rows').each(function() {
    console.log($(this).find('input[name="associatedAgentId"]').val())
  })

});
<script src="http://ift.tt/1oMJErh"></script>
<div class="agent_rows">
  <input type="hidden" name="associatedAgentId" val="1">
</div>

<div class="agent_rows">
  <input type="hidden" name="associatedAgentId" val="2">
</div>

Click here view more answers http://ift.tt/1ks1O2R

Eclipse giving me a warning saying

Code:

    p.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e)
    {

        System.out.println("Welcome to Guess the number Game");
        System.out.println("You have 3 chances to guess a number between 0 and 10 excluding 10");

        ne.remove(p);

        //ne.removeAll();
        ne.revalidate();
        ne.repaint();}
       public void cam()
       {

        gamer2 game=new gamer2();
        game.generatenum();
       }
    }

    ); 

p is a JButton.

Eclipse is giving me a warning saying:"The method cam() from the type new ActionListener(){} is never used locally.

Why is it giving that warning?


Click here view more answers http://ift.tt/1QXlgDf

Animating image on toggle

I managed to create a div that toggled open and close and then stopped a hover animation while it was open. Which is good, and the div slides open nicely however, the image in the div does not slide open. How do I make the image follow the div instead of just blinking on?

Here is the div unopened: enter image description here

Here is the div opened, and the .block overflow:visible (once I get this working Ill make the image fit the div:

enter image description here

At the moment the stuff below the image slides down nicely, but the image just changes from overflow hidden to overflow visible without animation. How can I make it with animation?

Here is the html:

<div class="work">
        <h1 class="heading">Selected Projects</h1>
        <div class="line"></div><br>
        <ul>
            <li id="darl">
               <div class="block">
                    <img class="bg-image"  id="bgimg1" src="Images/perspective2final2pfolio2.jpg">
                </div>
                <p>1. Darlington Terrace<i id="close1" class="fa fa-times-circle-o"></i></p>
            </li>

            <li><div class="thinline"></div></li>
            <li id="chil">
             <div class="block">
                    <img class="bg-image"  id="bgimg2" src="Images/DSC_0756.jpg">
                </div>
                <p>2. Children's Playground</p>
            </li>

            <li><div class="thinline"></div></li>
            <li id="lawn">
               <div class="block">
                    <img class="bg-image"  id="bgimg3"src="Images/perspective2final2pfolio2.jpg">
                </div>
                <p>3. Lawn Bowl Bakery Bridge</p>
            </li>

            <li><div class="thinline"></div></li>
            <li id="aque">
                <div class="block">
                    <img class="bg-image"  id="bgimg4"src="Images/perspective2final2pfolio2.jpg">
                </div>
                <p>4. Aqueduct: Museum of Architecture</p>
            </li>

            <li><div class="thinline"></div></li>
            <li id="velo">
                <div class="block">
                    <img class="bg-image"  id="bgimg5"src="Images/perspective2final2pfolio2.jpg">
                </div>
                <p>5. Velocity Frequent Flyer Website</p>
            </li>

            <li><div class="thinline"></div></li>
        </ul>

    </div>

Here is the jquery (the fadeOutt is for a hover effect that fades in/out the image on the div):

$("#darl").click(function() {
  $(this).toggleClass('expanded');
      if($("#darl").hasClass('expanded')){
     $(this).off('mouseleave',fadeOutt);
}else{
    $(this).on('mouseleave',fadeOutt);
}
});

And here is the css for #darl:

#darl {
overflow: visible;
height: 54px;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-ms-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}

#darl.expanded {
height: 300px;
}

#darl .block {
overflow: hidden;
}

#darl.expanded .block {
overflow: visible;
transition: all 0.5s ease-in-out;
}

Here is the full code files: http://ift.tt/1ks1Pnr

Thanks so much for help!


Click here view more answers http://ift.tt/1mhPAvs

Initializers from generic types won't be inherited in swift?

Here is my code:

public  class A<T:Any> { 
    public init(n:Int) { 
        print("A")
    } 
} 
public class B:A<Int>{}
public class C:B{}
let x = C(n:123)

And this fails compilation and yells such error:

repl.swift:9:9: error: 'C' cannot be constructed because it has no accessible initializers

And the following code can be compiled.

public  class A { 
        public init(n:Int) { 
            print("A")
        } 
    } 
    public class B:A{}
    public class C:B{}
    let x = C(n:123)

Shouldn't requirement types specified generic types' initializers be inherited?


Click here view more answers http://ift.tt/1mhPC6v

How to get the output of ping(bash) while it is running?

I want to monitor round-trip time of my network, drawing the date using highcharts on linux

I know how to get the result of ping after it finished running. Like:

[root@localhost dev]# ping stackoverflow.com -c 5
PING stackoverflow.com (104.16.36.249) 56(84) bytes of data.
64 bytes from 104.16.36.249: icmp_seq=1 ttl=128 time=341 ms
64 bytes from 104.16.36.249: icmp_seq=2 ttl=128 time=351 ms
64 bytes from 104.16.36.249: icmp_seq=3 ttl=128 time=342 ms
64 bytes from 104.16.36.249: icmp_seq=4 ttl=128 time=294 ms
64 bytes from 104.16.36.249: icmp_seq=5 ttl=128 time=286 ms

--- stackoverflow.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 5622ms
rtt min/avg/max/mdev = 286.302/323.460/351.832/27.258 ms
[root@localhost dev]# 

I know how to get the info such as rtt min/avg/max/mdev = 286.302/323.460/351.832/27.258 ms after ping has finished.

Now I want to draw a Live chart using Ajax.

Is there a way to get the output of ping while it is running? I need the round-trip time.

[root@localhost dev]# ping stackoverflow.com       
PING stackoverflow.com (104.16.36.249) 56(84) bytes of data.
64 bytes from 104.16.36.249: icmp_seq=1 ttl=128 time=359 ms
64 bytes from 104.16.36.249: icmp_seq=2 ttl=128 time=341 ms
64 bytes from 104.16.36.249: icmp_seq=3 ttl=128 time=348 ms
64 bytes from 104.16.36.249: icmp_seq=4 ttl=128 time=359 ms
64 bytes from 104.16.36.249: icmp_seq=5 ttl=128 time=357 ms
64 bytes from 104.16.36.249: icmp_seq=6 ttl=128 time=301 ms
64 bytes from 104.16.36.249: icmp_seq=7 ttl=128 time=299 ms

I need time : 64 bytes from 104.16.36.249: icmp_seq=7 ttl=128 time=299 ms

Please help with linux bash shell, js and php. Thank you.


Click here view more answers http://ift.tt/1OYPIGE

javascript validation phone number

alright, whats wrong with my script, JShint is throwing three lines of red code saying i have issues in my variable and my if/else statement. I am trying to validate if the phone number is a valid USA phone format

    $( "#phone" ).focusout(function telephone() {
    if( this.value === "" || this.value === null ) {
        $( "#error_messages" ).text("");
        return false;
    } else {
        var re = \d{3}[\-]\d{3}[\-]\d{4};
        if(re.test(document.getElementById("phone").value)) {
            $( "#error_messages" ).text("");
            return true;
        } else {
            $( "#error_messages" ).text("Phone Number* not a valid format xxx-xxx-xxxx");
            return false;
        }
    }
});


Click here view more answers http://ift.tt/22xYFRb

Destroy All Previous Activities After Specific Activity is Open

This is the scenario

Activity A -> Activity B -> Activity C -> Activity D (I would like to destroy Activity A, B, and C after Activity D is launched.

Any ideas please?


Click here view more answers http://ift.tt/1mpcqR7

jquery alternative to change or keyup

I have a form in which the user must initial a bunch of different sections.

<script>
  $.function(){
    $('.initialMe').change(function(){
      var id = $(this).attr('id');
      alert(id);
    }); 
  });
</script>

<?php
  echo "<div class='signature'>Initial Here:<input type='text' class='initialMe' id='sign[service1]' name='sign[service1]' size='4'></div>";
  echo "<div class='signature'>Initial Here:<input type='text' class='initialMe' id='sign[service2]' name='sign[service2]' size='4'></div>";
?>

I want to fire off an action when they are done initializing the text box. I don't want to use change because they have to click off somewhere for event to be fired. I don't want to use keyup, because event will fire after first letter of initials. I do not know if user will use 2 letters or 3 for initials. This is not a submittable form. Think of it as a legal document where the user has to initial different sections of the page. What options do I have?


Click here view more answers http://ift.tt/1OYPIqh

Recursive function not returning sum of object values

Why sum is undefined. What am I doing wrong?

var testData1 = [{
  "name": "Doctors",
  "category": "Doctors",
  "subCategory": [{
    "name": "Likes",
    "category": "Likes",
    "subCategory": [{
      "name": "Visit",
      "category": "Visit",
      "subCategory": [{
        "name": "Charges",
        "category": "Charges",
        "subCategory": null,
        "val": 30
      }]
    }]
  }, {
    "name": "Dislikes",
    "category": "Dislikes",
    "subCategory": [{
      "name": "Quality",
      "category": "Quality",
      "subCategory": [{
        "name": "Appointment",
        "category": "Appointment",
        "subCategory": null,
        "val": 50
      }, {
        "name": "Care",
        "category": "Care",
        "subCategory": null,
        "val": 70
      }, {
        "name": "Attentive ",
        "category": "Attentive ",
        "subCategory": null,
        "val": 90
      }]
    }]
  }, {
    "name": "Neutral",
    "category": "Neutral",
    "subCategory": [{
      "name": "Professional ",
      "category": "Professional ",
      "subCategory": [{
        "name": "Ease",
        "category": "Ease",
        "subCategory": null,
        "val": 50
      }, {
        "name": "Competent ",
        "category": "Competent ",
        "subCategory": null,
        "val": 40
      }, {
        "name": "Availability",
        "category": "Availability",
        "subCategory": null,
        "val": 80
      }]
    }]
  }],
  "index": 6
}, {
  "name": "Service",
  "category": "Service",
  "subCategory": [{
    "name": "Likes",
    "category": "Likes",
    "subCategory": [{
      "name": "Environment",
      "category": "Environment",
      "subCategory": [{
        "name": "Professionalism ",
        "category": "Professionalism ",
        "subCategory": null,
        "val": 50
      }, {
        "name": "Room",
        "category": "Room",
        "subCategory": null,
        "val": 30
      }, {
        "name": "Parking",
        "category": "Parking",
        "subCategory": null,
        "val": 20
      }]
    }, {
      "name": "Availability",
      "category": "Availability",
      "subCategory": [{
        "name": "Competent ",
        "category": "Competent ",
        "subCategory": null,
        "val": 30
      }]
    }]
  }, {
    "name": "Dislikes",
    "category": "Dislikes",
    "subCategory": [{
      "name": "Management",
      "category": "Management",
      "subCategory": [{
        "name": "Staff",
        "category": "Staff",
        "subCategory": null,
        "val": 50
      }, {
        "name": "Operations",
        "category": "Operations",
        "subCategory": null,
        "val": 70
      }]
    }, {
      "name": "Nurses",
      "category": "Nurses",
      "subCategory": [{
        "name": "Medicine",
        "category": "Medicine",
        "subCategory": null,
        "val": 30
      }]
    }]
  }, {
    "name": "Neutral",
    "category": "Neutral",
    "subCategory": [{
      "name": "Serving",
      "category": "Serving",
      "subCategory": [{
        "name": "Took long time",
        "category": "Took long time",
        "subCategory": null,
        "val": 50
      }, {
        "name": "Rude",
        "category": "Rude",
        "subCategory": null,
        "val": 40
      }, {
        "name": "Seated",
        "category": "Seated",
        "subCategory": null,
        "val": 80
      }]
    }]
  }],
  "index": 16
}];

function addSum(data) {
  data.forEach(function(d, index) {
    if (Array.isArray(d.subCategory)) {
      return (0 + addSum(d.subCategory));

    } else {

      document.write('<pre>' + JSON.stringify(d.val, 0, 4) + '</pre>');
      return d.val;
    }
  });
}
var sum = addSum(testData1);
alert(sum);

Click here view more answers http://ift.tt/1YSbrWb

how to manipulate private variable between classes

I'm trying to build a stock inventory and cash register simulation, in the code I have 2 class, first is Inventory and second is Cash. Both have their own properties and method, when I'm trying to sell item the _balance property is giving Error undefined _balance and the _balance is still 0. How should I fix it? Just in case this question have been already asked please just give the link don't mark as duplicate. I just can't find it.

<?php
        class Inventory {
            public $_name;
            public $_price;
            public $_stock;
            public function _addStock($item,$itemIn)
            {
                $this->_stock += $itemIn;
            }
        };

        $item2 = new Inventory;
        $item2->_name = "item2";
        $item2->_price = 5000;
        $item2->_addStock('item2',100);
        $item1 = new Inventory;
        $item1->_name = "item1";
        $item1->_price = 1000;
        $item1->_addStock('item1',100);

        class Cash {
            private $_balance = 0;
            public function _display(Inventory $_name)
            {
                echo $_name->_price;
            }
            public function getBalance()
            {
                echo $this->_balance;
            }
            public function sell(Inventory $_name, $amount)
            {   
                return $_name->_stock -= $amount;

                return $_balance += $_name->_price*$amount;// Error $_balance undifined
            }    
        };
        $cash = new Cash;
        print_r($item2);
        echo "<br/>";
        print_r($item1);
        echo " <br/>Balance :<br/>";
        $cash->getBalance();
        echo "<br/>item1 price :<br/>";
        $cash->_display($item1);
        echo "<br/>item2 price :<br/>";
        $cash->_display($item2);
        echo "<br/>item1 sold 12 pcs<br/>";
        $cash->sell($item1,12);

        $cash->sell($item2,12);
        echo "<br/>item2 sold 12 pcs <br/>";

        echo "<br/> current stock :<br/>";
        print_r($item2);
        echo "<br/>";
        print_r($item1);

        echo "<br/> current balance :<br/>";
        $cash->getBalance();
        ?>


Click here view more answers http://ift.tt/1mhPAeU

why the first statement is illegal while the second is legal?

I'm new to C++. I'm trying to learn the concept of const. Could someone please tell me why the first statement is illegal while the second is legal?

int i = -1, &r = 0;         

const int i = -1, &r = 0;  


Click here view more answers http://ift.tt/1ks1Pnb

Convert matching arrays to one single array

i need your help, i have an array which look like this

Array
(
    [vaccine_id] => 1
)
Array
(
    [vaccine_id] => 1
)
Array
(
    [vaccine_id] => 1
)
Array
(
    [vaccine_id] => 2
)
Array
(
    [vaccine_id] => 2
)
Array
(
    [vaccine_id] => 2
)
Array
(
    [vaccine_id] => 12
)
Array
(
    [vaccine_id] => 12
)
Array
(
    [vaccine_id] => 12
)

and i need to convert it so it can look some thing like this so that array with the same key and value should not repeat. e.g

Array
(
    [vaccine_id] => 1
)
Array
(
    [vaccine_id] => 2
)
Array
(
    [vaccine_id] => 12
)

my code looks like this. i am using codeigniter framework.

$data['vaccManagment'] = $this -> Common_model -> get_info('manage_epi_vacc', '', '','*', array('uncode' => $this -> uri -> segment(3), 'fmonth' => $this -> uri -> segment(4)));
        $vaccManagmentDetail = $this -> Common_model -> fetchall('manage_epi_vacc_items_record', '','vaccine_id', array('uncode' => $this -> uri -> segment(3), 'fmonth' => $this -> uri -> segment(4),'manage_vacc_id'=>$data['vaccManagment']->recid));
        $newDetail = array();
        foreach($vaccManagmentDetail as $detail){
            print_r($detail);
        }exit;

Thanks for your interest.


Click here view more answers http://ift.tt/1ks1P6X

How to declare a self-referential container in C++?

For a typedef of a struct in C, I can't do this:

typedef struct {
    unsigned id;
    node_t *left;
    node_t *right;
} node_t;

because node_t is not known until it is defined, so it can't be used in its own definition. A bit of a Catch-22. However, I can use this workaround to make the desired self-referential type:

typedef struct node_s node_t;
struct node_s {
    unsigned id;
    node_t *left;
    node_t *right;
};

Similarly, I would like to do something like this for a C++ container referring to itself:

typedef pair<unsigned, pair<node_t *, node_t * > > node_t;

but of course, the compiler complains that it's never heard of node_t before it's defined node_t, as it would for the struct typedef above.

So is there a workaround like for the struct? Or some better way to do this? (And no, I don't want to use void pointers.)


Click here view more answers http://ift.tt/1ks1NvQ

Concurrent access to a public field. Why is it possible to observe inconsistent state?

I'm reading B. Goetz Java Concurrency In practice and now I'm at the section 3.5 about safe publication. He stated:

// Unsafe publication
public Holder holder;
public void initialize() {
    holder = new Holder(42);
}

This improper publication could allow another thread to observe a partially constructed object.

I don't see why it is possible to observe a partially constructed subobject. Assume, that the constructor Holder(int) does not allow this to escape. So, the constructed reference can be observed only by the caller. Now, as JLS 17.7 stated:

Writes to and reads of references are always atomic, regardless of whether they are implemented as 32-bit or 64-bit values.

it is impossible for thread to observe a partially constructed object.

Where was I wrong?


Click here view more answers http://ift.tt/1MGl6b6

Accessing a static variable and setting it outside the class

Here is a SubtitleCustomField class.

Class SubtitleCustomField: CustomCellField {
static var CellIdentifier: String!

  override init(frame: CGRect) {
  super.init(frame: frame)
  if CellIdentifier == "A" {
   //DO SOMETHINIG
  } else if CellIdentifier == "B" {
  //DO SOMETHING
  }

  }
}

Outside SubtitleCustomField class, I basically need to access static variable CellIdentifier, set value like "A", and trigger if statement to run.

In another class, Custom class, I've confirmed that I can access the static variable, Cell Identifier, in a following way:

Class Custom: CustomViewController {
     SubtitleCustomField.CellIdentifier = "part1_subtitle"
}

I face a problem at this point. In SubtitleCustomField class, I get an error on if CellIdentifier == "A" saying

Static member 'CellIdentifier' cannot be used on instance of type 'SubtitleCustomField'

What would be the best approach I can use to achieve what I want? In summary, I want to set CellIdentifier variable outside 'SubtitleCustomField' and trigger if statement with the value I set in 'SubtitleCustomField' class.


Click here view more answers http://ift.tt/1PwiBi9

Database for Android App

How and where I can maintain my DB for my android app. I know we can use sqlite DB for android apps but, I don't have any idea of Storing the DB at some other location and then accessing it on the app.

Example Structure:

enter image description here

I want to know, where and how we can have DB at some different point of location, Do I need to buy space or rent? Or there are any other ways (Having DB Server at my own Desktop and accessing it via IP address. Will there be any difficulties or dependencies) I believe we can access it by creating a connection to the Db and writing queries to fetch by using Http Get and Post or Put methods.

If yes, then can we use SQL Server Management studio 2008 or what would be the simplest & the best to work with.


Click here view more answers http://ift.tt/1ID4IO0

How to listen a frame property of a view on iOS

I have a view and I added a observer like this:

_aView = [UIView new];
[_aView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
_aView.frame = CGRectMake(100, 100, 100, 100);

In the observer method I get the new value : - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"frame"]) { NSLog(@"%@", change[@"new"]); } } The log is NSRect: {{100, 100}, {100, 100}}. The question is that I got the value type is NSRect, how to convert it to CGRect?

In the UIKit library have no type named NSRect


Click here view more answers http://ift.tt/1OYN2ZB

Add data at the end of existing data in resource file

I want to add data at the end of existing data in resource file on the click of button in windows form. I have a windows form with 3 text boxes -

text_box1: Name
text_box2: Value
text_box3: Comments
and a button named as Save.

code for button:

 private void button1_Click(object sender, EventArgs e)
        {
            myMethod.Create(textBox1.Text, textBox2.Text, textBox3.Text);
        }

Method to add data in resource file:

public class myMethod
    {
        public static void Create(string myName, string myValue, string myComment)
        {
            try
            {
                ResXResourceReader resxReader = new ResXResourceReader(@"D:\Validator_Tool\resx\resx\myres.resx");
                resxReader.UseResXDataNodes = true;
                IDictionaryEnumerator data = resxReader.GetEnumerator();

            while (data.MoveNext())
            {
                ResXResourceWriter resxWriter = new ResXResourceWriter(@"D:\Validator_Tool\resx\resx\myres.resx");
                var node = new ResXDataNode(myName, myValue);
                node.Comment = myValue;
                resxWriter.AddResource(node);
                resxWriter.Close();
            }

            }
            catch (FileNotFoundException caught)
            {
                MessageBox.Show("Source: " + caught.Source + " Message: " + caught.Message);
            }
        }
    }

Please help me in this problem to add data in resource file because with this code my data is overwrite with existing data but I want my data should append at the end of the existing data. This code giving me exception too while using IDictionaryEnumerator exception is:

System.InvalidOperationException


Click here view more answers http://ift.tt/1mhPzYt

How to convert an array all value without using foreach loop

I want to convert an array value without using any loop and i have an array something like this

Array
  (
[0] => Array
       (
        [month] => August
       )

[1] => Array
    (
        [month] => July
     )

[2] => Array
    (
        [month] => October
    )
)

I want to convert above array in to below format

  Array
  (
  [month] => August  
  )
  Array
  (
  [month] => July   
  )
  Array
  (
  [month] => October
  )

Without using any loop


Click here view more answers http://ift.tt/1ks1P6R

Javascript OOP literal access variable inside method

i have a problem accessing variable inside method in OOP.

this is my code :

var slideshow = {

    elSet   : $(".slideshow"),
    next    : function() {

    },
    swipe   : function() {
                var clear = this.autorun().loop;

                onSwipe(function() {

                    clearInterval(clear); // not working
                });
    },
    autorun    : function() {

                var self = this;
                var loop = setInterval(function() {

                        self.next();

                    }, 5000);

    },
    initial : function() {

                this.swipe();
                this.autorun();
    }

}

slideshow.initial();

i want to clearInterval from variable loop,

on browser console return error TypeError: this.loop(...) is undefined

what's wrong with my code?


Click here view more answers http://ift.tt/1Jff4U9

PHP : sending reset password link in email

i am sending password reset link using html email in php . this is structure of m code . First is html email

<?php $bodymessage= '<table border="0" cellpadding="0" cellspacing="0" width="100%" >;
 $bodoymessaage= .='<a href="$link"' .....?>

the i've setup heaeders

 <?php $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
 ?>

and after this i recieve form fields and mail function like this

if($passreset){
       mail($to, $subject, $bodymessage, $headers);
} 

now problem is that I've to get reset link and place it in html template thats being set in query and that comes after html template and headers , my questions is what should be order of template , headers and form query that i may get reset link in html template here $bodoymessaage= .='<a href="$link"' .....?>


Click here view more answers http://ift.tt/1Jff7iU

Sessions in PHP 7

I have been working with PHP 5.xx for years but recently updated to PHP 7. I can't create sessions.

I have read the documentation.

In earlier PHP, you just have to do:

session_start();

to start session, but this doesn't work with PHP 7 and my page keeps loading. I provided the array in the parameter too as documented on the PHP website but still it keeps loading the page.

I have tried this:

session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);

But my browser keeps loading and after few seconds it displays 'This webpage is not available'

Apache restart errors:

[Wed Dec 30 00:45:16.470001 2015] [mpm_winnt:notice] [pid 2384:tid 376] AH00455: Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.0 configured -- resuming normal operations

[Wed Dec 30 00:45:16.470001 2015] [mpm_winnt:notice] [pid 2384:tid 376] AH00456: Apache Lounge VC14 Server built: Dec 9 2015 10:17:39

[Wed Dec 30 00:45:16.470001 2015] [core:notice] [pid 2384:tid 376] AH00094: Command line: 'c:\xampp\apache\bin\httpd.exe -d C:/xampp/apache'

[Wed Dec 30 00:45:16.470001 2015] [mpm_winnt:notice] [pid 2384:tid 376] AH00418: Parent: Created child process 1716

[Wed Dec 30 00:45:17.172064 2015] [ssl:warn] [pid 1716:tid 384] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name

[Wed Dec 30 00:45:17.343941 2015] [ssl:warn] [pid 1716:tid 384] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name

[Wed Dec 30 00:45:17.375192 2015] [mpm_winnt:notice] [pid 1716:tid 384] AH00354: Child: Starting 150 worker threads.


Click here view more answers http://ift.tt/1mhPzI1

Updating global variable via callback

I have the following function

   var urls = '';
    handleFiles(f,function(url){
        urls = urls + url + ',';
        console.log("urls is " + urls);
    });

I get the url after uploading and update my urls. But my Urls never gets updated, it shows the url of the last file uploaded.

UPDATE 1 This is my complete code now.

var urls = '';
document.getElementById('question-file-selector').addEventListener('change',handleFileSelect,false);
    function handleFileSelect(evt){
        var files = evt.target.files; //File list object
            // Loop through file list, render image files as thumbnails
        for (var i = 0,f;f = files[i];i++){


        handleFiles(f,function(url){
                urls = urls + url + ',';
                console.log("urls is " + urls);
                });
        // Only process image files
        if (!f.type.match('image.*')){
            $('#list').append('<img class="file-thumb" src="/static/download168.png"/>');
            continue;
        }
        var reader = new FileReader();

        //Closure to capture file information
        reader.onload = (function(theFile){
                return function(e){
                    //Render thumbnail
                    $('#list').append('<img class="thumb" src="'+e.target.result+'" title="'+escape(theFile.name)+'"/>'); 
                    };
                    })(f);
        reader.readAsDataURL(f);
    }
    }

console.log("Url is",urls);`   

And my ajax function

    //Code for Image upload

// Custom jQuery xhr instance to support our progress bar.

var xhr_with_progress = function() {
     var xhr = new XMLHttpRequest();
     xhr.upload.addEventListener("progress",
         function(evt) {
             if (!evt.lengthComputable) return;
             var percentComplete = evt.loaded / evt.total;
             $("#progress-bar div.progress-bar").css('width', String(100*percentComplete) + "%");
         }, false);
     return xhr;
 };





$.support.cors = true;//For cross origin transfer

//Event listners to avoid default drag and drop reaction of browser
window.addEventListener("dragover",function(e){
  e = e || event;
  e.preventDefault();
},false);
window.addEventListener("drop",function(e){
  e = e || event;
  e.preventDefault();
},false);



function handleFiles(file,callback){

            var filename = file.name;
            $.ajax({
                type:'GET',
                data:{"filename":file.name, "FileType":"question_file"},
                url:'/dashboard/generateuploadurl/',
                contentType:"application/json",
                dataType:"json",
                async:false,
                success: function(data){ 
                    if(data.UploadUrl){
                      console.log("upload url successfully created for " + file.name + " file");
                        console.log(data.UploadUrl);
                        handleUpload(data.UploadUrl, file, data.Filename,callback);

                    }
                },
                error: function(data){ 
                    console.log("error occured while creating upload url for " + file.name + ' file');
                    console.log(data);
                },
            });
        }           
function handleUpload(UploadUrl, file, Filename,callback){
    $.ajax({
        xhr:xhr_with_progress,
        url:UploadUrl,
        type:'PUT',
        data:file,
        cache:false,
        contentType:false,
        processData:false,
        success: function(data){
            console.log('http://ift.tt/1mhPyDP'+ Filename);
            callback('http://ift.tt/1mhPyDP'+ Filename);
        },
        error: function(data){ 
            alert("error occured while uploading " + file.name );
            console.log(data);
        },
    }); 
}


Click here view more answers http://ift.tt/1Os3Bwt

Align elements inside an tag vertically

I have an <a> tag (which is part of multiple <li> tags). In the <a> tag I have an <i> tag and some text - the text of the link.

What I would like to achieve is to have the icon on top and the text under it (and then centered). So it would look like:

   ICON
MYTEXTHERE

However they are always placed next to each other. I tried using display: inline-block - because my <a> is inline and the content inside should be block but without success.

The fiddle is here: http://ift.tt/1mFkDBp


Click here view more answers http://ift.tt/1YHObKm

how to use ng-repeat in append to get the key value?

if i use ng-repeat in append html div, the content is not appending. how to get the label name key value on appended each fields. i want to change each label name from field label options from below code. click on appended div, it will shows filed label options, from there i have to change each label name seperately.. pls help me

var app = angular.module('myapp', ['ngSanitize']);

app.controller('AddCtrl', function ($scope, $compile) {

    $scope.field = {single: 'untitled'};
    $scope.addNew_SingleField = function (index) {
              var singlehtml = '<fieldset ng-repeat="(fieldkey, field) in singleField" ng-click="selectSingle($field)"><label ng-bind-html="field.single"></label><input type="text" placeholder="Enter name" name="{{field.single}}"><button ng-click="removeSingle($index)">-</button></fieldset>';
        var single = $compile(singlehtml)($scope);
        angular.element(document.getElementById('drop')).append(single);
    };
    $scope.removeSingle = function (index) {
            var myEl = angular.element(document.querySelector('#single_field'));
        myEl.remove();
    };
    $scope.selectSingle = function (field) {
      selectedField = field
      $scope.showSingle_Fieldsettings = true;
    };
});
<!DOCTYPE html>
<html ng-app="myapp">

<head>
        <script src="http://ift.tt/1YHObKi"></script>
        <script src="http://ift.tt/1mFkDBk"></script>
</head>

<body ng-controller="AddCtrl">
        <button ng-click="addNew_SingleField($index)">Single Line Text</button>
        <div id="drop"></div>

        <form ng-show="showSingle_Fieldsettings">
                <div class="form-group">
                        <label>Field Label(?)</label>
                        <br/>
                        <input ng-model="selectedField.single" class="fieldLabel">
                </div>
        </form>

</body>

</html>

Click here view more answers http://ift.tt/1YHO95a

Why Bootstrap is not working properly?

The body portion of my webpage is becoming white when path for bootstrap is being provided (I have tried with both cdn and downloaded file path) as shown

This is before giving path for bootstrap

enter image description here

This is after giving path for bootstrap

enter image description here

Here is my HTML code (until body tag)

   <!doctype html>
        <html>

        <head>

           <title>Meme Engine</title>

          <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">

           <link rel="stylesheet" type="text/css" href="css/meme.css">


         <script src="js/jquery-2.1.4.min.js"></script>

         <script src="js/bootstrap.min.js"></script>

        </head>

        <body>


           <h1 class="outer">Generate-Meme</h1>  

            <div class="outer">

            </div>

            <br>

             <div id="box1">


                   <input id="ifile" type="file" style="display:none" />
                     <input type="button" class="myButton" value="Load" onclick="$('#ifile').click();"/>

                     <br>

            </div>

           <div id="box2" style="display: none;">

                <input id="topline" placeholder="TOP LINE">
                <br><br>
                <input id="bottomline" placeholder="BOTTOM LINE">
                <br><br>

                <canvas id="c" width="0" height="0"></canvas>
                <br><br>
                <a href="#" class="buttonLink" id="downloadLink" download>Download </a> <!--download attribute http://ift.tt/1rHhbpa -->


                <br><br>
                <a href="">Make Another Meme!</a>  <!-- href="" reloads the current page -->
            </div>
            <br><br>

            <br>

</body>

Here is my CSS code

 html {
    height: 100%;
    background: red; /* For browsers that do not support gradients */    



     background: #780206; /* fallback for old browsers */
     background: -webkit-linear-gradient(to left, #780206 , #061161); /* Chrome 10-25, Safari 5.1-6 */
     background: linear-gradient(to left, #780206 , #061161); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

       }

      h1{
          color: white;
        }



        body {

            max-width: 60em;
            margin: 12px  auto;
            border: 4px dotted black;
            border-radius: 2em;
            padding: 1em;
            text-align: center;
        }
        input,button {
            font-size: 1.25em;
            padding: 0.5em;
            display: inline-block;
        }
        input[type="file"] {   /*element with specified attribute can be selected like this */
            border: 0.125em solid dodgerBlue;
            border-radius: 0.5em;



        .outer{
            margin: 5;

        padding:2.5ex;
        }

` What can be the reason ? this is only seen when I add path for bootstrap.


Click here view more answers http://ift.tt/1QS1Lvw

Turbo C - stop code re runs

I have a code below where if ran, scanf will ask for a char type value. As you can see, the code has no for loops or do while, but if a value is inserted the code re runs as long as the value is a char type. hope someone could help :)

#include <stdio.h>
main(){
char name;
clrscr();
printf("welcome who?\n->");
scanf("%s",&name);
getche();
return 0;
}


Click here view more answers http://ift.tt/1YHObtX

Dynamic Radio Button PHP

I am currently creating an online quiz. In order for me to retrieve information from the input, I think I am required to input a value for the radio button. I wish to input the values as 1 for the first, 2 for the second etc. Since i have used this echo in php, I am assuming it has to be some sort of variable?

I have tried different loop but I can't seem to get it working. Sorry if this sounds like an easy question. Any help would be appreciated!

    <!DOCTYPE html>

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <title>Online Quiz</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/styles.css">  
</head>


<body>
    <div>
        <form action="" method="post" id="quiz">
            <?php
            require'./quizData.php';
            include('Header.php');

            foreach ($quizSGHistoryQ as $questionNo => $questionInfo) {

                echo "<br>" . $questionNo . ")";

                echo $questionInfo['question'];

                echo $questionInfo['answer'] . "<br>";

                foreach ($questionInfo['options'] as $option => $desc) {






                        echo "<input type= 'radio' name = " . $questionNo  .      " >" . $desc . "<br>";


                }
            }







            include('Footer.php');
            ?>

            <input type="submit" name="submit" value="Submit">


        </form>
    </div>

    <?php
    foreach ($quizSGHistoryQ as $questionNo => $questionInfo) {

        $pickedAns = $_POST [$questionNo];


        $totalScore = 0;

        if ($pickedAns == $questionInfo['answer']) {

            $totalScore++;
        }
    }
    ?> 



</body>


Click here view more answers http://ift.tt/1mFkFsW

How to make Xcode Simulator show up on the same page of Xcode?

I am using Xcode 7.1 and when I run the simulator, it shows up in totally different window, which makes it hard to see the changes in Xcode. I wonder if there is a way to make it appears on the same window for Xcode. Thanks for the help in advance.


Click here view more answers http://ift.tt/1Sg2JAY

Compiler Error Message: CS1061 ASPX

I am trying to code a drop down list that will have an OnSelectedIndexChanged event but i can't make it work.

So here's the code on my .aspx

<asp:DropDownList ID="DDLSample" OnSelectedIndexChanged="DDLSample_SelectedIndexChanged" runat="server">
                    <asp:ListItem Text="Sample1" Value="0"></asp:ListItem>
                    <asp:ListItem Text="Sample2" Value="1"></asp:ListItem>
                    <asp:ListItem Text="Others..." Value="2"></asp:ListItem>
                </asp:DropDownList> 

and a textbox

<asp:TextBox  ID="txtOthers" runat="server" Visible ="false" CssClass="form-control" ></asp:TextBox>

What I plan to do is that when "Others..." is selected from the drop down list, it will show the Others field.

on my aspx.cs, I have this code

protected void Page_Load(object sender, EventArgs e)
    {
        DDLSample.SelectedIndexChanged += new EventHandler(DDLSample_SelectedIndexChanged);
        DDLSample.AutoPostBack = true;
    }

    void DDLSample_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DDLFindings.SelectedValue.ToString() == "2")
            txtOthers.Visible = true;
        else
            txtOthers.Visible = false;
    }

but still, I keep getting this error

CS1061: 'sample_aspx' does not contain a definition for 'DDLSample_SelectedIndexChanged' and no extension method 'DDLSample_SelectedIndexChanged' accepting a first argument of type 'sample_aspx' could be found (are you missing a using directive or an assembly reference?)


Click here view more answers http://ift.tt/1YHObtR

Search in JSON api url with ajax

I have an api URL it's output JSON, it is about daily deals like groupon.

I want to create a search form and client search in this json

Samle json url here

I'm decode JSON like that and show it but how to search in this api url i don't know.

$param = array(
    'apiKey' => 'VN43ZG2LLHKHHIU6',
    'publisherId' => 316,
    //'isPopular' => 'on',
    'p' => $sayfasi,
    'itemInPage' => $sayi
);

if(isset($tagid) && $tagid !='')
    $param['tagIds[]'] = $tagid;

if(isset($cityId) && $cityId !='')
    $param['cityId'] = $cityId;



$jsonurl     = 'http://ift.tt/1YHObtK?'.http_build_query($param);


//$json        = CurlConnect($jsonurl

$json = file_get_contents($jsonurl);

$json_output = json_decode($json);

Search form should search in deals: title, description

Sample deals json block

"deals":[  
      {  
         "id":"1041296",
         "title":"Tüm Cinemaximum'larda İndirimli Sinema Biletleri 9.50 TL'den Başlayan Fiyatlarla!",
         "description":"Cinemaximum İndirimli Bilet Fırsatı\r\nCinemaximum'larda indirimli bilet fırsatını kaçırmayın. ",
         "howToUse":null,
         "endDate":"2015-12-26 23:59:59",
         "discountPercent":"41",
         "country":"Turkey",
         "businessIds":"",
         "latLngs":"",
         "city":"",
         "provider":"Fırsat Bu Fırsat",
         "realPriceWithSymbol":"16 TL",
         "dealPriceWithSymbol":"9.50 TL",
         "showDealUrl":"http://ift.tt/1mFkFsR",
         "buyDealUrl":"http://ift.tt/1YHObtM",
         "image200_H":"http://ift.tt/1mFkDBa",
         "timeLeft":43377
      },...


Click here view more answers http://ift.tt/1Oesz6K

Show / Hide contents base on radio button selection

I am trying to toggle a content DIV base on the selection of radio buttons.

HTML for radio button.

<div class="row-fluid">
    <label class="radio">
      <input type="radio" name="account" id="yes" value="yes" checked>
      Yes, I have an existing account
    </label>
    <label class="radio">
      <input type="radio" name="account" id="no" value="no">
      No, I don't have an account
    </label>
</div>

Content DIV

<div id="account_contents">
    <p>This is account contents.......</p>  
</div>

This is how I tried it in jquery.

$('#no').bind('change',function(){
  $('#account_contents').fadeToggle(!$(this).is(':checked'));
  $('#account_contents').find("input").val("");
  $('#account_contents').find('select option:first').prop('selected',true);
});

But it doesn't work for me correctly. Here I want to show this content DIV only if user don't have an account.

Can anybody tell me how to fix this problem?


Click here view more answers http://ift.tt/1mFkFsN

Implementing step progress bar

I have the following code in my html page to implement a simple step progress bar

<ol class="progtrckr" data-progtrckr-steps="5" id="stepBar">
    <li class="progtrckr-done"><a href="documents?form" style="color: black;">Order Processing</a></li>
    <li class="progtrckr-done">Pre-Production</li>
    <li class="progtrckr-done">In Production</li>
    <li class="progtrckr-done">Shipped</li>
    <li class="progtrckr-todo">Delivered</li>
</ol>

With the following CSS

ol.progtrckr {
        margin: 0;
        padding: 0;
        list-style-type: none;
    }

ol.progtrckr li {
    display: inline-block;
    text-align: center;
    line-height: 3em;
}

ol.progtrckr[data-progtrckr-steps="2"] li { width: 49%; }
ol.progtrckr[data-progtrckr-steps="3"] li { width: 33%; }
ol.progtrckr[data-progtrckr-steps="4"] li { width: 24%; }
ol.progtrckr[data-progtrckr-steps="5"] li { width: 19%; }
ol.progtrckr[data-progtrckr-steps="6"] li { width: 16%; }
ol.progtrckr[data-progtrckr-steps="7"] li { width: 14%; }
ol.progtrckr[data-progtrckr-steps="8"] li { width: 12%; }
ol.progtrckr[data-progtrckr-steps="9"] li { width: 11%; }

ol.progtrckr li.progtrckr-done {
    color: black;
    border-bottom: 4px solid yellowgreen;
}
ol.progtrckr li.progtrckr-todo {
    color: silver; 
    border-bottom: 4px solid silver;
}

ol.progtrckr li:after {
    content: "\00a0\00a0";
}
ol.progtrckr li:before {
    position: relative;
    bottom: -2.5em;
    float: left;
    left: 50%;
    line-height: 1em;
}
ol.progtrckr li.progtrckr-done:before {
    content: "\2713";
    color: white;
    background-color: yellowgreen;
    height: 1.2em;
    width: 1.2em;
    line-height: 1.2em;
    border: none;
    border-radius: 1.2em;
}
ol.progtrckr li.progtrckr-todo:before {
    content: "\039F";
    color: silver;
    background-color: white;
    font-size: 1.5em;
    bottom: -1.6em;
}
#stepBar {
    margin-bottom: 50px;
    text-align: center;
}

How can I move the step bar only if the user has some other values saved in the database, known that I'm using gvNix


Click here view more answers http://ift.tt/1ZtSbQX

Which way is faster to copy the data from a matrix to other matrix in C/C++?

I have two matrix which are A1 and A. The matrix A1 has data. I want to copy (two cases):

  1. All data from A1 to A
  2. Copy selected row from A1 to A

I have two way to copy A1 to A for each case. It is that I will copy each element from A1 to A. Or, I will copy by using memset. Which way is more faster in C/C++. Could you see the way which uses memset and let me know if it was wrong? Thanks

***********************************************************************************/
    typedef unsigned char  U8;
    typedef unsigned int   U32;
    U8** A1;
    U8** A;
    //Alloc A1 and A matries
    int M1=32;
    int N1=64;
    int M=64;
    int N=128;
    A1= new U8*[M1]; //Max number of rows that M can achieve 
    for (U32 i = 0; i < N1; ++i)
    {
      A1[i] = new U8[N1];
      memset(A1[i],0,N1);
    }
    A= new U8*[M]; //Max number of rows that M can achieve 
    for (U32 i = 0; i < N; ++i)
    {
      A[i] = new U8[N];
      memset(A[i],0,N);
    }

    // Assume A1 is set data in here
    // Now we will copy A1 to A
    // Use first way- copy element by element
    for (U32 i = 0; i < M; ++i)
    {
      for(U32 j=0; j<N;j++)
          A[i] = A1[i];
    }
    //Use second way is memset
    for (U32 i = 0; i < M; ++i)
    {
         memcpy(A[i],A1[i],N);
    }


Click here view more answers http://ift.tt/1NPUKWa

Mongoose - Take sum of [Number] and add new property to same document

I have the following document in a Mongo database:

{
    _id: 1,
    question: "Blue or red?",
    __v: 0,
    votes: [9, 5]
}

I want to, in the back-end, get the total of votes, 14, (because 9 + 5 = 14) and append a new property on that document dynamically. So in the end, it'll look like this:

{
    _id: 1,
    question: "Blue or red?",
    __v: 0,
    votes: [9, 5],
    totalVotes: 14
}

I researched how to do this, and found words like: Aggregate, unwind, etc. I don't think those will help me because Aggregating in MongoDB is comparing the properties of documents, and I only want to modify the innards of a singular document relative to the properties of itself.

This was my "attempt" to do so:

var getTotal = function(arr){
   var total = 0;
   for(var i in arr) { total += arr[i]; }
   return total;
 };

Model.update({ $set: { totalVotes: getTotal(votes) }}, function(){
  console.log('Updated.');
});

Obviously votes is not defined, and this will result in an error. How would I tell it to get the votes from the Model, and pass it in the getTotal() function?

Here's the schema of the Model, btw:

question: {type: String, required: true},
votes: [Number],
totalVotes: Number


Click here view more answers http://ift.tt/1QS1Lvi

ASP.NET C#, menu class="active" in Site Master page

My project is an asp.net (C#). Menu buttons placed in Site Master page. I'm new on asp.net and c#. Could you help me to How I can add class="active" to menu buttons?

Ex:

<ul id="main_menu">
    <li><a href="Default.aspx">Home</a></li>
    <li>
        <a>Recipes</a>
        <ul id="recipes_menu">
            <li><a href="Recipes.aspx">Recipes 1</a></li>
            <li><a href="Recipes.aspx">Recipes 2</a></li>
            <li><a href="Recipes.aspx">Recipes 3</a></li>
            <li><a href="Recipes.aspx">Recipes 4</a></li>
            <li><a href="Recipes.aspx">Recipes 5</a></li>
            <li><a href="Recipes.aspx">Recipes 6</a></li>
            <li><a href="Recipes.aspx">Recipes 7</a></li>
            <li><a href="Recipes.aspx">Recipes 8</a></li>
            <li><a href="Recipes.aspx">Recipes 9</a></li>
            <li><a href="Recipes.aspx">Recipes 10</a></li>
        </ul>
    </li>
    <li><a href="Cooking.aspx">Cooking</a></li>
    <li><a href="Contact.aspx">Contact</a></li>
</ul>

Thank you!


Click here view more answers http://ift.tt/22sIdSa

How to give border to to current displaying border

I am using Shopify envy theme. I have multiple product images. I want to give border to thumb image which image is displaying as main image. In short the current image should have border.

Here is the example image what I want :enter image description here

Small images are multiple different thumb image. If thumb image is displaying in main big image that thumb should have border.

This is my jQuery:

$('a.image-swap').click(function() {
    var newImage = $(this).attr('href');
    $('.featured-image-div img').attr({ src: newImage });
    return false;
});


Click here view more answers http://ift.tt/1NGBD31

can any one help me on this java Questions

customer must maintain a minimum balance. If a customer’s current balance falls below the minimum balance, there is a service charge of 5 OMR for savings account and 10 OMR for current accounts. If the balance
at the end of the month is at least the minimum balance, the account receives interest as follows:  ‘savings’ accounts receive 4% interest on current balance  ‘current’ accounts with balances of up to 3000 OMR more than the minimum balance receive 3% interest on current balance; otherwise the interest is 5% on current balance. Write and execute a Java program that reads a customer’s account number (int type), account type (char type: s or S for savings, c or C for current), minimum balance that the account should maintain, and current balance (both of type double). The program must use switch-case construct for calculations and then output the account number, account type, final balance, and print appropriate messages.
final balance is calculated as per the conditions given above (by adding the calculated interest amount to the current balance). Test you program by running it five times, using the following input data samples and print the output (final balance) for each case: 77728 S 1000 2700 65624 C 1500 7869 79387 S 1000 800 99532 C 2000 3000 23521 C 1000 750 Note: Assume that OMR refers to Omani Rials


Click here view more answers http://ift.tt/1kkobqQ

How to use singleton class?

I want to know how can we declare variables in singleton class and access them in different activities?? If we have edit texts how can we set the value of edit text to the singletons variables? and if we want to show the values in the text views how can we show them? I am new in android can anyone help please..


Click here view more answers http://ift.tt/1OetdBf

Which should I learn Bootstrap or w3.css?

Recently I went w3 School to learn bootstrap. But I noticed they have introduced W3.CSS , and both are responsive css framework and both are now continued by W3school. So which should learn? Which will have advantage in future. Also if you give some feature comparison it will be helpful. Thank you.


Click here view more answers http://ift.tt/1IvhdLh

numpy.loadtxt loading floats from single line file when ndmin=1

Problem: I have a text file containing several numbers. I am trying to grab some of them and load them into arrays. I would like arrays, even when only 1 line is present in the file. I have an issue when there is a single line only. The values are loading as floats and are not loaded into arrays.

Tried: From the numpy documentation I would expect arrays of length 1 for the single line text file when using ndmin=1. However, I am still getting a series of floats, see below:

>>> ra_deg,dec_deg,l_deg,b_deg=np.loadtxt(args.infile,ndmin=1,usecols=[0,1,2,3],unpack=True)
>>> ra_deg
127.55905
>>> np.__version__
'1.8.1'

Expected:

>>> ra_deg
array([127.55905])

Example args.infile input:

127.55905 +00.00000 224.77661 +21.83227

I am not sure if this is my error, or there is something up with numpy? Any advice before opening a numpy issue would be great, thanks.


Click here view more answers http://ift.tt/1IvhbmA

How to run OpenCV Videocapture in a separate posix thread in C++ for cross-platform?

In my code, I want to run a Videocapture in a separate pthread continuously, while the main thread will act as a socket server to communicate to any client (or vice versa).

When the client communicates to the server, the server will immediately send the latest Videocapture frame to the client and close the connection and again wait for another connection.

I am currently using OpenCV 2.3.0 in mingw32 environment.

After looking some possible solutions on StackOverflow, I tried following them, but, however may I place the OpenCV variables either locally or globally or swapping the threads i.e. keeping Videocapture thread in main thread or in the 2nd thread, the program just hangs silently at the mutex locked area of the VideoCapture thread when the client gets connected.

I suppose this is happening when the server thread starts locking the mutex after connecting to a client.

Any reasoning or possible solution will be highly appreciated. Also, I am using prebuilt OpenCV version 2.3.0 and I need the code to be cross platform. In any case, if it points to a bug, I can obviously switch to some other version.


Server code

mynet.h

#ifndef __MYNET__
#define __MYNET__
#ifdef _WIN32
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501  /* Windows XP. */
#endif
#include <winsock2.h>
#include <Ws2tcpip.h>
#else
/* Assume that any non-Windows platform uses POSIX-style sockets instead. */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>  /* Needed for getaddrinfo() and freeaddrinfo() */
#include <unistd.h> /* Needed for close() */
#endif

int sockInit(void)
{
#ifdef _WIN32
    WSADATA wsa_data;
    return WSAStartup(MAKEWORD(1,1), &wsa_data);
#else
    return 0;
#endif
}

int sockQuit(void)
{
#ifdef _WIN32
    return WSACleanup();
#else
    return 0;
#endif
}

/* Note: For POSIX, typedef SOCKET as an int. */
#ifndef _WIN32
typedef int SOCKET;
#else
typedef unsigned int SOCKET;
#endif

int sockClose(SOCKET sock)
{
    int status = 0;
#ifdef _WIN32
    status = shutdown(sock, SD_BOTH);
    if (status == 0) { status = closesocket(sock); }
#else
    status = shutdown(sock, SHUT_RDWR);
    if (status == 0) { status = close(sock); }
#endif
    return status;
}


#if(defined(_WIN32) || defined(WIN32))
#include <windows.h>
#define mysleep(x) Sleep((x))
#else
#include <unistd.h>
#define mysleep(x) usleep((x)*1000)
#endif

#endif

netserver.cpp

#define _GLIBCXX_USE_CXX11_ABI 0
#undef _GLIBCXX_DEBUG
#include "../mynet.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <pthread.h>

using namespace cv;
Mat frame(120, 160, CV_8UC3);;
pthread_mutex_t mutex;
pthread_t thread;

void *myfunc(void *threadid)
{
    int n;
    int listenfd = 0,connfd = 0;
    struct sockaddr_in serv_addr;
    unsigned char sendBuff[160*120*3];
    Mat hereframe;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    printf("socket retrieve success\n");

    memset(&serv_addr, '0', sizeof(serv_addr));
    memset(sendBuff, '0', sizeof(sendBuff));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(5000);
    bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr));
    if(listen(listenfd, 10) == -1)
    {
        printf("Failed to listen\n");
    }
    else
    {
        connfd = accept(listenfd, (struct sockaddr*)NULL,NULL);  // accept awaiting request
        if(connfd<=0)  printf("Something went wrong with write()! %s\n", strerror(errno));
        else
        {
            while(1)
            {
                printf("Got client...\n");
                pthread_mutex_lock (&mutex);
                printf("Copying data...\n");
                frame.copyTo(hereframe);
                pthread_mutex_unlock (&mutex);
                printf("Hereframe size: %dX%d\n", hereframe.rows, hereframe.cols);
                memcpy(sendBuff, hereframe.data, 120*160*3);
                printf("Sending data...\n");
                n = send(connfd, (char*)sendBuff, 120*160*3,0);
                if(n<0)  printf("Something went wrong with write()! %s\n", strerror(errno));
                printf("Closing client after writing %d bytes...\n", n);
                printf("Closed...\n");
                mysleep(40);
                printf("Restartng data...\n");
            }
            sockClose(connfd);
        }
    }
    sockQuit();

    pthread_exit(NULL);
}

int main(void)
{
    //cvNamedWindow("Sisplay", CV_WINDOW_AUTOSIZE);
    sockInit();
    pthread_mutex_init(&mutex,NULL);
    VideoCapture cap;
    Mat hereframe1;
    cap.open(0);
    cap.set( CV_CAP_PROP_FRAME_WIDTH, 160 );
    cap.set( CV_CAP_PROP_FRAME_HEIGHT, 120 );

    if( !cap.isOpened()) printf("Fukced up\n");
    int rc;
    long t;
    rc = pthread_create(&thread, NULL, myfunc, (void *)t);
    if (rc)
    {
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
    }

    for(;;)
    {
        cap >> hereframe1;
        //     printf("Video size: %dX%d\n", hereframe1.rows, hereframe1.cols);

        pthread_mutex_lock(&mutex);
        hereframe1.copyTo(frame); /* hangs here*/
        pthread_mutex_unlock(&mutex);
        // cvtColor(frame, gray, CV_BGR2GRAY);

        Scalar tempVal = mean(hereframe1);
        //  printf("Mean = %f\n", tempVal.val[0]);
        mysleep(30);
        //if(waitKey(30)=='q') break;
        // std::swap(prevgray, gray);
    }
    char *b;
    pthread_join(thread,(void**)&b);
    return 0;
}


Client code

receiver.cpp

#define _GLIBCXX_USE_CXX11_ABI 0
#include "../mynet.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>

using namespace cv;

int main(int argc, char *argv[])
{
    int sockfd = 0,n = 0;
    unsigned char recvBuff[120*160*3];
    struct sockaddr_in serv_addr;
    sockInit();
    memset(recvBuff, '0',sizeof(recvBuff));
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
    {
        printf("\n Error : Could not create socket \n");
        return 1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(5000);
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);

    if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
    {
        printf("\n Error : Connect Failed \n");
        return 1;
    }
    printf("Connected to server...\n");
    Mat frame(120, 160, CV_8UC3);
    int csz = 0;
    cvNamedWindow("Display", CV_WINDOW_AUTOSIZE);
    printf("OK here 0\n");
    for(;;)
    {
        csz = 0;
        while((n = recv(sockfd, (char*)recvBuff, sizeof(recvBuff), 0)) > 0)
        {
            printf("OK here 2\n");

            printf("Read %d bytes...\n", n);
            csz += n;
            if(csz<=120*160*3)
            {
                memcpy(frame.data+(csz-n), recvBuff, n);
            }
            if(csz>= 120*160*3) break;
        }
        printf("OK here 3\n");

        printf("Got data of size %d bytes...\n", csz);
        imshow("Display", frame);
        if(csz < 120*160*3)
        {
            printf("\n Read Error \n");
        }
        if(waitKey(30)=='q') break;
        // std::swap(prevgray, gray);
    }
    sockClose(sockfd);

    sockQuit();
    return 0;
}


Click here view more answers http://ift.tt/1Ivhb6k