Remove all files from directory/folder in Qt

Clean directory entries/ Empty directory/folder content

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 
//single line function 
QDir dir( path );
dir.removeRecursively();
 
//But there is no info about deleting files and whether they are deleted or not. and also it remove directory itself
// so you need to create a empty directory again in case you want to delete content only.
 
//Below functions does same except it won't remove directory and gives proper status of each files.
 
//Yash - Speedovation.com : Please don't remove this line
bool Cleanup::clearDir( const QString path )
{
    QDir dir( path );
 
    dir.setFilter( QDir::NoDotAndDotDot | QDir::Files );
    foreach( QString dirItem, dir.entryList() )
    {
        if( dir.remove( dirItem ) )
        {
            Logger::Log_Info( "Cleanup", "Deleted - " + path + QDir::separator() + dirItem );
        }
        else
        {
            Logger::Log_Error( "Cleanup", "Fail to delete - " + path+ QDir::separator() + dirItem);
        }
    }
 
 
    dir.setFilter( QDir::NoDotAndDotDot | QDir::Dirs );
    foreach( QString dirItem, dir.entryList() )
    {
        QDir subDir( dir.absoluteFilePath( dirItem ) );
        if( subDir.removeRecursively() )
        {
            Logger::Log_Info("Cleanup","Deleted - All files under " + dirItem );
        }
        else
        {
            Logger::Log_Error("Cleanup","Fail to delete - Files under " + dirItem);
        }
    }
 
    return true;
}

Count all files under directory recursively in Qt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
//Yash - Speedovation.com : Please don't remove this line
int Cleanup::countFiles(const QString &path, bool countDirs)
{
 
    QDir dir(path);
    QStringList fileslist = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
 
    qDebug() < <fileslist.count() ;
 
    if(!countDirs)
        return fileslist.count();
 
    int count = fileslist.count();
 
    QStringList folderList = dir.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
 
    foreach (QString folder, folderList) {
         folder = tr("%1%2%3").arg(path).arg(QDir::separator()).arg(folder) ;
        qDebug() << folder;
         count += countFiles( folder, true);
    }
 
 
    return count;
 
}

converting QString to LPCWSTR, QString to const wchar_t, QString to CONST WCHAR and vice-versa

All of above means same. Below I’ve explained why

Convert from QString to LPCWSTR

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
QString key;
const wchar_t *keyName = (const wchar_t*)key.utf16();
 
LPCWSTR = const wchar_t
 
Here is how
LPCWSTR = CONST WCHAR  
CONST = const
wchar_t = WCHAR
 
 
//so we can write like this
LPCWSTR str = (const wchar_t*)key.utf16();

Convert from LPCWSTR to QString

1
QString::fromWCharArray(keyName)

Laravel load Huge CSV file into MySQL

1
2
3
4
5
6
 
$csv = app_path().DIRECTORY_SEPARATOR."database".DIRECTORY_SEPARATOR."resources".DIRECTORY_SEPARATOR."locations.csv";
 
 $query = sprintf("LOAD DATA INFILE '%s' INTO TABLE locations FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"' LINES TERMINATED BY '\\n' IGNORE 0 LINES (`location_id`, `country`, `region`, `city`, `postal_code`, `lat`, `lng`, `metro_code`, `area_code`)", addslashes($csv));
 
 DB::connection()->getpdo()->exec($query);

May face this problem

SQLSTATE[28000]: Invalid authorization specification: 1045 Access denied for user ‘ww’@'localhost’ (using password: YES)

So the first thing I did was to check if the parameter “local_infile” was enabled in my mysql database by running the following command:

mysql> show variables;

As in my case was already, I added the following parameter in my config file laravel / database.php:

1
2
3
'options'  => array(
   PDO::MYSQL_ATTR_LOCAL_INFILE => true
)

And then added the argument ‘local’ for the load data infile command, thus:

1
2
$pdo = DB::connection()->pdo;
$pdo->exec("load data LOCAL infile '".path('data')."filetoimport.sql' replace into table tablename CHARACTER SET 'UTF8' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n';");

Instead of:

1
2
$pdo = DB::connection()->pdo;
$pdo->exec("load data infile '".path('data')."filetoimport.sql' replace into table tablename CHARACTER SET 'UTF8' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n';");

This is one solution

and other is

Try to give more privileges ..admin and query related. In my case giving more access worked.

Enjoy

Extract environmental variable and replace using Qt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
QString Common::parse(QString str)
{
    int pos = 0;
    QRegExp rx("%([^%]+)%"); // Match env var between two '%'
    rx.setMinimal(true);
    while((pos = rx.indexIn(str, pos)) != -1)
    {
        // Replace env var
        QString capture = rx.cap(1);
        QString replacement = qgetenv(capture.toLatin1().constData());
        str.replace("%" + capture + "%", replacement);
 
        // Skip env var + two '%'
        pos += rx.matchedLength() + 2;
    }
    return str;
}

Manually Clean Windows’s Registry

Windows Registry is a virtual record of physically scattered hives, containing certain system and user settings. These records are employed by system components, third party applications, hardware, user profiles, and other great deal of stuff. A contaminated registry can lead to certain problematic situations, like sluggish PC performance, broken file extensions, and misconfigured applications.

 

Fortunately, Windows lets you enter the realm of its registry and make changes in it. You can create, remove, copy, rename, and modify registry entries for your own customization. However, to perform such tasks, you must possess an advanced level of knowledge and experience.

 

Assess registry entries to know their validity. Some of the basic types of entries are;

 

  • Application Settings
  • Uninstall Entries
  • Shared DLLs
  • Startup Items
  • File Extension Association
  • COM Components
  • Drivers and Services

 

Detailed examples associating each of the above are described below. Each cleaning process requires Registry Editor. Wait a second! Just before editing your registry, make sure to create a backup to avoid inconvenience due to any mistake.

 

  • Type regedit in the Run box or Start menu/screen Search
  • Click Yes on UAC message to confirm your action
  • Create a backup of your current registry by accessing File menu and selecting Export
  • Under Export range select All, give .reg file a name and Save it
  • If anything goes wrong during the course of registry cleanup, you can restore the backup by accessing Import option from File menu
  • In the displayed Dialog box locate the .reg file created earlier and click Open.

Read more »

Convert BYTE* to QSTRING in Qt

1
2
3
4
BYTE* pu8_RawData = (BYTE*)i_RawData.parray->pvData;
    DWORD u32_RawLen  =        i_RawData.parray->rgsabound[0].cElements;
 
    qDebug() < < "PP: " << QString(QByteArray((const char*) pu8_RawData, (int)u32_RawLen));

Generate thumbnail in ubuntu

sudo apt-get install imagemagick

for i in $(ls *.png); do convert -scale 400 $i th-$i; done

Code is like poetry

Code is like poetry

difficult to understand and often has other meaning than intended.

Code is like poetry.

Delightful to read
a pleasure to understand
a lifetime to master.

Handle Uploaded file using post in django

def receive(request):
   assert request.method=="POST"
   print "receive.META.SERVER_PORT", request.META["SERVER_PORT"], request.POST
   files = []
   for multipart_name in request.FILES.keys():
      multipart_obj = request.FILES[multipart_name]
      content_type  = multipart_obj['content-type']
      filename      = multipart_obj['filename']  
      content       = multipart_obj['content']  
      files.append((filename, content_type, content))
      import datetime
      # write file to the system - add timestamp in the name
      file("c:\\tmp\\%s_%s" % (datetime.datetime.now().isoformat().replace(":", "-"), filename), "wb").write(content)
 
   fnames = ",".join([fname for fname, ct, c in files])
   return HttpResponse("me-%s-RECEIVE-OK[POST=%s,files=%s]" % (request.META["SERVER_PORT"], request.POST.values(), fnames ))
def write_tmp_file(self,request):
        # open a new file to write the contents into
        new_file_name = TEMP_FILE_PATH + request.FILES['file'].name 
 
        destination = open(new_file_name, 'wb+')
        destination.write(request.FILES['file'].read())
        destination.close()
 
        return str(new_file_name)
Page 1 of 912345...Last »