mercredi 5 août 2015

Is it possible to add include path to visual studio from an FTP address?


We have a bunch of libraries and projects like OpenCV, Boost and etc. and for that we have a sharing space in our local network. Everyone can access this libraries using ftp protocol and probably by a username and password. I want to know if I can set visual studio additional include or library path from ftp address? For example for adding include file of opencv you have to add $(OPENCV_DIR)\include which $(OPENCV_DIR) address from your hard drive(c:\opencv\build). I want to address it from ftp such as (ftp://ipaddres/opencv/build). I want to know if it possible or not? and if you can give me another options for my purpose?



via Chebli Mohamed

C String while using Bison/Flex


I'm working on a bison/flex project where I am using string but I'm not able to use well methods like strlen() (same for strcmp etc.)

To better explain I wrote a new short .l and .y files:

%{
#include <string>
#include "test.tab.h"
void yyerror(char*);
extern void printVars();
int yyparse(void);
char linebuf[500];


%}

%option yylineno

blanks          [ \t\n]+
text            [^<>]+


%%

\n.*  { strncpy(linebuf, yytext+1, sizeof(linebuf)); /* save the next line */
        yyless(1);      /* give back all but the \n to rescan */
       }

{blanks}        { /* ignore */ };

"<test>"        return(START);
"</test>"       return(STOP);
"<string>"      return(BEGIN_STRING);
"</string>"     return(END_STRING);
"<num>"         return(BEGIN_NUM);
"</num>"        return(END_NUM);

{text}          { yylval.str_val=strdup(yytext);
                  return(IDENTIFIER);
                }

.               return yytext[0];

%%


void yyerror(char *s){ 
    printf("--------- ERROR ---------\n");
    printf("%d: %s at %s in this line:\n%s\n", yylineno, s, yytext, linebuf);
    }

int yywrap (void){
    printf("--------- EOF ---------\n");
    }

int main(int num_args, char** args){
    if(num_args != 2) {printf("usage: ./parser filename\n"); exit(0);}
    FILE* file = fopen(args[1],"r");
    if(file == NULL) {printf("couldn't open %s\n",args[1]); exit(0);}
    yyin = file;
    yyparse();
    fclose(file);

    printVars();
}

And

%{
#include <stdio.h>
#include <string>
#define MAX_VAR     10

using namespace std;
extern int yylex();
extern void yyerror(char*);
void printVars();

string data_str[MAX_VAR];
string data_int[MAX_VAR];
int num_data_str = 0;
int num_data_int = 0;

%}



//Symbols
%union
{
    char *str_val;
};

%token START
%token STOP
%token BEGIN_NUM
%token END_NUM
%token BEGIN_STRING
%token END_STRING

%token <str_val>    IDENTIFIER

%start MyTest

%%

MyTest:
    START Block STOP
    ;

Block:
    /* empty */
    | Block 
      BEGIN_STRING IDENTIFIER END_STRING
      { if(num_data_str<MAX_VAR){
            data_str[num_data_str]=$3;
            num_data_str++;
        }
        else printf("string: %s not saved!\n", $3); }
    | Block
      BEGIN_NUM IDENTIFIER END_NUM
      { if(num_data_int<MAX_VAR){
            data_int[num_data_int]=$3;
            num_data_int++; //saved
        }
        else printf("integer: %s not saved!\n", $3); }
    ;

%%

void printVars(){
    printf("Printing Strings:\n");
    for(int i=0;i<num_data_str;i++) printf("-- %s of length %d\n",data_str[i].c_str(),strlen(data_str[i]));
    printf("Printing Integers:\n");
    for(int i=0;i<num_data_int;i++) printf("-- %s \n",data_int[i].c_str());

}

As you can see I have

#include <string>
using namespace std;

In this way I have the following error while compiling:

test.tab.c: In function ‘int yyparse()’:
test.tab.c:1289:35: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
       yyerror (YY_("syntax error"));
                                   ^
test.tab.c:1433:35: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   yyerror (YY_("memory exhausted"));
                                   ^
test.y: In function ‘void printVars()’:
test.y:66:100: error: ‘strlen’ was not declared in this scope
  for(int i=0;i<num_data_str;i++) printf("-- %s of length %d\n",data_str[i].c_str(),strlen(data_str[i]));



via Chebli Mohamed

cutting first string from second string and show remaining characters


I want to code a program in which we take two strings separated by space as an input from user. Then the first string will be cut from second one, if resultant again have first string then again cut it from that string until there is no first string in second string as a result. The output will be the remaining characters in separated line and at the end a number that shows the quantity of those characters.

#include<iostream>
using namespace std;


int main() {
    string ch1, ch2, ch3;
    cout << " Enter  two strings values...separated by space..." << endl;
    cin >> ch1 >> ch2;
    //cout<<aa<<" 2nd  "<<bb<<endl;
    // ch1[]={"ab"},ch2[]={"caabbefcdeab"},ch3[50];
    int a = 0, b = 0, c;
    string s, t, r;
    int check = true;

    for (int i = 0; ch2[i] != '\0'; i++)
    {
        int w = i;
        check = 1;
        b = 0;
        if (ch1[0] == ch2[i])
        {
            for (int p = 0; ch1[p] != '\0' && check == 1; p++)
            {
                if (ch1[p] == ch2[w])
                {
                    check = 1;
                    w = w + 1;
                }
            }
            if (check == 1)
            {
                for (int e = i; e<w; e++)
                {
                    ch2[e] = '\0';
                    ch2[e] = '~';
                }
                i = -1;
                for (int l = 0; ch2[l] != '\0'; l++)
                {
                    ch3[l] = '\0';
                    if (ch2[l] != '~')
                    {
                        // cout<<" ch2 "<<ch2[l]<<endl;
                        ch3[b] = ch2[l];

                        // cout<<" ch3 "<<b<<" contains.."<<ch3[b]<<endl;
                        b = b + 1;
                    }
                }
                for (int l = 0; ch2[l] != '\0'; l++)
                {
                    ch2[l] = '\0';
                    ch2[l] = ch3[l];
                }
            }
        }
    }
    for (int u = 0; ch2[u] != '\0'; u++)
    {
        cout << ch2[u] << endl;
        a = a + 1;
        //  cout<<" ch3 "<<u<<" contains "<<ch3[u]<<endl;
    }
    cout << a << endl;

    system("pause");
    return 0;
}

Sample input:

cde ccdedefcde

Sample output:

f
1

But my output is:

d
e
f
3



via Chebli Mohamed

I use CRegKey to open some, but this m_hKey != 0


I want to get JDk path by the Registry, this path is HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit\1.8, when i use CRegKey.open(HKEY_LOCAL_MACHINE, L"SOFTWARE\JavaSoft\Java Development Kit\1.8"), it throw expression m_hKey != 0. so what's happend ? how to fix this bug? Here is my code:

    // Get Java environment variable install path
CRegKey key;
wchar_t JavaHome[40];
ULONG szJavaHome = 40;
bool res = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\JavaSoft\\Java Development Kit\\1.8");
if (key.m_hKey == 0)
    MessageBox(L"11");
restrul = key.QueryStringValue(L"JavaHome", JavaHome, &szJavaHome);

Thanks ~



via Chebli Mohamed

std::mutex missing when building Qt app with MXE gcc


I'm attempting to get a Qt application to build from the command line under linux targetted for windows. I've used mxe to build a toolchain for targetting windows but my build fails whinging about various thread related bits. mxe built with winpthreads and I know the Qt project will build on windows itself from inside of creator, using the pre-packaged mingw compiler. I'm successfully building using my ARM Linux cross compiler, so I just want to get windows done the same. I'm trying to get a one line build on a build server or from Jenkins for all my targets.

I'm guessing I'm missing something that I need to pass to mxe when doing the cross toolchain build or alternatively missing something I need to pass to qmake to for this build to succeed.



via Chebli Mohamed

MFC - How to draw pixel waves inside a rectangle


I am new to MFC trying to learn from the scratch.

I am trying to create a small dialog based application in VS2012 - MFC.

On the dialog window i have drawn a rectangle (in OnPaint event) like this.

CPaintDC dc(this);
CRect background1(10,10,208,92);
dc.Rectangle(10,10,208,92);

Then i filled the bacground with some color. Like this.

   CBrush brush1;
   brush1.CreateSolidBrush(RGB(2,3,4));
   dc.FillRect(background1,&brush1);

Now i wanted to draw waves in form of pixels continuously inside the rectangle.

As of now what i have done is,

bool top = false;
    for(i=10,j=92;i<200 && j>10;)
    {
        pDC->SetPixel(i,j,NewColor);
        Sleep(10);

        if(!top)
            j-=1;
        else
            j+=1;
        if(j%4==0)
        {
            i+=1;

        }
        if(j==12)
            top=true;
        if(j==90)
            top = false;

    }

I am just drawing the pixels straightaway on the window, but within the dimensions where the rectangle lies. And the waves stop as it reaches the right dimension of the rect. But i feel thats not the right way to do it.

I want to draw the waves inside the rectangle and also continuosly, like when it reacahes the right end it should move left and it should be continuous.

Is there any proper way in MFC to draw something inside a rectangle (technically inside another object)?

Please help me out.



via Chebli Mohamed

Optionally safety-checked cast on possibly incomplete type


Pursuant to a simple, intrusively reference-counted object system, I have a template<typename T> class Handle, which is meant to be instantiated with a subclass of CountedBase. Handle<T> holds a pointer to a T, and its destructor calls DecRef (defined in CountedBase) on that pointer.

Normally, this would cause problems when trying to limit header dependencies by using forward declarations:

#include "Handle.h"

class Foo; // forward declaration

struct MyStruct {
    Handle<Foo> foo; // This is okay, but...
};

void Bar() {
    MyStruct ms;
}   // ...there's an error here, as the implicit ~MyStruct calls
    // Handle<Foo>::~Handle(), which wants Foo to be a complete
    // type so it can call Foo::DecRef(). To solve this, I have
    // to #include the definition of Foo.

As a solution, I rewrote Handle<T>::~Handle() as follows:

template<typename T>
Handle<T>::~Handle() {
    reinterpret_cast<CountedBase*>(m_ptr)->DecRef();
}

Note that I'm using reinterpret_cast here instead of static_cast, since reinterpret_cast doesn't require the definition of T to be complete. Of course, it also won't perform pointer adjustment for me... but as long as I'm careful with layouts (T must have CountedBase as its leftmost ancestor, must not inherit from it virtually, and on a couple of unusual platforms, some extra vtable magic is necessary), it's safe.

What would be really nice, though, would be if I could get that extra layer of static_cast safety where possible. In practice, the definition of T is usually complete at the point where Handle::~Handle is instantiated, making it a perfect moment to double-check that T actually inherits from CountedBase. If it's incomplete, there's not much I can do... but if it's complete, a sanity check would be good.

Which brings us, finally, to my question: Is there any way to do a compile-time check that T inherits from CountedBase which will not cause a (spurious) error when T is not complete?

[Usual disclaimer: I'm aware that there are potentially unsafe and/or UB aspects to the use of incomplete types in this way. Nevertheless, after a great deal of cross-platform testing and profiling, I've determined that this is the most practical approach given certain unique aspects of my use case. I'm interested in the compile-time checking question, not a general code review.]



via Chebli Mohamed

Assignment between union members


Is this code well-defined?

int main()    
{    
    union     
    {    
        int i;    
        float f;    
    } u;    

    u.f = 5.0;    
    u.i = u.f;       // ?????
}    

It accesses two different union members in one expression so I am wondering if it falls foul of the [class.union]/1 provisions about active member of a union.

The C++ Standard seems to underspecify which operations change the active member for builtin types, and what happens if an inactive member is read or written.



via Chebli Mohamed

How To Start another app while running a program in Turbo C++


I was making a program that would help me keep track of all the other programs I was making.In the program I would hit the key corresponding to a particular app and the the app should open up.

But I am not able to find a way to do that.{ system(D:\\APPS\\calc.exe) is not working}. I Need Help for this :) Both are Dos Apps and are running on DosBox Emulator. (Drive D: is Mounted-No problem about that)

No Error.When I press the key to launch that app in my program, nothing happens :(



via Chebli Mohamed

How Can I Use a Regex on the Reverse of a string?


I want to use a regex on the reverse of a string.

I can do the following but all my sub_matches are reversed:

string foo("lorem ipsum");
match_results<string::reverse_iterator> sm;

if (regex_match(foo.rbegin(), foo.rend(), sm, regex("(\\w+)\\s+(\\w+)"))) {
    cout << sm[1] << ' ' << sm[2] << endl;
}
else {
    cout << "bad\n";
}

[Live example]

What I want is to get out:

ipsum lorem

Is there any provision for getting the sub-matches that are not reversed? That is, any provision beyond reversing the strings after they're matched like this:

string first(sm[1]);
string second(sm[2]);

reverse(first.begin(), first.end());
reverse(second.begin(), second.end());

cout << first << ' ' << second << endl;

EDIT:

It has been suggested that I update the question to clarify what I want:

Running the regex backwards on the string is not about reversing the order that the matches are found in. The regex is far more complex that would be valuable to post here, but running it backwards saves me from needing a look ahead. This question is about the handling of sub-matches obtained from a match_results<string::reverse_iterator>. I need to be able to get them out as they were in the input, here foo. I don't want to have to construct a temporary string and run reverse on it for each sub-match. How can I avoid doing this.



via Chebli Mohamed

flushing stdout of c executable


I've got program that crashes after several printing command lines. however, I cannot see the output even though those prints already performed. this lead me to the assumption that there's a buffer that dump output after accumulating enough data, and if program crashed unexpectedly, the buffer disappear.

For debugging my crash, I'd like to set this buffer to zero and avoid performance degradation, so i can see the prints prior to the crash event.

thanks



via Chebli Mohamed

CLion does not recognize SDL2_image


I have got SDL2_image library installed on /usr/include/SDL2 (in this directory I can find SDL_image.h).

When I compile with CLion all works fine but, in the editor, either include and functions of SDL2_image librarie appear with error (this library is found by the compiler but It is not found by the editor).

This is my CMake:

cmake_minimum_required(VERSION 3.2)
project(sdl)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp)
add_executable(sdl ${SOURCE_FILES} Game.cpp Game.h)

INCLUDE(FindPkgConfig)

PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED SDL2_image>=2.0.0)

INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${SDL2_LIBRARIES}  ${SDL2IMAGE_LIBRARIES})

add_custom_command(TARGET sdl POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
    ${CMAKE_SOURCE_DIR}/assets
    $<TARGET_FILE_DIR:sdl>/assets)

What is the problem?



via Chebli Mohamed

Exception not being caught at catch site


I have a class Bar which inherits from std::exception.

I'm throwing that exception

throw new Bar(foo)

where foo is a parameter which we can consider arbitrary.

But it's not being caught on my catch site:

} catch (const Bar& ex){

In fact, the only thing that catches it is (...).

What is going on? I've been through all my compiler settings that I think are relevant. Been playing with this since 5am! Help!



via Chebli Mohamed

OpenCV installation problems for Python


I am trying to install OpenCV on my Ubuntu system. I followed the steps of this page. I am able to run the demos for C/C++ etc. But when I try to run the python demos, I get an ImportError: No module named cv2

Here is more info :

python --version Python 2.7.8 :: Anaconda 2.1.0 (64-bit)

python -c 'import sys; print sys.path' ['', '/home/radar/anaconda/lib/python2.7/site-packages/pydy-0.2.1-py2.7.egg', '/home/radar', '/home/radar/opencv-2.4.9/modules/python/src2', '/home/radar/anaconda/lib/python27.zip', '/home/radar/anaconda/lib/python2.7', '/home/radar/anaconda/lib/python2.7/plat-linux2', '/home/radar/anaconda/lib/python2.7/lib-tk', '/home/radar/anaconda/lib/python2.7/lib-old', '/home/radar/anaconda/lib/python2.7/lib-dynload', '/home/radar/anaconda/lib/python2.7/site-packages', '/home/radar/anaconda/lib/python2.7/site-packages/PIL', '/home/radar/anaconda/lib/python2.7/site-packages/Sphinx-1.2.3-py2.7.egg', '/home/radar/anaconda/lib/python2.7/site-packages/runipy-0.1.1-py2.7.egg', '/home/radar/anaconda/lib/python2.7/site-packages/setuptools-5.8-py2.7.egg']



via Chebli Mohamed

Socket is open after process, that opened it finished


After closing client socket on sever side and exit application, socket still open for some time.

I can see it via netstat

Every 0.1s: netstat -tuplna  | grep 6676    
tcp        0      0 127.0.0.1:6676          127.0.0.1:36065         TIME_WAIT   -

I use log4cxx logging and telnet appender. log4cxx use apr sockets. Socket::close() method looks like that:

void Socket::close() {
    if (socket != 0) {
        apr_status_t status = apr_socket_close(socket);
        if (status != APR_SUCCESS) {
            throw SocketException(status);
        }        
        socket = 0;
    }
}

And it's successfully processed. But after program is finished I can see opened socket via netstat, and if it starts again log4cxx unable to open 6676 port, because it is busy. I tries to modify log4cxx. Shutdown socket before close:

void Socket::close() {
    if (socket != 0) {
        apr_status_t shutdown_status = apr_socket_shutdown(socket, APR_SHUTDOWN_READWRITE);
        printf("Socket::close shutdown_status %d\n", shutdown_status);
        if (shutdown_status != APR_SUCCESS) {
            printf("Socket::close WTF %d\n", shutdown_status != APR_SUCCESS);
            throw SocketException(shutdown_status);
        }
        apr_status_t close_status = apr_socket_close(socket);
        printf("Socket::close close_status %d\n", close_status);
        if (close_status != APR_SUCCESS) {
            printf("Socket::close WTF %d\n", close_status != APR_SUCCESS);
            throw SocketException(close_status);
        }
        socket = 0;
    }
}

But it didn't helped, bug still reproduced.



via Chebli Mohamed

Build project that uses qt 4.8.5 in vs 2013?


Is it possible to build project that uses qt 4.8.5 in vs 2013? I cant find qt Add In for qt 4.8.5 and vs 2013.



via Chebli Mohamed

How to make g++ force me to adhere to C++ standard


I am trying to learn C++ having no previous experience with it or C, and I see that some training materials are sometimes trying to teach me C coding instead of C++.

As I don't have enough knowledge to discern if the books are trying to teach me proper C++ or not, I thought I could set some parameter on g++ compiler to save me this problem. So here my question is:

How can I set the g++ compiler in Windows so that he won't compile if what I am writing is not pure C++ standard?

Many thanks in advance



via Chebli Mohamed

I want to customize mouse pointer(include changing text in file)


I want to monitor specific equipment. so I made the specific value of the system performance remain at text file. so Text file is changing realtime. so I want to make mouse pointer display very tiny value at text file. Is it available? Can you let me know useful api or language(c++,vb,c#,java)?



via Chebli Mohamed

Qt QSslSocket "The certificate is self-signed, and untrusted"


i want to connect server with QSslSocket and on server i get soketSslError "The certificate is self-signed, and untrusted" , but i dont understand why i have this error.

On first step was generated file for server and client with openssl

$openssl req -new -newkey rsa:1024 -keyout ca.key -x509 -days 500 -out ca.crt
$openssl req -new -newkey rsa:1024 -keyout client01.key -out client01.csr
$openssl ca -config ca.config -in  client01.csr -out client01.crt -batch

in c++ server / client

On server:

start server

if (listen(QHostAddress::Any,this->connectingPort)) {
        std::cout<<"Server start on port: "<<this->connectingPort<<std::endl;
        return true;
    } else {
        std::cout<<"Cant start server. "<<errorString().toStdString().c_str()<<std::endl;
        return false;
    }

incomingConnection

    QFile keyFile("ca.key");
    if (!keyFile.open(QIODevice::ReadOnly)) {
        delete this->sslSocket;
        qDebug()<<"Cant open file: "<<keyFile.fileName();
        return false;
    }
    QByteArray pasp ="qwerty";
    QSslKey key(keyFile.readAll(),QSsl::Rsa,QSsl::Pem,QSsl::PrivateKey,pasp);
    if (key.isNull()) {
        delete this->sslSocket;
        qDebug()<<"key in file "<<keyFile.fileName()<<" is empty";
        return false;
    }
    keyFile.close();

    this->sslSocket->setPrivateKey(key);
    this->sslSocket->setPeerVerifyMode(QSslSocket::VerifyPeer);
    this->sslSocket->setLocalCertificate("ca.crt");
    this->sslSocket->startServerEncryption();

on client side:

this->sslSocket->setPeerVerifyMode(QSslSocket::VerifyPeer);


QFile keyFile("client01.key");

if (!keyFile.open(QIODevice::ReadOnly)) {
    delete this->sslSocket;
    qDebug()<<"Cant open file: "<<keyFile.fileName();
    return ;
}
QByteArray pasp ="qwerty";
QSslKey key(keyFile.readAll(),QSsl::Rsa,QSsl::Pem,QSsl::PrivateKey,pasp);
if (key.isNull()) {
    delete this->sslSocket;
    qDebug()<<"key in file "<<keyFile.fileName()<<" is empty";
    return ;
}
keyFile.close();

this->sslSocket->setPrivateKey(key);

this->sslSocket->setLocalCertificate("client01.crt");

this->sslSocket->connectToHostEncrypted("192.168.0.10",1258);

if (!this->sslSocket->waitForEncrypted()) {
    qDebug()<<"error: "<<sslSocket->errorString();
}

and when i connecting from client i get on server error

soket ssl error
"The certificate is self-signed, and untrusted" 
"The certificate is self-signed, and untrusted" 
socketError:  QAbstractSocket::SocketError( 13 ) 

any idea what i do wrong?



via Chebli Mohamed

forward declaration of 'const class LHContactInfo' error when try to access it property


I have two c++ class bellow. I want get LHContactInfo property from LHSceneSubclass but I can get nothing.So How can I do with this?

#ifndef __LEVELHELPER_API_CONTACT_INFO_H__
#define __LEVELHELPER_API_CONTACT_INFO_H__

#include "LHConfig.h"
#if LH_USE_BOX2D

#include "cocos2d.h"

class b2Contact;

using namespace cocos2d;

class LHContactInfo
{
public:
    
    LHContactInfo();
    virtual ~LHContactInfo();
    
    Node*       nodeA;
    Node*       nodeB;
    std::string nodeAShapeName;
    std::string nodeBShapeName;
    int         nodeAShapeID;
    int         nodeBShapeID;
    
    Point       contactPoint;
    float       impulse;
    
    b2Contact*  box2dContact;
};

#endif

#endif //__LEVELHELPER_API_CONTACT_INFO_H__


#include "LHContactInfo.h"

#if LH_USE_BOX2D

#include "Box2d/Box2d.h"

LHContactInfo::LHContactInfo(){
    nodeA = NULL;
    nodeB = NULL;
    box2dContact = NULL;
}
LHContactInfo::~LHContactInfo(){
    nodeA = NULL;
    nodeB = NULL;
    box2dContact = NULL;
}

#endif
#ifndef __LH_SCENE_SUBCLASS_H__
#define __LH_SCENE_SUBCLASS_H__

#include "cocos2d.h"
#include "LevelHelper2API.h"

class LHContactInfo;
class LHSceneSubclass : public LHScene
{
public:
    static cocos2d::Scene* createScene();

    LHSceneSubclass();
    virtual ~LHSceneSubclass();
    
    bool initWithContentOfFile(const std::string& plistLevelFile);
    virtual bool shouldDisableContactBetweenNodes(Node* nodeA, Node* nodeB);
    virtual void didBeginContact(const LHContactInfo& contact);
    virtual void didEndContact(const LHContactInfo& contact);
};

#endif // __LH_SCENE_SUBCLASS_H__


//file.cpp

void LHSceneSubclass::didBeginContact(const LHContactInfo& contact){
        if(contact.nodeA->getName() == "box1"){// error invalid use of incomplete type 'const class 
 LHContactInfo'

        }
}
void LHSceneSubclass::didEndContact(const LHContactInfo& contact){
    CCLOG("DIDENDCONTACT...\n");
}

I want to do like contact.nodeA from LHContactInfo in didBeginContact function but compile error ->error invalid use of incomplete type 'const class LHContactInfo'

Note:: - Compile with android NDK 10c



via Chebli Mohamed

Query total CPU usage of all instances of a process on Linux OS


I have a python server that forks itself once it receives a request. The python service has several C++ .so objects it can call into, as well as the python process itself.

My question is, in any one of these processes, I would like to be able to see how much CPU all instances of this server are currently using. So lets say I have foo.py, I want to see how much CPU all instances of foo.py are currently using. For example, foo.py(1) is using 200% cpu, foo.py(2) is using 300%, and foo.py(3) is using 50%, id like to arrive at 550%.

The only way I can think of doing this myself is getting the PID of every process and scanning through the /proc filesystem. Is there a more general way available within C/Python/POSIX for such an operation?

Thank you!



via Chebli Mohamed

QRegExp weird behaviour in for loop


QList<QRegExp> ignores;
ignores.append(QRegExp("*", Qt::CaseSensitive, QRegExp::Wildcard));
QStringList l;
l.append("sau");
l.append("bär");
for (const QString& s : l)
    //for (QList<QRegExp>::iterator i = ignores.begin(); i != ignores.end(); ++i)
    //for (QRegExp& ignore : ignores)
    for (QRegExp ignore : ignores)
        if(ignore.exactMatch(s))
            continue;

If I test this code only the third for loop matches. The former two versions do not match. I know that the working version of the rangebased for-loops makes a copy of the object, but why does a reference not match?



via Chebli Mohamed

Dynamically executing and terminating external programs with C++


I need to execute processes with still being in control of each process. I want to create a class which stores the threads or pids or what ever is necessary to do so.

I currently have a program which executes one external application with the C function execvp and also loads the environment from a shell script. So my current program is blocking. But I need to be able to keep it freely running and only by time I terminate a currently running or start a new external application.

My current approach would be to create a thread, which uses the execve function. But then the thread would be blocking as far as I can see.

The code which might be in the thread (with variables then):

char *argv[] = { "/bin/bash", "-c", "myApplication", 0 };
execve(argv[0], &argv[0], environment.data());

The applications called are probably not fixed in the code their names will be given by an external setup file, including parameters.

Now my actual question, is there a better way to "manage" external applications like that in c++? Some ready solution (class, library)? And if not how do I terminate the thread if this is the actual way. Using the terminate call is said to be bad practice, that's what I often read.

I hope this is now specific enough for the forum, because I do not know how to get more specific anymore. If you need more hints what I want to create here, feel free to ask in the comments.

Update:

to DBus & others:

Additional information I do not wrote all of the processes I want to start! So it will be used to start 3rd party applications, which even if I have the code, do not want to change.



via Chebli Mohamed

Redirect IP-packets to my Application and then send them forward


I want to process IP-packets in my app like encrypting them, remove "bad" ones etc if they match some rule (say for example destination ip) and then send to destination. I think I can use for that purpose REDIRECT of iptables. I know that after forwarding packets to my app the original destination address will be overwritten but there is a solution:

iptables overrites the original destination address but it remembers the old one. The application code can then fetch it by asking for a special socket option, SO_ORIGINAL_DST

static int getdestaddr_iptables(int fd, const struct sockaddr_in *client, const struct sockaddr_in *bindaddr, struct sockaddr_in *destaddr)
{
        socklen_t socklen = sizeof(*destaddr);
        int error;

        error = getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, destaddr, &socklen);
        if (error) {
                log_errno(LOG_WARNING, "getsockopt");
                return -1;
        }
        return 0;
}

solution taken from here

For this purpose I also configured IPv4 forwarding by doing this:

sysctl -w net.ipv4.ip_forward=1

But then by trying to set iptable's rule, I've got an error

My rule is: iptables -t nat -A OUTPUT -p ip -j REDIRECT --to-port 666

Error: iptables v1.4.21: Need TCP, UDP, SCTP or DCCP with port specification1

I'm really newbie in iptables and in such theme in general. Can somebody tell me what I doing wrong? Why it can't do redirect with IP? And is my idea correct? I know also about divert-sockets, but they don't support fragmentation.

UPD1 Let me get straight about my problem: I want my device which is connected to internet be kind of gateway for incoming/outgoing connections. And I want to process those packets with help of my app. Some packets I will modify if they match some rule, other - just send forward without any modifications. And the laptop is "getting the internet" with help of that device



via Chebli Mohamed

Is there a way of examining the message queue of a thread other than the one calling FindWindow+GetMessage? I mean different apps checking each other's court? Particularly from a C++ console application (not using GDI, WndProc).



via Chebli Mohamed

VA-API how to render VASurface


I'm using Intel Media Server in order to decode h264 streams, I'm decoding it via hardware properly and I'm getting a VASurface now I want to be able to render that surface using hardware too.

is there any way to be able to render in hardware mode a VASurface? I can use X11 but this is consuming CPU.



via Chebli Mohamed

Global variable prevents the code to show the result


The following code doesn't show anything! I think the problem is to do with X glob(2); because when I remove it, the code works fine. I don't know what is the reason. Would you help me please? The std_lib_facilities_4.h is here

#include "std_lib_facilities_4.h"
using namespace std;

struct X {
    int val;
    void out(const string& s) {cerr << this << "->" << s << ": " << val << endl; }

     X(int v) { val = v; out("X(int)"); }
    ~X() { out("~X()"); }

};

X glob(2); // A global variable

int main()
{
    X loc(4);

    char ch;
    cin>>ch;
    return 0;
}



via Chebli Mohamed

How to set the class name for a form while creating?


EDIT:

I created an application using a windows forms. The application is having two text boxes to accept Username and password. Here my requirement is to have my own class name to a form instead of default which will be generated by VS. I observed these class name parameter using winspy++ tool. I observed my application is having class name as " WindowsForms10.Window.8.app.0.bf7d44_r29_ad1" . I want to have my own class name for a form. How can I achieve this.

I am adding snapshot here:enter image description here

In above figure I marked my present class name (default ) with red colour. My requirement is similar to the one, which is marked with green colour.

EDIT:

I tried with following code:::: Form1.cs-->

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
using System.Windows.Forms;
namespace classidtrail
{
public partial class Form1 : Form
{


    delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);

    [System.Runtime.InteropServices.StructLayout(
        System.Runtime.InteropServices.LayoutKind.Sequential,
       CharSet = System.Runtime.InteropServices.CharSet.Unicode
    )]
    struct WNDCLASS
    {
        public uint style;
        public IntPtr lpfnWndProc;
        public int cbClsExtra;
        public int cbWndExtra;
        public IntPtr hInstance;
        public IntPtr hIcon;
        public IntPtr hCursor;
        public IntPtr hbrBackground;
        [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
        public string lpszMenuName;
        [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
        public string lpszClassName;
    }

    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern System.UInt16 RegisterClassW(
        [System.Runtime.InteropServices.In] ref WNDCLASS lpWndClass
    );

    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr CreateWindowExW(
       UInt32 dwExStyle,
       [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
   string lpClassName,
       [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
   string lpWindowName,
       UInt32 dwStyle,
       Int32 x,
       Int32 y,
       Int32 nWidth,
       Int32 nHeight,
       IntPtr hWndParent,
       IntPtr hMenu,
       IntPtr hInstance,
       IntPtr lpParam
    );

    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern System.IntPtr DefWindowProcW(
        IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam
    );

    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern bool DestroyWindow(
        IntPtr hWnd
    );

    private const int ERROR_CLASS_ALREADY_EXISTS = 1410;

    private bool m_disposed;
    private IntPtr m_hwnd;public UInt16 class_atom;
    public Form1()
    {
        // Create WNDCLASS
        m_wnd_proc_delegate = CustomWndProc;
        WNDCLASS wind_class = new WNDCLASS();
        wind_class.lpszClassName = "hyd";
        wind_class.lpfnWndProc = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate);

        class_atom= RegisterClassW(ref wind_class);

        int last_error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();

        if (class_atom == 0 && last_error != ERROR_CLASS_ALREADY_EXISTS)
        {
            throw new System.Exception("Could not register window class");
        }

        InitializeComponent();
    }
     protected override CreateParams CreateParams
    {
        get
        {
            CreateParams c = base.CreateParams;
            c.ClassName = class_atom.ToString();
            return c;
        }

    }
       private WndProc m_wnd_proc_delegate;
 }

Program.cs--->

using System;
using System.Collections.Generic;
using System.Linq;
 using System.Windows.Forms;

  namespace classidtrail
   {
   static class Program
   {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
    }
  }

If I use above code am getting exception as "Window class name is not valid" at Application.Run(new Form1()) line in Program.cs. How can resolve this?

Thanks.



via Chebli Mohamed

Using virtual destructors gives error


I'm making a little program for school. I want to add virtual destructor to the class 'IObject', 'Square' and 'RotatedSquare'. But when I do, it gives an error. Is it not possible in this case or how to do it here? here's my code:

interface iobject :

#ifndef IOBJECT_H_
#define IOBJECT_H_
#include "Point.h"

class IObject {
public:
    virtual const Point& getPosition()const = 0;
    virtual double getSize()const = 0;
    //virtual ~IObject();

};

#endif

class square

#ifndef SQUARE_H_
#define SQUARE_H_
#include "IObject.h"
#include "Point.h"
#include <iostream>
class Square : public IObject{
private:
    Point position;
    double size;
public:
    Square(const Point& position, const double size):position(position),size(size){};
    virtual const Point& getPosition() const {return this->position;}
    virtual double getSize() const {return this->size;}
    friend std::ostream& operator<<(std::ostream& out, const Square& s);
    //virtual ~Square();

protected:
    virtual void print(std::ostream& out) const;
};

#endif 

class RotatedSquare

#ifndef ROTATEDSQUARE_H_
#define ROTATEDSQUARE_H_
#include "Square.h"

class RotatedSquare : public Square{
private:
    double angle;
public:
    RotatedSquare(const Point& position, const double size, const double angle): Square(position,size),angle(angle){};
    double getAngle() const {return this->angle;}
    //virtual ~RotatedSquare();
protected:
    virtual void print(std::ostream& out) const;
};

#endif

the error :

Undefined symbols for architecture x86_64:
  "Square::~Square()", referenced from:
      _main in Practice.o
  "vtable for RotatedSquare", referenced from:
      RotatedSquare::RotatedSquare(Point const&, double, double) in Practice.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "vtable for Square", referenced from:
      Square::Square(Point const&, double) in Practice.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "vtable for IObject", referenced from:
      IObject::IObject() in Practice.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.

the main class :

#include <iostream>
#include "Point.h"
#include "IObject.h"
#include "Square.h"
#include "RotatedSquare.h"

int main() {

     IObject* s1 = new Square(Point(1,4),2.2);
     std::cout << s1->getPosition() << std::endl;
     std::cout << s1->getSize() << std::endl;
  Square s2 = Square(Point(4,5),5);
  Square* s3 = new RotatedSquare(Point(5,5),8,60);
  std::cout << s2 << std::endl;
  std::cout << *s3;
return 0;
}



via Chebli Mohamed

Why is C# running faster than C++?


I am not joking. I have a C# application, and a C++ application. They do they exact same thing, in the exact same amount of code...

...And the C# one is running faster, not just faster, but like 10 times faster.

This struck me as weird, because for one, I was running the C# app in the debugger, which should slow C# down to begin with. Then, for the reason of that C# is bytecode with huge overhead using .NET compiled into MSIL with a bunch of extra features, that should slow it down. While C++ is just pure machine code.

Here is the C# code:

static void main()
{
    ulong i = 0;
    while (i < 100000000000)
    {
        Console.WriteLine(i);
        i++;
    }
}

While this was the C++ code

int main()
{
    usigned long i = 0;
    while (i < 100000000000)
    {
        cout << i << endl;
        i++;
    }
    return 0;
}

They are just counting and displaying a number. The C++ one would be at 1000, while the C# one would be at 7000. ( 7x faster)

I even tried compiling both of them, and running them without the debugger using command prompt with the command: cplusplus.exe && csharp.exe

Yeah, I know maybe this question is "offtopic" :P or maybe it is "not clear what's being asked for". :/ But please, someone explain this to me.

If this matters, I am using this CPU: Intel i7 2.5 Ghz.

EDIT: I did the cout << i << "\n"; idea, plus the std::ios_base::sync_with_stdio(false); idea, without any luck or change in results.



via Chebli Mohamed

How to build static and dynamic libraries from .obj files for Visual C++?


I have Visual Studio 2008, Windows7 64 bit.

I am using WinBGIm Graphics Library.

This library is supplied with some .obj files. There are no .lib or .dll files.

I want to convert them into static .lib and dynamic .dll files.

I have copied all .obj files in the directory:

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\amd64

But, the following command is not working:

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\amd64>lib.exe /out:bgiout.lib *.obj
Microsoft (R) Library Manager Version 9.00.21022.08
Copyright (C) Microsoft Corporation.  All rights reserved.

LINK : fatal error LNK1104: cannot open file 'bgiout.lib'

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\amd64>

How to do that?



via Chebli Mohamed

vss sample hardware provider


I've been trying to follow the instructions to install the sample VSS hardware provider that comes with the Windows SDK. I have been able to compile the code successfully with VS2013 for 64bit platform. However when I try to install the provider i get the following error..

Unregistering the existing application.

  • Create the catalog object
  • Get the Applications collection
  • Populate...
  • Search for VssSampleProvider application.
  • Saving changes.

Done.

Creating a new COM+ application

  • Creating the catalog object
  • Get the Applications collection
  • Populate.
  • Add new application object
  • Set app name = VssSampleProvider>
  • Set app description = VSS HW Sample Provider
  • Set app access check = true- Set encrypted COM communication = true
  • Set secure references = true
  • Set impersonation = false
  • Save changes.
  • Create Windows service running as Local System
  • Add the DLL component

ERROR:

  • Error code: -2146368511 [0x80110401]
  • Exit code: 113
  • Description:
  • Source:
  • Help file:
  • Help context: 0

COM+ Errors detected: (1)

(COM+ ERROR 0) on c:\vsssampleprovider\VssSampleProvider.dll
ErrorCode: -2146368475 [0x80110425]
MajorRef: c:\vsssampleprovider\VssSampleProvider.dll

Looking up for COM error code -2146368475 [0x80110425] I could only find that DLL load failed.

Even Viewer logs show a warning saying ... Unable to load DLL c:\vsssampleprovider\VssSampleProvider.dll

Process Name: dllhost.exe Comsvcs.dll file version: ENU 2001.12.10530.16384

shp during component registration. Unable to validate DLL entry points.

#

Thanks in advance.



via Chebli Mohamed

How much DATA section memory is loaded along with Code section in C


I have created a shared library where I have static const data section and code section of 4 functions.

Here are the details of my static const data section,

static const u32 T0[256] = { 256 NON_ZERO value };
static const u32 T1[256] = {256  NON_ZERO value };
static const u32 T2[256] = {256  NON_ZERO value };
static const u32 T3[256] = {256  NON_ZERO value };
static const u32 T4[256] = {256  NON_ZERO value };
static const u32 T5[256] = {256  NON_ZERO value };
static const u32 T6[256] = {256  NON_ZERO value };
static const u32 T7[256] = {256  NON_ZERO value };
static const u32 T8[256] = {256  NON_ZERO value };
static const u32 T9[10] = {10 NON_ZERO value };

Different functions defined just below the static const section

int A();
int B();

// Access different index of T0 - T4 table 
void C();

void D();

As per my understanding the text/code section will contain the executable instruction whereas data section will contain initialized static data ( for simplicity in my case all are static const)

Inside C() function , different index of T0,T1,T2 and T3 are accessed in random order.

Intentionally, inside C(), I have not accessed T0[0].

However, every time I call C() function, it is loading T0[0] irrespective of whether T0[0] is accessed or not inside C() function.

My question is how much adjacent memory of data section is loaded along with code section?

I was thinking may be whole 4KB page loaded, so everytime C() function called, whole 4KB page loaded , therefore T0[0] is also loaded along with it.

but, the experimental result shows THIS CONCEPT IS NOT TRUE/CORRECT.

Let me explain it elaborately as below.

I have calculated the distance between function C() and different static const data as below

Base address of C - Base address of T0[0] = 3221 Bytes
Base address of C - Base address of T1[0] = 4345 Bytes
Base address of C - Base address of T2[0] = 5369 Bytes
Base address of C - Base address of T3[0] = 6393 Bytes

So, whenever C() is invoked , ONLY 64Bytes (i.e. T0[0] ) is loaded . T0[1], T0[2],... the part of T0 array which also belong to same 4KB page with C() NOT LOADED.

In other experiment, when I add another static const of 64Byte ( like static const int DATA=10; ) before static const u32 T0[256] = {.....}

these distances become

Base address of C - Base address of T0[0] =3385 Bytes [ =64 + Base address of C - Base address of T0[0]]
Base address of C - Base address of T1[0] = 4345+64 Bytes =4409 Bytes [=64 + Base address of C - Base address of T0[0]+1024]
Base address of C - Base address of T2[0] = 5369+64 Bytes = 5433 Bytes[=64 + Base address of C - Base address of T0[0]+2*1024]
Base address of C - Base address of T3[0] = 6393 +64 Bytes = 6457 Bytes[=64 + Base address of C - Base address of T0[0]+3*1024]

Now, although T0[0] still present in same 4KB page with C(), it is not loaded whenever C() is invoked.

Note : To calculate whether T0[0] is loaded or not , before invoking C(), I just flushed T0[0] using clflush() instruction and then after C() is invoked I have calculated access time using rdtsc().

Can you help me to explain/understand WHY T0[0] is always accessed/loaded whenever C() is invoked although it is not accessed/used inside C() ?

or any link to understand the memory layout of program and size of memory loaded during execution of program.

I am using Debian OS and gcc compiler.

Thanks in advance



via Chebli Mohamed

Copying value of char pointer array to char array


This is for a simple game and I am trying to learn how to apply C++ in an existing project (that's how I learn best), I have experience programming in C# and other high level languages so it is quite new to me still. So I have this list of races:

const char* Races[] = {
   "Demon",
   "Human",
   "Elf",
   "Orc",
   "Aliens"
};

At one point I receive the registration of a user and a race is selected. I save away all the information of the user to a struct and I want to save the full name of the race to this struct as well.

struct User_t {
   unsigned int RaceID;
   char Race[16];
};

The following code is what I got to put the values inside the struct:

User_t User;

User.RaceID = 3;
strcpy(User.Race, Races[User.RaceID]);

This, however, does not work. This is part of a game and the exception handling is horrible (it basically crashes the game without any error visible). I am trying to figure out what I am doing wrong. Any suggestions, perhaps suggestions on other things as well?



via Chebli Mohamed

Error sending data via Socket


I'm working on a Kinect Application wich need to send the Real Coordenates of the face to another program, Matlab, now I've a Console Application acting as a Client (who receive the data). I test the code apart from the Kinect program and works fine (the message is sent) but when I implement it to the Kinect code the send of the message fails in the SUCCESFUL line (SUCCESFUL = -1 don't know why)

Any ideas of what I have to change in the kinect code?

KINECT FUNCTION

    void SingleFace::FTHelperCallingBack(PVOID pVoid)
    {
    SingleFace* pApp = reinterpret_cast<SingleFace*>(pVoid);
    if (pApp)
    {
    char *sendbuf = new char[buffsize];
    long SUCCESFUL;
    WSAData WinSockData;
    WORD DLLVERSION;
    DLLVERSION = MAKEWORD(2, 1);
    SUCCESFUL = WSAStartup(DLLVERSION, &WinSockData);

    SOCKADDR_IN ADDRESS;
    int AddressSize = sizeof(ADDRESS);
    SOCKET sock_LISTEN;
    SOCKET sock_CONNECTION;
    sock_CONNECTION = socket(AF_INET, SOCK_STREAM, NULL);
    listen(sock_LISTEN, SOMAXCONN);

    IFTResult* pResult = pApp->m_FTHelper.GetResult();
    if (pResult && SUCCEEDED(pResult->GetStatus()))
    {
        fstream outputFile("TrackingResults.txt");
        outputFile << "Resultados del Tracking \n";
        outputFile.close();




        FLOAT* pAU = NULL;
        UINT numAU;
        pResult->GetAUCoefficients(&pAU, &numAU);
        pApp->m_eggavatar.SetCandideAU(pAU, numAU);
        FLOAT scale;
        FLOAT rotationXYZ[3];
        FLOAT translationXYZ[3];

        pResult->Get3DPose(&scale, rotationXYZ, translationXYZ);
        pApp->m_eggavatar.SetTranslations(translationXYZ[0], translationXYZ[1], translationXYZ[2]);
        pApp->m_eggavatar.SetRotations(rotationXYZ[0], rotationXYZ[1], rotationXYZ[2]);

        // MOSTRANDO RESULTADOS EN LA VENTANDA OUTPUT
        std::string resultados = "T = [" + to_string(translationXYZ[0]) + "," + to_string(translationXYZ[1]) + "," + to_string(translationXYZ[2]) + ", ], R=[" + to_string(rotationXYZ[0]) + "," + to_string(rotationXYZ[0]) + "," + to_string(rotationXYZ[1]) + "," + to_string(rotationXYZ[2]) + "], sc=" + to_string(scale) + "/n";
        std::wstring stemp = s2ws(resultados);
        LPCWSTR results = stemp.c_str();
        OutputDebugStringW(results);

        /*Matrix to calculate the real coordenates
        A1 = 98.1987    4.8642
             -6.3882   79.6357
              9.9648   20.0521*/

        double xr = 98.1987*translationXYZ[0] - 6.3882*translationXYZ[2]  + 9.9648;
        double yr =  4.8642*translationXYZ[0] + 79.6357*translationXYZ[2] + 20.0521;
        sprintf(sendbuf, "%+07.2f %+07.2f\n", xr, yr);


        if (sock_CONNECTION = accept(sock_LISTEN, (SOCKADDR*)&ADDRESS, &AddressSize));
        {
            cout << " \n\tA connection was found! " << endl;
            send(sock_CONNECTION, sendbuf, 17, NULL);
            cout << "Sent: (" << sendbuf << ")\n"; 
        }
    }
    }   
    }

//Main Code

int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR     lpCmdLine, int nCmdShow)
{
AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);


//SERVER
long SUCCESFUL;
WSAData WinSockData;
WORD DLLVERSION;

DLLVERSION = MAKEWORD(2, 1);

SUCCESFUL = WSAStartup(DLLVERSION, &WinSockData);

SOCKADDR_IN ADDRESS;
int AddressSize = sizeof(ADDRESS);

SOCKET sock_LISTEN;
SOCKET sock_CONNECTION;
sock_CONNECTION = socket(AF_INET, SOCK_STREAM, NULL);
ADDRESS.sin_addr.s_addr = inet_addr("127.0.0.1");
ADDRESS.sin_family = AF_INET;
ADDRESS.sin_port = htons(444);

sock_LISTEN = socket(AF_INET, SOCK_STREAM, NULL);
bind(sock_LISTEN, (SOCKADDR*)&ADDRESS, sizeof(ADDRESS));
listen(sock_LISTEN, SOMAXCONN);

for (;;)

{
    cout << "\n\tSERVER: Waiting for incomming connetion...";
    if (sock_CONNECTION = accept(sock_LISTEN, (SOCKADDR*)&ADDRESS, &AddressSize));
    {

        cout << " \n\tA connection was found! " << endl;
        UNREFERENCED_PARAMETER(hPrevInstance);
        SingleFace app;
        HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
        return app.Run(hInstance, lpCmdLine, nCmdShow);

    }
} }



via Chebli Mohamed

Finding the directory path


I'm making a windows application, and right now I can find the path for a file when I click open, but how would I be able to find the directory path? For example, if user selects "file.txt", then I want to get the path of "file.txt".(Its location on the disk). I'm using ATL/WTL, and VS 2013.

OPENFILENAME m_ofn;

BOOL m_bOpenFileDialog = true;  // TRUE for file open, FALSE for file save
TCHAR m_szFileTitle[_MAX_FNAME];// contains file title after return
TCHAR m_szFileName[_MAX_PATH];  // contains full path name after return

memset(&m_ofn, 0, sizeof(m_ofn));
m_szFileName[0] = _T('\0');
m_szFileTitle[0] = _T('\0');

m_ofn.lStructSize = sizeof(m_ofn);

m_ofn.lpstrFile = m_szFileName;
m_ofn.nMaxFile = _MAX_PATH;
m_ofn.lpstrDefExt = _T("bmp");
m_ofn.lpstrFileTitle = (LPTSTR)m_szFileTitle;
m_ofn.nMaxFileTitle = _MAX_FNAME;

m_ofn.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | 
              OFN_OVERWRITEPROMPT | OFN_EXPLORER | 
              OFN_ENABLEHOOK | OFN_ENABLESIZING;

m_ofn.lpstrFilter = _T("Image Files (*.bmp;*.jpg;*.jpe;*.gif;*.tga)\0*.bmp;*.jpg;*.jpe;*.gif;*.tga\0All Files\0*.*\0");
m_ofn.hInstance = ModuleHelper::GetResourceInstance();
m_ofn.lpfnHook = NULL;
m_ofn.hwndOwner = NULL;

BOOL bRet;
bRet = ::GetOpenFileName(&m_ofn);
char gcd;
gcd = GetCurrentDirectory(sizeof(m_ofn), m_szFileName);
m_view.Report("Filename = %S\n", m_szFileName);



via Chebli Mohamed

Ho do I sample a cubic shadow map for softer shadows in DirectX 11?


I've implemented a cubic shadow map for dealing with omni-directional light sources in my scene. By defualt it produces hard shadows enter image description here

Obviously a shadow map with higher resolution (currently using 512x512) would produce a finer edge but that would also result in larger memory footprint for the application.

I'm currently using a very simple approach to sample the cubic shadow map using the TextureCube::SampleCmp method

float depthBias = 0.002f;
float shadowFactor = omniShadowMap.SampleCmp( omniShadowSampler, -lightVec, lightVecLength / pointLight.positionAndRadius.w - depthBias );  

if( shadowFactor == 0.0f )
    shadowFactor = 0.5f;

return float4( ( finalDiffuse + finalSpecular.xyz  ) * shadowFactor , 1.0f );

The SamplerComparisonState is configuered like this

D3D11_SAMPLER_DESC samplerDesc;

samplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.MipLODBias = 0;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL;
samplerDesc.BorderColor[0] = 0.0f;
samplerDesc.BorderColor[1] = 0.0f;
samplerDesc.BorderColor[2] = 0.0f;
samplerDesc.BorderColor[3] = 0.0f;
samplerDesc.MinLOD = 0.0f;
samplerDesc.MaxLOD = 0.0f;

A logic approach would be to use Percentage-Closer Filtering but I don't know how to access the texels in a TextureCube.

Any suggestions? Thank you!



via Chebli Mohamed

How to design a Twain DS for a web cam


I would like to make a Twain data source for use with a web cam we use as part of our application.

We have been using a universal driver called Videods.ds which is usually ok but as it saves a temp file to the root of "C" it cant be used on tightly controlled computers.

We would like to write our own Twain data source file so we can simply drop the *.ds file into the Windows\twain32 folder, select it from our application.

We DO NOT want to talk to the web cam directly form our application as we often change web cams as companies like Logitech tend to drop older models quite regularly.

Please suggest!!!



via Chebli Mohamed

How to use a template image to match target which have scale,rotation change and Partial Occlusion using opencv


i have a template image and target image.as follow,enter image description here 1、the target have scale change 2、the target have rotation change 3、the target mix with noise,Partial Occlusion(the color is same-black) So, how can i use the template image to detect the target,and use a ellipse to show the target,like thisenter image description here I have tried matchTemplate function and surf function,but the result is not good,anyone can help me. Please give me some advises. Thanks in advance!!



via Chebli Mohamed

Cannot open type library file: 'msxml.dll': No such file or directory


I'm trying to do a reverse engineering to old .net tool written with c++. The problem begins in this line: import "msxml.dll" named_guids

I understand this is old system dll file which currently replaced with msxml3.dll or msxml6.dll. I found both msxml3.dll and msxml6.dll in system32 folder and mange to do import but then this error appears: error C2653: 'MSXML' : is not a class or namespace name

Please advice and spread some light on this issue. Thank you.



via Chebli Mohamed

Using SetupDI API functions, to disable enable COM port device driver requires running as Administrator


I need to Disable/Enable a loaded device driver because the device "at times" when connected fails to load properly.
This device is controlled by the user and is POWERED AND UN-POWERED very frequently. The program which needs to use the driver DETECTS a failure and needs to Disable/Enable which ALWAYS corrects the issue.

But using the SetupAPI methods causes the executable to require ADMIN rights (Windows 7 and Windows 10). I'm not sure if I need to use "other" coding methods or if SIGNING the executable will remove the "requirement" to run as administrator?

Any ideas would be greatly appreciated.



via Chebli Mohamed

how stream and play ip camera rtsp using libvlc with rtp over rtsp(TCP) VLC option


I write a video server in c++ that is using LIBVLC to stream a AXIS IP camera(192.168.1.25) with computer ip(192.168.1.46). All this time it has been working well with video file stream. Now the I wants to work with IP stream When I tried to open this url(forexample for clint mode): rtsp://192.168.1.46/axis_string_stream on my windows VLC player, I had to go to Tools > Preferences > Input/Codecs and select RTP over RTSP (TCP) in order to be able to play the video stream. Otherwise it wont display the camera(pause in first frame). My question is, is there such parameter in VLC object for the code application to select RTP over RTPS(default parameter:Http)? Because currently it is not working on the application and I'm want set rtp over rtsp (TCP), is this already possible with libvlc through parameter setting in source code? any help would be appreciated! Thanks



via Chebli Mohamed

How to create a search engine like google


I'm new in programming, but I already have 4 months of experience. I'm good in HTML and starting to learn CSS. I want to make search engine like google, that can search in many websites and display the results quick

this is what I already did:

<div id="search_div">
   <input type="text" placeholder="search" name="search">
</div>

how can I do the search? what else I need to know? is there's a ready code for this?

thanks a lot!



via Chebli Mohamed

libusb_control_transfer call returns error "Incorrect Function" (LIBUSB_ERROR_IO)


I've posted a question in order to determinate hardware keylogger, but it seems its to complex and has blurry description, so nobody can answer.
For now my problem is narrowed to a single function call. I am trying to send output report to USB Keyboard with control transfer using libusb. And I am getting LIBUSB_ERROR_IO everytime with the description "Incorrect function" (GetLastError()=1). If doing tracing of libusb_control_transfer call, then the error occured once after DeviceIoControl call there. What that means? Does the device (usb KB) doesn't support output reports? Or maybe some required drivers needed? Testing on Windows 7sp1.

Here is my code:

int UsbKeyboard::SendOutputReport( )
{
    auto kbdev = FindKeyboard();   // finds the keyboard device by product description 
    int r;
    libusb_device_handle *devh = nullptr;
    if ((r = libusb_open(kbdev, &devh)) < 0)
    {
        ShowError("Error open device", r);
        return r;
    }

    r = libusb_set_configuration(devh, 1);
    if (r < 0)
    {
        ShowError("libusb_set_configuration error ", r);
        goto out;
    }

    libusb_set_debug(_context, 4);

    r = libusb_claim_interface(devh, 0);    
    if (r < 0)
    {
        ShowError("libusb_claim_interface error ", r);
        goto out;
    }

    unsigned char buf[65];   // trying to send LED packet
    buf[0] = 0x2; // First byte is report number
    buf[1] = 0x80;

    // here is always error, r==-1 (LIBUSB_ERROR_IO)
    r = libusb_control_transfer(devh, LIBUSB_ENDPOINT_OUT|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
            HID_SET_REPORT/*0x9*/, (HID_REPORT_TYPE_OUTPUT/*0x2*/ << 8) | 0x00,
            0, buf, (uint16_t)2, 1000);                 

    if (r < 0) {
        ShowError("Control Out error ", r);
        goto out;
    }
    else
        cout << "Control Transfer send OK - " << r << endl ;

out:
    libusb_close(devh);
}

And libusb internals code:

// ...
// _windows_usb.c - _hid_set_report()

    // This call returns FALSE and GetLastError()=1 (ERROR_INVALID_FUNCTION)
    if (!DeviceIoControl(hid_handle, ioctl_code/*IOCTL_HID_SET_OUTPUT_REPORT*/, buf, write_size,
            buf, write_size, &write_size, overlapped)) {
            if (GetLastError() != ERROR_IO_PENDING) {
                usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
                safe_free(buf);
                return LIBUSB_ERROR_IO;
            }
            tp->hid_buffer = buf;
            tp->hid_dest = NULL;
            return LIBUSB_SUCCESS;
        }
//...



via Chebli Mohamed

GUI for compiling .cpp files


Net beans has stopped working on me and I've been using atom, which is a great code editor, however you have to compile programs manually. This means going into command prompt, setting up the file location, using g++ -o program program.cpp etc...

Is there any program that I can install that will allow me to right click and compile a .cpp file?

Kind Regards, David



via Chebli Mohamed

error: invalid types for array subscripts


I am trying to print matrix on the screen.My code:

#include <vector>
#include <algorithm>
#include <cmath>
#include <eigen2/Eigen/Core>

int main() {
    std::vector<int> items = {1,2,3,4,5,6,7,8,9,10,11,12,18};

    // generate similarity matrix
    unsigned int size = items.size();
    Eigen::MatrixXd m = Eigen::MatrixXd::Zero(size,size);

    for (unsigned int i=0; i < size; i++) {
        for (unsigned int j=0; j < size; j++) {
            // generate similarity
            int d = items[i] - items[j];
            int similarity = exp(-d*d / 100);
            m(i,j) = similarity;
            m(j,i) = similarity;
        }
    }
      for (unsigned int i=0; i < size; i++) {
        for (unsigned int j=0; j < size; j++) {
           std::cout << m[i][j];
        }
     std::cout << std::endl;
    }
    return 0;
}

When I compile I got this:

pex.cpp: In function ‘int main()’:
pex.cpp:25:31: error: invalid types ‘Eigen::ei_traits<Eigen::Matrix<double, 10000, 10000> >::Scalar {aka double}[unsigned int]’ for array subscript
            std::cout << m[i][j];

Why do I have invalid types here?Or is there any other way to print the content on the screen?My code will be much larger in the future so I want to check calculations on every step.



via Chebli Mohamed

openfl - audio doesn't work on cpp target


I've added <assets path="assets/audio" rename="audio" /> to the application.xml file.

And I load the "mp3" files in the audio folder by calling Assets.getSound("2_3_1.mp3");, and then use the .play(); method on that (sound) object to play the file.

The sounds play in flash target. But don't play on cpp targets. I'm mainly targeting Android (cpp) and iOS (c#) targets for my app.

When debugging for windows (cpp) target, it shows these errors in console:

Sound.hx:99: Error: Could not load "audio/2_3_1.mp3"
Error opening sound file, unsupported type.
Error opening sound data
Done(0)



via Chebli Mohamed

How to display an API populated virtual folder in Windows Common File Dialogs


We have a REST API that we can use to get a list of files, upload and download files. Now we need to integrate this API in one of our application so that users can open and save files using the API.
I want to make the UI consistent with opening and saving a normal file. Instead of creating new dialogs, I believe the Common File Dialogs can be tweaked to display a virtual folder populated using the API. A new location can be added on the list on the left hand side. Any ideas how this can be accomplished?



via Chebli Mohamed

Porting standalone Opencv exe file to run on a linux embedded board


I am making an image processing project with Raspberry Pi 2, ODROID and Core-i7 PC (Windows 7). Since RPi2 and ODROID have very less memory i need to know if i can make OpenCV applications on my PC and then copy the executables to RPi2 & ODROID which run Raspbian and Ubuntu respectively.

If yes then how?

In my PC i would be using OpenCV 2.4.9, Visual Studio 2013 & Qt creator.



via Chebli Mohamed

apple llvm 6.1 error invalid library name -stdlib=libc++ compiler-default


when I reference C++ codes in an O-C file, I modify the .m file to .mm according to articles on the internet. Then I build the project. Unfortunately,I got the err msg below:

apple llvm 6.1 error invalid library name -stdlib=libc++ compiler-default

I have try all the compilers in building settings->C++ language but they don't work. I have try kinds of grammars but they can't work. Now I can't locate the question.Is there someone know about this? Thank you :)



via Chebli Mohamed

samedi 25 avril 2015

Find object in array and then edit it


Let's say I have the following array:

var things = [
    {
        id: "12345",
        name: "Bryan"
    },
    {
        id: "55555",
        name: "Justin"
    }
]

I want to search for the object with the id of 55555. But I want to update the name of that particular object to "Mike" from Justin but still keep the entire army intact.

At the moment, I kinda figured out a way to search for the object, but I can't find a solution to actually edit that particular finding.

Could anyone help me out? This is what I have so far:

var thing = things.filter(function (item) {
    return "55555" === item.id;
})[0]


Empty post response ajax


I'm trying to use ajax to geta response from a codeigniter controller method but it doesn't work ,the response it's empty.

    <script type="text/javascript">
            $(document).ready(function(){
                $("#crear").click(function() {
                    //$('#error_msg').html("Error");
                    $.ajax({
                        type:"POST",
                        url:"clase/create",
                        success:function(data){
                            $('#error_msg').html(data);
                        }
                    });
                });
            });
    </script>

and this is the controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Clase extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('clase_model','',TRUE);
   $this->load->helper(array('form'));
 }

 function index()
 {
    if($this->session->userdata('logged_in')){
        $data['title'] = 'Gestión de Clases';
        $data['clases'] = $this->clase_model->getAll();
      $this->load->view('header', $data);
      $this->load->view('clase_view', $data);

     }
     else{

          redirect('login', 'refresh');
     }
 }

 function create(){
    if($this->session->userdata('logged_in')){
      $this->load->library('form_validation');
      $this->form_validation->set_rules('name', 'Nombre', 'trim|min_length[2]|required');
      $this->form_validation->set_rules('info', 'Información', 'trim');

       if($this->form_validation->run() == FALSE){
          $data = array(
            'error_message1' => form_error('name'),
            'error_message2' => form_error('info')
            );
           return $data['error_message1'];
       }
       else{
          if($this->input->post('info')){
             $this->insert2($this->input->post('name'),$this->input->post('info'));
          }
          else{
            $this->insert1($this->input->post('name')); 
          }
       }   
    }
    else{
          redirect('login', 'refresh');
    }
 }

 function insert2($name,$information){
    $dat = array(
      'nombre'=>$name,
      'info'=>$information
    );
    $this-> db ->insert('clase',$dat);

    echo $name;
    redirect('clase', 'refresh');
 }
 function insert1($name){
    $dat = array(
      'nombre'=>$name,
    );

    $this-> db ->insert('clase',$dat);
    redirect('clase', 'refresh');
 }
}
?>

and the response header

Cache-Control   
no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection  
Keep-Alive
Content-Length  
0
Content-Type    
text/html; charset=UTF-8
Date    
Sat, 25 Apr 2015 16:04:47 GMT
Expires 
Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive  
timeout=5, max=100
Pragma  
no-cache
Server  
Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3
Set-Cookie  
ci_session=941a601d7eaf9f590d21bd4c0aa8c2ac043faa81; expires=Sat, 25-Apr-2015 18:04:47 GMT; Max-Age=7200
; path=/; httponly
x-powered-by    
PHP/5.6.3

Somebody can tell me what is wrong?it's my first time with ajax


how to add image dinamycly jquery


i used the following code to dynamicly create an img the div is created and works fine so is the input text but the problem is that the img control is created but the img is not shown i cant find where the problem is help plz

$.each(data.user, function (i,data) {

    $("<div>"+data.id+"  </div>").attr('id',data.id).appendTo('#page_14_14');
    $('#'+data.id).css({"border-color": "#C1E0FF", 
                        "border-weight":"1px",
                        "margin-top":"10px",                    
                        "border-style":"solid"});

    var ctrl = $('<input/>').attr({ type: 'text', name:'text', value:data.email , id:data.email, disabled:true }).addClass("text");
    $(ctrl).appendTo("#"+data.id); 
    $('#'+data.email).css({"border-color": "#C1E0FF", 
                           "width":"50px",
                           "margin-top":"10px",                    
                           "border-style":"solid"});

    var img = $('<img/>').attr({ className:"inline" , src:"/www/images/Arrow.png" }).addClass("img");

    $(img).appendTo("#"+data.id);        
});   

i also used this for the following two methods for the img but i had the same problem

 var img = $('<img/>', {"class" :"inline", src:"/www/images/Arrow.png"     });


 var img = $('<img class="inline" src="/www/images/bg.png" width="50px" height="50px"  />');


php - pass an array from php to jquery ajax and then again pass the same array from jquery to php


I am in a situation where i am passing an array from php to jquery ajax using json_encode and saving it in an empty array i declared in jquery script var myarr = [], and later on in the same script i am sending the same array i-e, myarr to php script through $.ajax using JSON.stringify function and receiving the array in php script like this json_decode($_POST['myarr'], true), but the problem is it is not converting back into an array. I want to receive an array so that i can use foreach loop to read that array.

Here is the code below. First I am declaring an array in jquery script

var imgArr = [];

Then fetching all the images from php script and saving it in above declared array

PHP Script:

$getProfileId = $users->getPrfId($photoId);
$getImages = array();
$getImages = $users->getTypeImage($getProfileId);
//echo json_encode($getImages);
foreach($getImages as $value){
   echo json_encode($value);
 }

JQuery
  $.ajax({
        type: 'POST',
        url: 'fetchAllImages.php',
        data: {'photoId': photoId},
        success: function(data){
             imgArr = data;
          }
        });

Now in the same script on other button click i am sending this array imgArr to php Script using $.ajax. Here is the code:

JQuery:

$('#right_arrow').live('click', function(e){

var photoId =   $(this).siblings('#o_popup_post').children('#o_post_box').children("#o_complete_post_image").children("img").attr("id");
       $.ajax({
       type: 'POST',
       url: 'nextImage.php',
       data: {'photoId': photoId, 'imgArr' : JSON.stringify(imgArr)},
               beforeSend: function(){
                $('#o_popup_post').fadeOut("normal").remove();
                    $('.o_background_popup').append("<div id='o_popup_post'></div>");
       },
       success: function(response){
            $('#o_popup_post').append(response);
        // alert(imgArr);

       }
    });
   });  


  PHP Script:

  $photoId = $_POST['photoId'];

  $imageArray = array();
  $imageArray = json_decode($_POST['imgArr'], true);

  foreach($imageArray as $key=>$value){....}

Please help. Thanks


How to obtain innerHTML of an active li link?


I want to store the innerHTML of an active menu item to display it as a title for my page. The title HTML is {{pageTitle}}, in the "container" template.

here is my (cleaned) HTML

<template name="container">
   {{pageTitle}
   {{ > SideMenu}}
</template>

<template name="SideMenu">
    <ul id="menu-items" class="nav nav-stacked nav-pills">
        <li id="menu-item-simple" class="">
            <a href="#">
                menuItem1
            </a>
        </li>
        <li id="menu-item-simple" class="">
            <a href="#">
                menuItem2
            </a>
        </li>
    </ul>
</template>

I created an helper to return the string

Template.container.helpers({
"pageTitle":function(){
    return Session.get("pageTitle");
}
});

And an event to set the string to its correct value when a menu item is clicked

Template.SideMenu.events({
    "click #menu-items":function(e,t){
        var activeItem = $(this).find("li.active")
        Session.set ("pageTitle",activeItem.children("a").innerHTML);
        console.log (activeItem.children("a").innerHTML);
    }
});

The console returns "undefined". I don't get what I am doing wrong and since I'm just beginning, I also wanted to know if I'm going the right way.


how to put a message while waiting for callback from ajax


I would like to insert an image working.gif while the data is being processed by the PHP post.. right now it just does nothing until data is returned.. sometimes there is a 10-15 second processing time before data is returned so some sort of indication to tell the user to wait will be great. Lets use the working.gif image as that indicator.

Appreciate assistance on how i can factor the above in to the following code:

$.ajax({
    type: "POST",
    url: "post.php",
    data: dataString,

    //if received a response from the server
    success: function (response) {

        $('#ajaxResponse').html('<pre>' + response + '</pre>');


Convert jquery/js function to pass variable between pages to a ColdFusion variable


I have some jquery which checks if a particular element is visible on a page and passes a parameter to be appended to the url, so the element can be shown/hidden on the next page.

I want to see if it is possible to store this value in a coldfusion variable and then pass it via the navigation, as this seems to be a more robust method to me.

Here is my basic html:

<nav>
            <ul id="mainNav" class="clearfix">
                <li><a href="/">Main</a></li>
                <li><a href="#" class="<cfif VARIABLES.primarydir EQ 'work'>clicked</cfif>">Work</a></li>
                <li><a href="/about"  class="<cfif VARIABLES.primarydir EQ 'about'>clicked</cfif>">About</a></li>
                <li><a href="/news" class="<cfif VARIABLES.primarydir EQ 'news'>clicked</cfif>">News </a></li>
                <li><a href="/tumblr.com" target="_blank">Blog</a></li>
            </ul>
            <ul id="subNav">
                <li><a href="/work/effort" class="<cfif VARIABLES.primarydir EQ 'work' and VARIABLES.secondarydir EQ 'effort'>clicked</cfif>">Effort, We Cried!</a></li>
                <li><a href="/work/why" class="<cfif VARIABLES.primarydir EQ 'work' and VARIABLES.secondarydir EQ 'why'>clicked</cfif>">Why Do We Do This</a></li>
                <li><a href="/work/guests" class="<cfif VARIABLES.primarydir EQ 'work' and VARIABLES.secondarydir EQ 'guests'>clicked</cfif>">Guests &amp; Hosts</a></li>
                <li><a href="/work/prettygirls" class="<cfif VARIABLES.primarydir EQ 'work' and VARIABLES.secondarydir EQ 'prettygirls'>clicked</cfif>">Pretty Girls Doing Horrid Things</a></li>
            </ul>
</nav>

#subNav is set to hidden by default in the css.

I think have some basic jquery to toggle the visibility of the subNav:

    var toggleSubNav = (function(){
        trigger.on('click',function(){
            subNav.toggleClass('visible', function(){
                subNavLength = subNav.is(':visible');
            });
            return false;
        });
    }());

And then a second function which checks the visibility of the subNav and appends the url:

merge.on('click',function(){
            var url = $(this).attr('href');
            subNavLength = subNav.is(':visible');
            if(subNavLength){
                window.location = url + '?subnav=true';
            }else{
                window.location = url;
            }
            return false;
        });

Finally a function which checks the url for the content of '?subnav=true' to display this on the next page:

var subNavProp = (function(){
        if(href.indexOf('?subnav=true') > 0){
            subNav.addClass('visible');
        }else{
            subNav.removeClass('visible');
        }
    }());

The variable subNavLength is global and gets updated via these various functions.

I realise I am posting an awful lot of jquery and I don't really know how (or if) there is a way to convert this to a backend solution for coldfusion. My thought was that I could toggle a class on the subNav element that is wrapped in a coldfusion if, something like:

<ul id="subNav" class="<cfif var IS true">className</cfif>">

But I am wondering if that still requires something of a Front End solution. Or even if there is another better way to do this?


Passing mouseover through element


I'm working on a regex-analyzer that has syntax highlighting as a feature.

My site uses an overlay of two contenteditable divs.

enter image description here

Because of the difficulty in getting the cursor position and maintaining that even as tags are added and subtracted, I decided the best route was to have two contenteditable divs, one on top of the other. The first (#rInput) is pretty plain. If not for some nuisance problems that made me switch from a textarea, it could be a textarea. The second (#rSyntax) gets its value from rInput and provides syntax highlighting. I make sure that both are always scrolled to the same position so that the overlay is perfect (However, I also use a transparent (rgba(...)) font on rSyntax, so that if a momentary sync-delay should occur, the text is still legible.)

In the lower portion snapshot above, the code of the contenteditable rSyntax is this:

<span class="cglayer">(test<span class="cglayer">(this)</span>string)</span>

While rInput, positioned exactly on top, contains only this

(test(this)string)

The problem with this method is that I want to offer some alt-tooltips (or a javascript version) when a user mouses over. When the user mouses over rInput, I would like to pass the mouseover event to elements of rSyntax.

I'd like mousing over (test ... string) to show "Capturing group 1", while mousing over (this) would show "Capturing group 2", or if it were (?:test), it would say "Non-capturing group".

The terminology is a little tough because searching for things like "above" and "below" pulls up a lot of results that have nothing to do with z-index.

I did find the css property pointer-events which sounded ideal for the briefest moment but doesn't allow you to filter pointer events (set rInput to receive clicks, scrolls, but pass mouseover through to rSyntax and its child-elements.

I found document.elementFromPoint which may offer a solution but I'm not really sure how. I thought I would try document.getElementById('rInput').getElementFromPoint(mouseX,mouseY), but this function is not available to child elements.

Theoretically, I could hide the rInput on mousemove, using a setTimeout to put it back quickly, and then a tooltip should appear when mousing over child elements of rSyntax, but that doesn't seem like the best solution because I don't want rSyntax to be clickable. Clicks should always go to rInput.

It's possible to disable the mouseover wizardry while rInput has the focus, but then tooltips from rSyntax won't work, and though I haven't tried this method, I'm not sure if passing a click event from rSyntax to rInput would position the cursor properly.

Is there a method to make this work?


check if the image is available in the given URL by javascript / angularjs or jquery


I am developing an application using java and angularJS. I am getting an image url from database and in the client side I want to check whether that Image is available in that url, if ONLY display it else to display a default image I have.

So how can I check that image is actually available in the given URL..?


Manipulating dynamically generated elements on page load (not a click event or similar)


To bind code to dynamic elements the following is often used: $(document).on('click','#element',function() {});

However I want to do something with those elements on page load, not when user does something particular. How to do that?


Is there a reliable jQuery plugin hat can repopulate the form from json values?


I have a form with 180 form fields. On a button click I need to replace current form fields values with the ones from json var. Instead of doing

on some element click 
$.each(getData, function(index, value) {

    check if select
        add new value, trigger refresh
    check if radio
       add new value, trigger refresh
    check if textarea
       add new value, trigger refresh
...

is there already a plugin that does something like this? I browsed and came up with very old scripts like populate or loadJSON wich are not supported anymore.

My biggest issue is that this is a multi level json array and the field names are like

<input name="form_field[one]"...
<input name="form_field[one][two][three]"...
<input name="form_field[one][two]"...

any help is appreciated.


JQuery Mobile creates wrong HTML code


I'm currently developing a PhoneGap Application for Android using JQuery Mobile. All i want, is to dynamically change the header text of a collapsible:

<div data-role="collapsible" id="collapse">
   <h3>I'm a header</h3>
   <p>I'm the collapsible content</p>
</div>

That code is from demos.jquerymobile.com. Chrome DevTools gives me the following html for this example: http://ift.tt/1HCVBut

For any reason, if i copy exactly the same code to my index.html and run it, chrome DevTools gives me the following html: http://ift.tt/1Gt3UWD

Why are there different html codes?

I actually can change the header's text by

$("#collapse").text("new text");

but then it looses all the styling and also

$("#collapse").trigger('create').

doesn't do anything. What am I doing wrong?


Create a 3D Slideshow with jquery


I'm looking to create a 3D Slideshow or carousel through jquery, css, & html. Something like this is what i want to have http://ift.tt/1ORLSiV

It would be nice if you can include the reflection on the images as well. I only plan to put 3-5 into the carousel.

If anyone could help me, it would be much appreciated


How to end JQuery endless scroll


I know this topic is overflowing on this site however when using the endless scroll plugin below I was hoping to figure out a way of just loading from my ajax request but somehow just ending at some point. e.g. eventually reaching the bottom? Any help is much appreciated?

     <script type="text/javascript">
$(window).scroll(function()
{
    if($(window).scrollTop() == $(document).height() - $(window).height())
{
    $('div#loadmoreajaxloader').show();
    $.ajax({
    url: "{{url('contentpage')}}",
    success: function(html)
    {
        if(html)
        {
            $("#postswrapper").append(html);
            $('div#loadmoreajaxloader').hide();
        }else
        {
            $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
        }
    }
    });
    }
});
</script>


How to find today's date in DateTimePicker JavaScript?


I'm using the following javascript: http://ift.tt/1MosCse , and I want to achieve simple effect - when User selects today's day, it should show him only hours available from now until the end of the day, the previous time should be disabled. But when he choses any other day in the future - then the whole time should be available. I wrote the following function in JS:

<script>
var today = new Date();
var dd = today.getDate();
alert(dd);
           var logic = function( currentDateTime ){
  if( currentDateTime.getDay()==dd ){
    this.setOptions({
      formatTime:'g:i A', 
format: 'd/m/Y h:i A',
  minDate:'+1970/01/02',//today
  minTime: //I don't know yet how to implement the current time
    });
  }else
    this.setOptions({
     formatTime:'g:i A', 
format: 'd/m/Y h:i A',
  minDate:'+1970/01/02'//today
    });
};


                jQuery('#datetimepicker').datetimepicker({
                onChangeDateTime:logic,
                onShow:logic
                });

</script>

The problem is that that line:

currentDateTime.getDay()==dd

doesn't work, because in my case dd equals todays day of the month (e.g. 25), and currentDateTime.getDay() checks current day of the week (e.g. for saturday it's 6). Is there anyone who could help me with that issue? I know there are some other available solutions (other datetime pickers), but I cannot find any other that is as simple and elegant as this. Thanks!


How to get the text from a specific closest element?


I've been learning to code by my own and to do some fancy stuff with jquery library but I'm stuck here. This is what I got:

<span class='ccy'>San Diego</span><span class='dc'> X</span>
<span class='ccy'>San francisco</span><span class='dc'> X</span>
<span class='ccy'>Palo alto</span><span class='dc'> X</span>

I want to be able to click in the $("span.dc") and get only the text() of the < span> next to it (the name of the city), works fine if there is only one city in the html, but as long as I keep adding them up the result gets messy and I end up with a string containing all the city names and I only need one.

I know that the obvious thing would be give them a different id to each one but it'd get even messier 'cause the that html is dynamically generated depending on a previous event triggered by the user, the cities come from an array and I need the individual name of the city to delete from it if 'x' is clicked, I hope I've explained myself good enough.

jsfiddle here!! so you can see better what I mean


facing on Making voting system (Like /Unlike) Button for Q&A website in php , mysql using ajax


i have a Question & Answer website as a part of my graduation project , so am still fresh to such languages but i will try to be specific as much as i can ,,, well i got voting for both Question and answers at each special question page ,, i use the same voting code with changing queries to retrieve desired data ,, but the problem is one of the voting system only works (Question voting or Answers voting) i suppose the problem is action listener is listen to the same btn or the span or smth like that i tried to change values but without any mentioned result,, i will provide all the code am using and am ready to replay to any comment to make stuff clear so i hope you guys help me out to make both voting systems work in the same page ,, thnx you very much ... ^^

srip.js > script for questions

 $(document).ready(function(){
    // ajax setup
$.ajaxSetup({
    url: 'ajaxvote.php',
    type: 'POST',
    cache: 'false'
});

// any voting button (up/down) clicked event
$('.vote').click(function(){
    var self = $(this); // cache $this
    var action = self.data('action'); // grab action data up/down 
    var parent = self.parent().parent(); // grab grand parent .item
    var postid = parent.data('postid'); // grab post id from data-postid
    var score = parent.data('score'); // grab score form data-score

    // only works where is no disabled class
    if (!parent.hasClass('.disabled')) {
        // vote up action
        if (action == 'up') {
            // increase vote score and color to orange
            parent.find('.vote-score').html(++score).css({'color':'orange'});
            // change vote up button color to orange
            self.css({'color':'orange'});
            // send ajax request with post id & action
            $.ajax({data: {'postid' : postid, 'action' : 'up'}});
        }
        // voting down action
        else if (action == 'down'){
            // decrease vote score and color to red
            parent.find('.vote-score').html(--score).css({'color':'red'});
            // change vote up button color to red
            self.css({'color':'red'});
            // send ajax request
            $.ajax({data: {'postid' : postid, 'action' : 'down'}});
        };

        // add disabled class with .item
        parent.addClass('.disabled');
       };
   });
});

ajaxvote.php for opertion inside the questions

<?php


include('config.php');
# start new session
dbConnect();
session_start(); /*  changes will occuar here */

if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) AND isset($_POST['action'])) {
    $postId = (int) mysql_real_escape_string($_POST['postid']);
    # check if already voted, if found voted then return
    //if (isset($_SESSION['vote'][$postId])) return;
    # connect mysql db
    dbConnect();

    # query into db table to know current voting score 
    $query = mysql_query(" 
        SELECT rate
        from qa
        WHERE id = '{$postId}' 
        LIMIT 1" ); /*  changes will occuar here */

    # increase or dicrease voting score
    if ($data = mysql_fetch_array($query)) {
        if ($_POST['action'] === 'up'){
            $vote = ++$data['rate'];
        } else {
            $vote = --$data['rate'];
        }
        # update new voting score
        mysql_query("
            UPDATE qa
            SET rate = '{$vote}'
            WHERE id = '{$postId}' "); /*  changes will occuar here */

        # set session with post id as true
        $_SESSION['vote'][$postId] = true;
        # close db connection
        dbConnect(false);
    }
}
}
?>

printing code : QR.php

  <?php 

require ("coonection.php");

if(isset($_GET['start']) )
 {
  $FURL = $_GET['start'];


   $data=mysql_query("SELECT * FROM qa WHERE id=($FURL)");
   while($d=mysql_fetch_assoc($data)) { ?>
  <div class="item" data-postid="<?php echo $d['id'] ?>"  data-score="<?php echo $d['rate'] ?>">
        <div class="vote-span"><!-- voting-->
            <div class="vote" data-action="up" title="Vote up">
                <i class="glyphicon glyphicon-thumbs-up"></i>
            </div><!--vote up-->
            <div class="vote-score"><?php echo $d['rate'] ?></div>
            <div class="vote" data-action="down" title="Vote down">
                <i class="glyphicon glyphicon-thumbs-down"></i>
            </div><!--vote down-->
        </div>

        <div class="title"><!-- post data -->
              <p><?php echo $d['question'] ?></p>
          </div>
     </div><!--item-->
    <?php  } } ?>
    </div>

 </p>


                        </div>
    <div class="single-post-title" align="center">
    <h2>Answers</h2>
    </div>
                        <!-- Comments -->
     <?php



  require ("coonection.php");
    if(isset($_GET['start']) )
    {
        $FURL = $_GET['start'];
        $data=mysql_query("SELECT * FROM answers WHERE question_id=($FURL)");
        while($d = mysql_fetch_assoc($data))
        {



                echo'<div class="shop-item">';
                echo'<ul class="post-comments">';
                echo'<li>';
                echo'<div class="comment-wrapper">';
                echo'<h3>';
                echo  $d['answerer'] ;
                echo'</h3>';
                echo '</div>'; ?>
                 <div class="item" data-postid="<?php echo $d['answer_id'] ?>" data-score="<?php echo $d['rate'] ?>">
        <div class="vote-span"><!-- voting-->
            <div class="vote" data-action="up" title="Vote up">
                <i class="icon-chevron-up"></i>
            </div><!--vote up-->
            <div class="vote-score"><?php echo $d['rate'] ?></div>
            <div class="vote" data-action="down" title="Vote down">
                <i class="icon-chevron-down"></i>
            </div><!--vote down-->
        </div>

        <div class="post"><!-- post data -->
            <p><?php echo $d['answer'] ?></p>
        </div>
    </div><!--item-->
<?php
                echo'<div class="comment-actions"> <span class="comment-date">';
                echo  $d['dnt'] ;
                echo'</div>';
                echo'</li>';
                echo'</ul>';
                echo'</div>';            




          }

        }
    ?>

i got ajaxvote2.php and also got scrip2.js for settings in answer ,,, i think using the same code make the printing page confused and only listen to one of voting systems

i will add ajaxvote2.php and scrip2.js just in case some one need to look at them ...

ajaxvote2.php

 <?php


include('config.php');
 # start new session
 dbConnect();
 session_start(); /*  changes will occuar here */

 if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
 if (isset($_POST['postid']) AND isset($_POST['action'])) {
    $postId = (int) mysql_real_escape_string($_POST['postid']);
    # check if already voted, if found voted then return
    //if (isset($_SESSION['vote'][$postId])) return;
    # connect mysql db
    dbConnect();

    # query into db table to know current voting score 
    $query = mysql_query(" 
        SELECT rate
        from answers
        WHERE answer_id = '{$postId}' 
        LIMIT 1" ); /*  changes will occuar here */

    # increase or dicrease voting score
    if ($data = mysql_fetch_array($query)) {
        if ($_POST['action'] === 'up'){
            $vote = ++$data['rate'];
        } else {
            $vote = --$data['rate'];
        }
        # update new voting score
        mysql_query("
            UPDATE answers
            SET rate = '{$vote}'
            WHERE answer_id = '{$postId}' "); /*  changes will occuar here */

        # set session with post id as true
        $_SESSION['vote'][$postId] = true;
        # close db connection
        dbConnect(false);
    }
}
} 
?>

scrip2.js

$(document).ready(function(){
// ajax setup
$.ajaxSetup({
    url: 'ajaxvote2.php',
    type: 'POST',
    cache: 'false'
});

// any voting button (up/down) clicked event
$('.vote').click(function(){
    var self = $(this); // cache $this
    var action = self.data('action'); // grab action data up/down 
    var parent = self.parent().parent(); // grab grand parent .item
    var postid = parent.data('postid'); // grab post id from data-postid
    var score = parent.data('score'); // grab score form data-score

    // only works where is no disabled class
    if (!parent.hasClass('.disabled')) {
        // vote up action
        if (action == 'up') {
            // increase vote score and color to orange
            parent.find('.vote-score').html(++score).css({'color':'orange'});
            // change vote up button color to orange
            self.css({'color':'orange'});
            // send ajax request with post id & action
            $.ajax({data: {'postid' : postid, 'action' : 'up'}});
        }
        // voting down action
        else if (action == 'down'){
            // decrease vote score and color to red
            parent.find('.vote-score').html(--score).css({'color':'red'});
            // change vote up button color to red
            self.css({'color':'red'});
            // send ajax request
            $.ajax({data: {'postid' : postid, 'action' : 'down'}});
        };

        // add disabled class with .item
        parent.addClass('.disabled');
    };
 });
});