Reset the scaling in the wxWidgets driver. It now uses wxDC::SetLogicalScale so that the wxDC does conversion from plplot internal coordinates to native device coordinates. This gives us subpixel accuracy when using the wxGCDC interface. The exception is when drawin text. Here the driver does the scaling. Ths ib partly to avoid rewriting the rather complex code that deals with newines, sub/superscripts and rotation, but also because we should get better text hinting for on screen/raster graphics if we work in native coordinates (although I haven't checked if is really any different).

--- drivers/wxwidgets_dc.cpp
+++ drivers/wxwidgets_dc.cpp
@@ -37,6 +37,30 @@
 #include <cmath>
 #include "wxwidgets.h"

+//--------------------------------------------------------------------------
+// ScaleChanger class
+// This class changes the logical scale of a dc on construction and resets
+// it to its original value on destruction. It is ideal for making temporary
+// changes to the scale and guarenteeing that the scale gets set back.
+//--------------------------------------------------------------------------
+class Scaler
+{
+public:
+	Scaler( wxDC * dc, double xScale, double yScale )
+	{
+		m_dc = dc;
+		dc->GetLogicalScale(  &m_xScaleOld, &m_yScaleOld );
+		dc->SetLogicalScale( xScale, yScale );
+	}
+	~Scaler( )
+	{
+		m_dc->SetLogicalScale( m_xScaleOld, m_yScaleOld );
+	}
+private:
+	wxDC *m_dc;
+	double m_xScaleOld;
+	double m_yScaleOld;
+};

 //--------------------------------------------------------------------------
 //  wxPLDevice::wxPLDevice( void )
@@ -184,10 +208,7 @@
 	if( !m_dc )
 		return;

-    x1a = (short) ( x1a / m_scalex ); y1a = (short) ( m_height - y1a / m_scaley );
-    x2a = (short) ( x2a / m_scalex );        y2a = (short) ( m_height - y2a / m_scaley );
-
-    m_dc->DrawLine( (wxCoord) x1a, (wxCoord) y1a, (wxCoord) x2a, (wxCoord) y2a );
+    m_dc->DrawLine( (wxCoord) x1a, (wxCoord) ( m_plplotEdgeLength - y1a ), (wxCoord) x2a, (wxCoord) ( m_plplotEdgeLength - y2a ) );
 }

@@ -201,18 +222,8 @@
 	if( !m_dc )
 		return;

-    wxCoord x1a, y1a, x2a, y2a;
-
-    x2a = (wxCoord) ( xa[0] / m_scalex );
-    y2a = (wxCoord) ( m_height - ya[0] / m_scaley );
     for ( PLINT i = 1; i < npts; i++ )
-    {
-        x1a = x2a; y1a = y2a;
-        x2a = (wxCoord) ( xa[i] / m_scalex );
-        y2a = (wxCoord) ( m_height - ya[i] / m_scaley );
-
-        m_dc->DrawLine( x1a, y1a, x2a, y2a );
-    }
+        m_dc->DrawLine( xa[i-1], m_plplotEdgeLength - ya[i-1], xa[i], m_plplotEdgeLength - ya[i] );
 }

@@ -228,29 +239,23 @@
 	if( !m_dc )
 		return;

-    if ( x1 < 0 )
-        x1 = 0;
-    else
-        x1 = (PLINT) ( x1 / m_scalex );
-    if ( y1 < 0 )
-        y1 = 0;
-    else
-        y1 = (PLINT) ( m_height - y1 / m_scaley );
-    if ( x2 < 0 )
-        x2 = m_width;
-    else
-        x2 = (PLINT) ( x2 / m_scalex );
-    if ( y2 < 0 )
-        y2 = m_height;
-    else
-        y2 = (PLINT) ( m_height - y2 / m_scaley );
+	x1 = x1 < 0 ? 0 : x1;
+	x2 = x2 < 0 ? m_plplotEdgeLength : x2;
+	y1 = y1 < 0 ? 0 : y1;
+	y2 = y2 < 0 ? m_plplotEdgeLength : y2;
+
+	PLINT x = MIN( x1, x2 );
+	PLINT y = MIN( y1, y2 );
+	PLINT width = abs( x1 - x2 );
+	PLINT height = abs( y1 - y2 );

     const wxPen   oldPen   = m_dc->GetPen();
     const wxBrush oldBrush = m_dc->GetBrush();

-    m_dc->SetPen( *( wxThePenList->FindOrCreatePen( wxColour( bgr, bgg, bgb ), 1, wxSOLID ) ) );
-    m_dc->SetBrush( wxBrush( wxColour( bgr, bgg, bgb ) ) );
-    m_dc->DrawRectangle( x1, y1, x2 - x1, y2 - y1 );
+	m_dc->SetPen( wxNullPen );
+
+	m_dc->SetBrush( wxBrush( wxColour( bgr, bgg, bgb ) ) );
+	m_dc->DrawRectangle( x, y, width, height );

     m_dc->SetPen( oldPen );
     m_dc->SetBrush( oldBrush );
@@ -339,10 +344,11 @@
 void wxPLDevice::SetExternalBuffer( PLStream *pls, void* dc )
 {
     m_dc   = (wxDC *) dc; // Add the dc to the device
-	strcpy( m_mfo, "" );
-	BeginPage( pls );
-	if( strlen( m_mfi ) > 0 )
-		plreplot();
+	//if( m_dc )
+	{
+		strcpy( m_mfo, "" );
+		SetSize( pls, m_width, m_height ); //call with our current size to set the scaling
+	}
 }

 //--------------------------------------------------------------------------
@@ -571,6 +577,11 @@
 	if( !m_dc )
 		return;

+	//for text work in native coordinates, partly to avoid rewriting existing code
+	//but also because we should get better text hinting for screen display I think.
+	//The scaler object sets the scale to the new value until it is destroyed
+	//when this function exits.
+	Scaler scaler( m_dc, 1.0, 1.0 );
     // Check that we got unicode, warning message and return if not
     if ( args->unicode_array_len == 0 )
     {
@@ -777,8 +788,13 @@
     // Set the number of plplot pixels per mm
 	plP_setpxl( m_plplotEdgeLength / m_width * pls->xdpi / 25.4, m_plplotEdgeLength / m_height * pls->xdpi / 25.4 );

-	//redraw the plot if we have somewhere to draw it to
+	// set the dc scale and redraw the plot if we have a dc
 	if( m_dc )
+	{
+		//we use the dc to do the scaling as it then gives us subpixel accuracy
+		m_dc->SetLogicalScale( (PLFLT)m_width / m_plplotEdgeLength, (PLFLT)m_height / m_plplotEdgeLength );
+		BeginPage( pls );
 		plreplot();
-}
-
+	}
+}
+


added leak checking for resource_mgr.purge()

--- mandala/resource_mgr.cpp
+++ mandala/resource_mgr.cpp
@@ -1,3 +1,11 @@
+#if defined(DEBUG)
+//std
+#include <vector>
+
+//boost
+#include <boost\weak_ptr.hpp>
+#endif
+
 //mandala
 #include "resource_mgr.hpp"

@@ -41,6 +49,25 @@

 	void resource_mgr_t::purge()
 	{
+#if defined(DEBUG)
+        std::vector<boost::weak_ptr<resource_t>> resources;
+
+        for (auto& type_resource : type_resources)
+        {
+            for (auto& resource : type_resource.second)
+            {
+                resources.push_back(resource.second);
+            }
+        }
+#endif
+
 		type_resources.clear();
+
+#if defined(DEBUG)
+        for (auto& resource : resources)
+        {
+            assert(resource.expired());
+        }
+#endif
 	}
 }


Add documentation to SpotifyBackstage.hpp

--- SpotifyBackstage.hpp
+++ SpotifyBackstage.hpp
@@ -12,41 +12,125 @@
 struct EqState;
 struct Track;

+/**
+ * SpotifyBackstage implements the API to spotify-backstage library.
+ * It offers a Spotify-powered music backend including playback, queuing tracks, Spotify search, etc.
+ * The API is used by creating a SpotifyBackstage instance.
+ *
+ * Features:
+ * - Play queue: Enqueue tracks to the play queue. spotify-backstage will play them in the order they were added.
+ * - Search: Search tracks from Spotify catalog.
+ * - Equalizer: Simple three channel equalizer.
+ * - Output device selection: Ability to select the output device for the audio.
+ */
 class SpotifyBackstage
 {
 public:
+    /**
+     * Ctor.
+     *
+     * @param username Spotify username
+     * @param password Password for username
+     */
     SpotifyBackstage(const std::string& username, const std::string& password);

     ~SpotifyBackstage();

+    /** Get the current state of the equalizer */
     EqState getEqState();

+    /** Get the current play queue */
     std::vector<Track> getPlayQueue();

+    /**
+     * Enqueue a track to the play queue.
+     *
+     * @param uri Spotify URI of the track to enqueue.
+     */
     void enqueue(const std::string& uri);

+    /**
+     * Start playback. The track currently at the head of the play queue will start playing.
+     * Once the track is finished, it's removed from the play queue and the next track in the queue is played.
+     * The playback will continue for as long as there are tracks in the play queue, or stop() is called.
+     */
     void play();

+    /** Stop playback. */
     void stop();

+    /**
+     * Stop the playback, remove the track currently at the head of the play queue from the queue,
+     * and start playing the next track in the queue (if the queue is not empty).
+     */
     void next();

+    /**
+     * Search tracks from the Spotify catalog.
+     *
+     * @param query Search query string.
+     * @param num_results Max number of tracks to return.
+     * @param offset Offset in the full result list from which to start taking the returned tracks.
+     *               This parameter is useful if you want to do more than one search with the same
+     *               query string. For example,
+     *
+     *               Get the first 10 results for "Neil Young":
+     *               search("Neil Young", 10, 0);
+     *
+     *               Get the next 10 results:
+     *               search("Neil Young", 10, 10);
+     */
     std::vector<Track> search(const std::string& query, int num_results, int offset);

+    /**
+     * Set equalizer on/off.
+     *
+     * @param on true = on, false = off.
+     */
     void setEqOn(bool on);

+    /**
+     * Set equalizer gain.
+     *
+     * @gain The gain. 1.0 = 100%.
+     */
     void setGain(double gain);

+    /**
+     * Set equalizer bass channel level.
+     *
+     * @param bass The level. 1.0 = 100%.
+     */
     void setBass(double bass);

+    /**
+     * Set equalizer mid channel level.
+     *
+     * @param mid The level. 1.0 = 100%.
+     */
     void setMid(double mid);

+    /**
+     * Set equalizer treble channel level.
+     *
+     * @param treble The level. 1.0 = 100%.
+     */
     void setTreble(double treble);

+    /** Get the index of the currently selected audio output device. */
     int getCurrentOutputDevice();

+    /**
+     * Get a list of audio output devices available in the system.
+     * The items in the list contain the device's index and name.
+     */
     std::vector<std::pair<int, std::string>> getOutputDevices();

+    /**
+     * Set the audio output device.
+     *
+     * @param dev Index of the device to set.
+     */
     void setOutputDevice(int dev);

 private:
@@ -54,6 +138,10 @@
     std::unique_ptr<Impl> impl_;
 };

+/**
+ * EqState encapsulates the state of the equalizer.
+ * With the gain and the channel levels, value 1.0 = 100%.
+ */
 struct EqState
 {
     EqState(bool on, double g, double b, double m, double t)
@@ -61,13 +149,25 @@
     {
     }

+    /** Is the equalizer on? */
     bool is_on;
+
+    /** Equalizer gain */
     double gain;
+
+    /** Bass channel level */
     double bass;
+
+    /** Mid channel level */
     double mid;
+
+    /** Treble channel level */
     double treble;
 };

+/**
+ * Track contains information of a single Spotify track.
+ */
 struct Track
 {
     Track(const std::string& artist_p, const std::string& album_p, const std::string& track_p,
@@ -76,10 +176,19 @@
     {
     }

+    /** Artist(s) */
     std::string artist;
+
+    /** Album */
     std::string album;
+
+    /** Track name */
     std::string track;
+
+    /** Track duration in seconds */
     int duration_sec;
+
+    /** Track's Spotify URI */
     std::string uri;
 };


Dock: Fix issue with not working settings saving

--- Src/Dock/Storage.cpp
+++ Src/Dock/Storage.cpp
@@ -322,14 +322,13 @@

 bool Storage::load(const wchar* file)
 {
+  filename = file;
   HANDLE hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
   if (hFile == INVALID_HANDLE_VALUE)
     return false;
   uint header;
   bool ret = read(hFile, &header, sizeof(header)) && header == 1 && load(hFile);
   CloseHandle(hFile);
-  if(ret)
-    filename = file;
   return ret;
 }


Disable compaction and rollback interleaving test

There is a sporadic failure in testing interleaving compaction and rollback
task. Disabling it until we resolve this test issue.

Change-Id: I2cae581cd91ed2778cfc40d10be7aea6c8e3b795
Reviewed-on: http://review.couchbase.org/61901
Tested-by: buildbot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Chiyoung Seo <fcffc23db27b19ee4ebba46695ee6b50e09216a2@couchbase.com>

--- tests/functional/compact_functional_test.cc
+++ tests/functional/compact_functional_test.cc
@@ -3409,7 +3409,8 @@
     compaction_daemon_test(20);
     auto_compaction_with_concurrent_insert_test(20);
     compaction_cancellation_test(COMPACTION_CANCEL_MODE);
-    compaction_cancellation_test(COMPACTION_ROLLBACK_MODE);
+    // Disable it temporarily until it is resolved.
+    //compaction_cancellation_test(COMPACTION_ROLLBACK_MODE);

     return 0;
 }


Handle more network cache cases

Handle more network cache cases

--- Misc/ZipArchive.cpp
+++ Misc/ZipArchive.cpp
@@ -2207,6 +2207,15 @@
 }

+static HeapString MakeCacheFilename(const char* fileCache, unsigned char digest[16], uint16_t compressionMethod, uint16_t compressionLevel)
+{
+	char hexBuffer[2 * 16 + 1];
+	for (int i = 0; i < 16; i++)
+		sprintf(hexBuffer + 2 * i,"%02x", digest[i]);
+	return HeapString::Format("%s%c%c%c/%s-%d-%d", fileCache, hexBuffer[0], hexBuffer[1], hexBuffer[2], hexBuffer, compressionMethod, compressionLevel);
+}
+
+
 /**
 **/
 bool ZipArchive::BufferCopy(const void* buffer, uint64_t size, ZipEntryFileHandle& destFile)
@@ -2257,12 +2266,7 @@
 		MD5Update(&c, (unsigned char*)buffer, (unsigned int)size);
 		MD5Final(digest, &c);

-		char hexBuffer[2*16+1];
-		int i;
-		for (i=0; i<16; i++) sprintf(hexBuffer+2*i,"%02x",digest[i]);
-		HeapString hex = hexBuffer;
-
-		cacheFileName = this->fileCache + hex.Sub(0, 3) + "/" + hex;
+		cacheFileName = MakeCacheFilename(this->fileCache, digest, entry->GetCompressionMethod(), 0);

 		if (access(cacheFileName, 0) != -1)
 		{
@@ -2309,7 +2313,7 @@

 /**
 **/
-bool ZipArchive::BufferCopy(const void* buffer, uint64_t size, const char* destFilename, int compressionMethod, int compressionLevel, const time_t* inFileTime)
+bool ZipArchive::BufferCopy(const void* buffer, uint64_t size, const char* destFilename, int _compressionMethod, int compressionLevel, const time_t* inFileTime)
 {
 	HeapString cacheFileName;

@@ -2357,12 +2361,15 @@
 		MD5Update(&c, (unsigned char*)buffer, (unsigned int)size);
 		MD5Final(digest, &c);

-		char hexBuffer[2*16+1];
-		int i;
-		for (i=0; i<16; i++) sprintf(hexBuffer+2*i,"%02x",digest[i]);
-		HeapString hex = hexBuffer;
-
-		cacheFileName = this->fileCache + hex.Sub(0, 3) + "/" + hex;
+		//MD5Init(&c);
+		//MD5Update(&c, (unsigned char*)digest, 16);
+
+		//uint8_t compressionMethod = (uint8_t)_compressionMethod;
+		//MD5Update(&c, (unsigned char*)&compressionMethod, sizeof(compressionMethod));
+
+		//MD5Final(digest, &c);
+
+		cacheFileName = MakeCacheFilename(this->fileCache, digest, _compressionMethod, 0);

 		if (access(cacheFileName, 0) != -1)
 		{
@@ -2387,7 +2394,7 @@
 	}

 	ZipEntryFileHandle fileHandle;
-	if (!FileCreate(destFilename, fileHandle, DEFLATED, compressionLevel, &fileTime))
+	if (!FileCreate(destFilename, fileHandle, _compressionMethod, compressionLevel, &fileTime))
 		return false;

 	if (FileWrite(fileHandle, buffer, size) != size)
@@ -3284,6 +3291,12 @@
 						}
 						continue;
 					} else {
+						delete newArchive;
+#if defined(_MSC_VER)
+						_unlink(newArchiveFileName);
+#else
+						unlink(newArchiveFileName);
+#endif
 						return false;
 					}
 				}
@@ -3307,21 +3320,28 @@

 		// Is this file being copied from another zip archive?
 		int pipePos = info.srcPath.ReverseFind('|');
-		if (pipePos != -1) {
-			HeapString archiveFileName = info.srcPath.Sub(0, pipePos);
-			HeapString entryName = info.srcPath.Sub(pipePos + 1);
-			ZipArchive* cacheDrive = info.sourceArchive ? info.sourceArchive : PFL_OpenArchive(archiveFileName, openArchives, m_flags);
-			if (cacheDrive) {
-				size_t cacheFileEntryIndex = cacheDrive->FindFileEntryIndex(entryName);
-				if (cacheFileEntryIndex == INVALID_FILE_ENTRY)
+		if (pipePos != -1  ||  info.sourceEntryName.IsNotEmpty()) {
+			HeapString archiveFileName;
+			HeapString entryName;
+			if (info.sourceEntryName.IsNotEmpty()) {
+				archiveFileName = info.srcPath;
+				entryName = info.sourceEntryName;
+			} else {
+				archiveFileName = info.srcPath.Sub(0, pipePos);
+				entryName = info.srcPath.Sub(pipePos + 1);
+			}
+			ZipArchive* sourceArchive = info.sourceArchive ? info.sourceArchive : PFL_OpenArchive(archiveFileName, openArchives, SUPPORT_MD5);
+			if (sourceArchive) {
+				size_t sourceFileEntryIndex = sourceArchive->FindFileEntryIndex(entryName);
+				if (sourceFileEntryIndex == INVALID_FILE_ENTRY)
 					continue;

-				ZipEntryInfo* cacheFileEntry = cacheDrive->GetFileEntry(cacheFileEntryIndex);
-				if (!cacheFileEntry)
+				ZipEntryInfo* sourceFileEntry = sourceArchive->GetFileEntry(sourceFileEntryIndex);
+				if (!sourceFileEntry)
 					continue;
-				if (cacheFileEntry->GetCompressionMethod() == info.compressionMethod) {
-					ZipEntryFileHandle cacheFileHandle;
-					if (cacheDrive->FileOpenIndexInternal(cacheFileEntryIndex, cacheFileHandle)) {
+				if (sourceFileEntry->GetCompressionMethod() == info.compressionMethod) {
+					ZipEntryFileHandle sourceFileHandle;
+					if (sourceArchive->FileOpenIndexInternal(sourceFileEntryIndex, sourceFileHandle)) {
 						if (!filenameShown) {
 							if (options->statusUpdateCallback)
 								options->statusUpdateCallback(UPDATING_ARCHIVE, m_filename, options->statusUpdateUserData);
@@ -3330,17 +3350,115 @@
 						if (options->statusUpdateCallback)
 							options->statusUpdateCallback(DIRECT_COPY_FROM_ANOTHER_ARCHIVE, info.entryName, options->statusUpdateUserData);

-						if (activeArchive->FileCopy(cacheFileHandle, info.entryName, &info.lastWriteTime))
+						if (activeArchive->FileCopy(sourceFileHandle, info.entryName, &info.lastWriteTime))
 						{
 //BROKEN						FileRename(entryName, info.entryName);
 							continue;
 						} else {
+							delete newArchive;
+#if defined(_MSC_VER)
+							_unlink(newArchiveFileName);
+#else
+							unlink(newArchiveFileName);
+#endif
 							return false;
 						}
 					}
 				} else {
-					ZipEntryFile cacheFile;
-					if (cacheFile.Open(*cacheDrive, entryName)) {
+					// We're processing a standard file from the disk.  In order to get into this special case
+					// processing block, the following criteria must be met:
+					//
+					// * The file order list wants the file compressed.
+					// * There is a network cache.
+					// * The size is within the network cache minimum size threshold as provided by the options.
+					if (info.compressionMethod != UNCOMPRESSED  &&  networkCache.IsNotEmpty()  &&
+								(info.size == (size_t)-1  ||  info.size >= options->fileCacheSizeThreshold)) {
+						// Do we need a CRC and MD5 update?  If the file order list doesn't provide the CRC
+						// or MD5, we have to calculate it.
+						if (info.lastWriteTime != info.fileTime  ||  info.crc == 0
+#if ZIPARCHIVE_MD5_SUPPORT
+									||  memcmp(info.md5, emptyMD5, sizeof(emptyMD5)) == 0
+#endif // ZIPARCHIVE_MD5_SUPPORT
+								) {
+							info.fileTime = info.lastWriteTime;
+
+							// Did the caller provide a callback to retrieve the checksum?  If so, call it.
+							int found = 0;
+							if (options->retrieveChecksumCallback) {
+								found = options->retrieveChecksumCallback(info.srcPath, &info.crc,
+#if ZIPARCHIVE_MD5_SUPPORT
+										(unsigned char*)&info.md5,
+#else
+										NULL,
+#endif // ZIPARCHIVE_MD5_SUPPORT
+										options->retrieveChecksumUserData);
+							}
+
+#if 0
+							// We still don't have a checksum.  Calculate it ourselves.
+							if (!found) {
+								FILE* file = fopen(info.srcPath, "rb");
+								if (file) {
+									info.crc = ZipArchive_GetFileCRC(file, 0, info.md5);
+									fclose(file);
+								}
+							}
+#endif
+						}
+
+						if (info.crc != 0
+#if ZIPARCHIVE_MD5_SUPPORT
+									&&  memcmp(info.md5, emptyMD5, sizeof(emptyMD5)) != 0
+#endif // ZIPARCHIVE_MD5_SUPPORT
+								) {
+							// Determine if the compressed file is in the provided network cache.
+							//
+							// First, build up the MD5 string.
+							//MD5_CTX c;
+							//MD5Init(&c);
+							//MD5Update(&c, (unsigned char*)info.md5, 16);
+//
+							//uint8_t compressionMethod = (uint8_t)info.compressionMethod;
+							//MD5Update(&c, (unsigned char*)&compressionMethod, sizeof(compressionMethod));
+//
+							//unsigned char digest[16];
+							//MD5Final(digest, &c);
+//
+							// Now build the cache name in the form: abc/abcdef0123456789987654321fedcba
+							cacheFileName = MakeCacheFilename(networkCache, info.md5, info.compressionMethod, 0);
+
+							// Does the compressed exist in the network cache?
+							if (access(cacheFileName, 0) != -1) {
+								// It appears so.  Try and open it.  Compressed network cache entries are
+								// stored as single file entry zips.
+								ZipArchive cacheArchive;
+								if (cacheArchive.Open(cacheFileName, true, SUPPORT_MD5)) {
+									// The zip archive opened successfully.  Now try the file entry itself.
+									ZipEntryFileHandle cacheFileHandle;
+									if (cacheArchive.FileOpenIndex(0, cacheFileHandle)) {
+										// So far so good.  Inform the caller we are updating the zip.
+										if (!filenameShown) {
+											if (options->statusUpdateCallback)
+												options->statusUpdateCallback(UPDATING_ARCHIVE, m_filename, options->statusUpdateUserData);
+											filenameShown = true;
+										}
+										if (options->statusUpdateCallback)
+											options->statusUpdateCallback(COPYING_ENTRY_FROM_CACHE, info.entryName, options->statusUpdateUserData);
+
+										// Perform a raw file copy from the network cache zip to the current zip.
+										if (activeArchive->FileCopy(cacheFileHandle, info.entryName, &info.lastWriteTime)) {
+											// The transfer was successful.  Move on to the next file.
+											continue;
+										}
+										// The transfer failed... move on to the non-network cache version.
+									} // if (cacheArchive.FileOpen(info.entryName, cacheFileHandle))
+								} // if (cacheArchive.Open(cacheFileName))
+							} // if (access(cacheFileName, 0) != -1)
+						} // if networkcache
+					}
+
+					ZipEntryFile sourceFile;
+					if (sourceFile.Open(*sourceArchive, entryName)) {
 						if (!filenameShown) {
 							if (options->statusUpdateCallback)
 								options->statusUpdateCallback(UPDATING_ARCHIVE, m_filename, options->statusUpdateUserData);
@@ -3349,10 +3467,60 @@
 						if (options->statusUpdateCallback)
 							options->statusUpdateCallback(UPDATING_ENTRY, info.entryName, options->statusUpdateUserData);

-						if (activeArchive->FileCopy(cacheFile, info.entryName, info.compressionMethod, info.compressionLevel, &info.lastWriteTime)) {
+						if (activeArchive->FileCopy(sourceFile, info.entryName, info.compressionMethod, info.compressionLevel, &info.lastWriteTime)) {
 //BROKEN						FileRename(entryName, info.entryName);
+							if (!networkCache.IsEmpty()) {
+								// First, build up the MD5 string.
+//								MD5_CTX c;
+//								MD5Init(&c);
+//								MD5Update(&c, (unsigned char*)info.md5, 16);
+//
+//								uint8_t compressionMethod = (uint8_t)info.compressionMethod;
+//								MD5Update(&c, (unsigned char*)&compressionMethod, sizeof(compressionMethod));
+//
+//								unsigned char digest[16];
+//								MD5Final(digest, &c);
+//
+								// Now build the cache name in the form: abc/abcdef0123456789987654321fedcba
+								cacheFileName = MakeCacheFilename(networkCache, info.md5, info.compressionMethod, 0);
+							}
+
+							// If we're using a network cache and we just compressed the file, we need to transfer the
+							// compressed file into the cache.
+							if (cacheFileName.IsNotEmpty()  &&  info.compressionMethod != 0) {
+								// Create all directories leading up to the network cache location the compressed file
+								// is to be put at.
+								PathCreate(cacheFileName);
+
+								// Create a single file zip archive at the network cache location.
+								ZipArchive cacheArchive;
+								if (cacheArchive.Create(cacheFileName, SUPPORT_MD5)) {
+									// Open the zip entry we just compressed.
+									ZipEntryFileHandle srcFileHandle;
+									if (activeArchive->FileOpen(info.entryName, srcFileHandle)) {
+										// Perform a raw transfer of the file straight into the network cache.
+										cacheArchive.FileCopy(srcFileHandle, "contents");
+
+										// Inform the caller of our update.
+										if (!filenameShown) {
+											if (options->statusUpdateCallback)
+												options->statusUpdateCallback(UPDATING_ARCHIVE, m_filename, options->statusUpdateUserData);
+											filenameShown = true;
+										}
+										if (options->statusUpdateCallback)
+											options->statusUpdateCallback(COPYING_ENTRY_TO_CACHE, info.entryName, options->statusUpdateUserData);
+									} // if (FileOpen(info.entryName, srcFileHandle))
+								} // if (cacheArchive.Create(cacheFileName, 0, m_flags))
+							} // if (cacheFileName.IsNotEmpty()  &&  info.compressionMethod != 0)
+
 							continue;
 						} else {
+							delete newArchive;
+#if defined(_MSC_VER)
+							_unlink(newArchiveFileName);
+#else
+							unlink(newArchiveFileName);
+#endif
 							return false;
 						}
 					}
@@ -3367,7 +3535,7 @@
 		// * There is a network cache.
 		// * The size is within the network cache minimum size threshold as provided by the options.
 		else if (info.compressionMethod != UNCOMPRESSED  &&  networkCache.IsNotEmpty()  &&
-					(info.size == 0  ||  info.size >= options->fileCacheSizeThreshold)) {
+					(info.size == (size_t)-1  ||  info.size >= options->fileCacheSizeThreshold)) {
 			// Do we need a CRC and MD5 update?  If the file order list doesn't provide the CRC
 			// or MD5, we have to calculate it.
 			if (info.lastWriteTime != info.fileTime  ||  info.crc == 0
@@ -3402,23 +3570,33 @@
 			// Determine if the compressed file is in the provided network cache.
 			//
 			// First, build up the MD5 string.
-			HeapString hex;
-			char* hexBuffer = hex.GetBuffer(2 * 16 + 1);
-			for (int i = 0; i < 16; ++i) sprintf(hexBuffer + 2 * i, "%02x", info.md5[i]);
-			hex.ReleaseBuffer(2 * 16);
-
+//			MD5_CTX c;
+//			MD5Init(&c);
+//			MD5Update(&c, (unsigned char*)info.md5, 16);
+//
+//			uint8_t compressionMethod = (uint8_t)info.compressionMethod;
+//			MD5Update(&c, (unsigned char*)&compressionMethod, sizeof(compressionMethod));
+//
+//			unsigned char digest[16];
+//			MD5Final(digest, &c);
+//
+//			HeapString hex;
+//			char* hexBuffer = hex.GetBuffer(2 * 16 + 1);
+//			for (int i = 0; i < 16; ++i) sprintf(hexBuffer + 2 * i, "%02x", digest[i]);
+//			hex.ReleaseBuffer(2 * 16);
+//
 			// Now build the cache name in the form: abc/abcdef0123456789987654321fedcba
-			cacheFileName = networkCache + hex.Sub(0, 3) + "/" + hex;
+			cacheFileName = MakeCacheFilename(networkCache, info.md5, info.compressionMethod, 0);

 			// Does the compressed exist in the network cache?
 			if (access(cacheFileName, 0) != -1) {
 				// It appears so.  Try and open it.  Compressed network cache entries are
 				// stored as single file entry zips.
-				ZipArchive cacheDrive;
-				if (cacheDrive.Open(cacheFileName)) {
+				ZipArchive cacheArchive;
+				if (cacheArchive.Open(cacheFileName, true, SUPPORT_MD5)) {
 					// The zip archive opened successfully.  Now try the file entry itself.
 					ZipEntryFileHandle cacheFileHandle;
-					if (cacheDrive.FileOpen(info.entryName, cacheFileHandle)) {
+					if (cacheArchive.FileOpenIndex(0, cacheFileHandle)) {
 						// So far so good.  Inform the caller we are updating the zip.
 						if (!filenameShown) {
 							if (options->statusUpdateCallback)
@@ -3429,20 +3607,35 @@
 							options->statusUpdateCallback(COPYING_ENTRY_FROM_CACHE, info.entryName, options->statusUpdateUserData);

 						// Perform a raw file copy from the network cache zip to the current zip.
-						if (activeArchive->FileCopy(cacheFileHandle, NULL, &info.lastWriteTime)) {
+						if (activeArchive->FileCopy(cacheFileHandle, info.entryName, &info.lastWriteTime)) {
 							// The transfer was successful.  Move on to the next file.
 							continue;
+						} else {
+							int hi = 5;  (void)hi;
 						}
 						// The transfer failed... move on to the non-network cache version.
-					} // if (cacheDrive.FileOpen(info.entryName, cacheFileHandle))
-				} // if (cacheDrive.Open(cacheFileName))
+					} // if (cacheArchive.FileOpenIndex(0, cacheFileHandle))
+					else {
+						int hi = 5;  (void)hi;
+					}
+				} // if (cacheArchive.Open(cacheFileName))
+				else {
+					int hi = 5;  (void)hi;
+				}
 			} // if (access(cacheFileName, 0) != -1)
 		} // if networkcache

 		// Open the file from the disk.
 		DiskFile diskFile;
-		if (!diskFile.Open(info.srcPath))
+		if (!diskFile.Open(info.srcPath, File::MODE_READONLY | File::SHARE_DENY_WRITE)) {
+			delete newArchive;
+#if defined(_MSC_VER)
+			_unlink(newArchiveFileName);
+#else
+			unlink(newArchiveFileName);
+#endif
 			return false;
+		}

 		// Inform the user we are updating the archive.
 		if (!filenameShown) {
@@ -3454,8 +3647,15 @@
 			options->statusUpdateCallback(UPDATING_ENTRY, info.entryName, options->statusUpdateUserData);

 		// Transfer the file from the disk into the archive compressing as we go per the file order info's specification.
-		if (!activeArchive->FileCopy(diskFile, info.entryName, info.compressionMethod, info.compressionLevel, &info.lastWriteTime))
+		if (!activeArchive->FileCopy(diskFile, info.entryName, info.compressionMethod, info.compressionLevel, &info.lastWriteTime)) {
+			delete newArchive;
+#if defined(_MSC_VER)
+			_unlink(newArchiveFileName);
+#else
+			unlink(newArchiveFileName);
+#endif
 			return false;
+		}

 		// We're done with the disk file.  Close it.
 		diskFile.Close();
@@ -3468,13 +3668,13 @@
 			PathCreate(cacheFileName);

 			// Create a single file zip archive at the network cache location.
-			ZipArchive cacheDrive;
-			if (cacheDrive.Create(cacheFileName, m_flags)) {
+			ZipArchive cacheArchive;
+			if (cacheArchive.Create(cacheFileName, SUPPORT_MD5)) {
 				// Open the zip entry we just compressed.
 				ZipEntryFileHandle srcFileHandle;
 				if (activeArchive->FileOpen(info.entryName, srcFileHandle)) {
 					// Perform a raw transfer of the file straight into the network cache.
-					cacheDrive.FileCopy(srcFileHandle);
+					cacheArchive.FileCopy(srcFileHandle, "contents");

 					// Inform the caller of our update.
 					if (!filenameShown) {
@@ -3485,7 +3685,7 @@
 					if (options->statusUpdateCallback)
 						options->statusUpdateCallback(COPYING_ENTRY_TO_CACHE, info.entryName, options->statusUpdateUserData);
 				} // if (FileOpen(info.entryName, srcFileHandle))
-			} // if (cacheDrive.Create(cacheFileName, 0, m_flags))
+			} // if (cacheArchive.Create(cacheFileName, 0, m_flags))
 		} // if (cacheFileName.IsNotEmpty()  &&  info.compressionMethod != 0)
 	} // for (FileOrderList


Added to test harness

Added to test harness

--- portableUnitTests/OTRadioLink/OTSIM900Link.cpp
+++ portableUnitTests/OTRadioLink/OTSIM900Link.cpp
@@ -110,11 +110,13 @@
           collectingCommand = false;
           if(verbose) { fprintf(stderr, "command received: %s\n", command.c_str()); }
           // Respond to particular commands...
-          if("AT" == command) { reply = "AT\r"; }
+          if("AT" == command) { reply = "AT\r"; }  // Relevant states: GET_STATE, RETRY_GET_STATE, START_UP
           // DHD20161101: "No PIN" response (deliberately not typical SIM900 response) resulted in SIGSEGV from not checking getResponse() result for NULL.
           // Should futz/vary the response to check sensitivity.
           // TODO: have at least one response be expected SIM900 answer for no-PIN SIM.
-          else if("AT+CPIN?" == command) { reply = (random() & 1) ? "No PIN" : "OK READY"; }
+          else if("AT+CPIN?" == command) { reply = (random() & 1) ? "No PIN\r" : "OK READY\r"; }  // Relevant states: CHECK_PIN
+          else if("AT+CREG?" == command) { reply = (random() & 1) ? "+CREG: 0,0\r" : "+CREG: 0,5\r"; } // Relevant states: WAIT_FOR_REGISTRATION
+//          else if("AT+CSTT=" == command) { reply = (random() & 1) ? "gbfhs\r" : "\n  OK\r"; } // Relevant states: SET_APN FIXME need to pass OTSIM900Link a config!
           }
         else if(collectingCommand) { command += c; }
         }


Expanded test rig

Expanded test rig

--- portableUnitTests/OTRadioLink/OTSIM900Link.cpp
+++ portableUnitTests/OTRadioLink/OTSIM900Link.cpp
@@ -128,7 +128,15 @@
           if("AT" == command) { reply = "AT\r"; }  // Relevant states: GET_STATE, RETRY_GET_STATE, START_UP
           else if("AT+CPIN?" == command) { reply = /* (random() & 1) ? "No PIN\r" : */ "READY\r"; }  // Relevant states: CHECK_PIN
           else if("AT+CREG?" == command) { reply = /* (random() & 1) ? "+CREG: 0,0\r" : */ "+CREG: 0,5\r"; } // Relevant states: WAIT_FOR_REGISTRATION
-          else if("AT+CSTT=apn" == command) { reply = /* (random() & 1) ? "gbfhs\r" : */ "AT+CSTT\r\n\r\nOK\r"; } // Relevant states: SET_APN
+          else if("AT+CSTT=apn" == command) { reply =  "AT+CSTT\r\n\r\nOK\r"; } // Relevant states: SET_APN
+          else if("AT+CIPSTATUS" == command) { reply = ""; }  // Relevant states: START_GPRS, WAIT_FOR_UDP
+          else if("AT+CIICR" == command) { reply = "AT+CIICR\r\n\r\nOK\r\n"; }  // Relevant states: START_GPRS
+          else if("AT+CIFSR" == command) { reply = "AT+CIFSR\r\n\r\n172.16.101.199\r\n"; }  // Relevant States: GET_IP
+          else if("AT+CIPSTART" == command) { reply = "AT+CIPSTART=\"UDP\",\"0.0.0.0\",\"9999\"\r\n\r\nOK\r\n\r\nCONNECT OK\r\n"; }  // Relevant states: OPEN_UDP fixme command probably wrong
+          else if("AT+CIPSEND=3" == command) { reply = "AT+CIPSEND=3\r\n\r\n>"; }  // Relevant states:  SENDING
+          else if("123" == command) { reply = "123\r\nSEND OK\r\n"; }  // Relevant states: SENDING
+          else if("" == command) { reply = ""; }  // Relevant states:
+          else if("" == command) { reply = ""; }  // Relevant states:
           }
         else if(collectingCommand) { command += c; }
         }


COVERITY: buffer size warning corrected.

--- THerwig/THerwig6.cxx
+++ THerwig/THerwig6.cxx
@@ -184,8 +184,8 @@

    // initialization:
    // type of beams
-   strncpy(HWBMCH.PART1,beam,8);
-   strncpy(HWBMCH.PART2,target,8);
+   strncpy(HWBMCH.PART1,beam, 7);
+   strncpy(HWBMCH.PART2,target, 7);
    // momentum of beams
    HWPROC.PBEAM1=pbeam1;
    HWPROC.PBEAM2=pbeam2;


Remove outdated and misleading code snippet.

--- src/realm/tools/unicode.cpp
+++ src/realm/tools/unicode.cpp
@@ -1,44 +1,3 @@
-
-
-/*
-// This code snippet will generate the collation_order[] table in unicode.cpp::utf8_compare() method. See
-// further documentation there.
-
-const wchar_t end = 0x250;    // up to and including Latin Extended B
-std::vector<wchar_t> vec;
-std::locale l = std::locale("");
-for (size_t t = 0; t < end; t++) {
-    wstring s;
-    s.push_back(wchar_t(t));
-    size_t j;
-    for (j = 0; j < vec.size(); j++) {
-        wstring s2;
-        s2.push_back(vec[j]);
-        bool less = l(s, s2);
-        if (less) {
-            break;
-        }
-    }
-    vec.insert(vec.begin() + j, wchar_t(t));
-}
-
-uint32_t inverse[end];
-for (size_t t = 0; t < end; t++) {
-    int v = vec[t];
-    inverse[v] = t;
-}
-
-std::cout << "static const uint32_t collation_order[] = {\n";
-for (size_t t = 0; t < end; t++) {
-    std::cout << (t == 0 ? "" : ", ") << inverse[t];
-    if (t != 0 && t % 100 == 0)
-        std::cerr << "\n";
-}
-std::cout << "};";
-*/
-
-
-

 // This snippet generates the lowers[] array in unicode.cpp::to_lower(). See further documentation there
 /*


Show datetime

Show datetime

--- src/recordattendancedlg.cpp
+++ src/recordattendancedlg.cpp
@@ -1,6 +1,8 @@
 #include "recordattendancedlg.h"
 #include "ui_recordattendancedlg.h"

+#include <QDateTime>
+#include <QSqlField>
 #include <models/trainingmodel.h>

 RecordAttendanceDlg::RecordAttendanceDlg(QSqlRecord record, QWidget *parent) :
@@ -15,7 +17,9 @@

     connect(ui->btnSave, SIGNAL(clicked()), attendanceModel, SLOT(saveData()));
     connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(close()));
-    //QString trainingDatetime = new TrainingModel().filter()
+
+    QDateTime datetime = record.field("datetime").value().toDateTime();
+    ui->txtTrainingDatetime->setText(datetime.toString(tr("dd.MM.yyyy h:mm")));
 }

 RecordAttendanceDlg::~RecordAttendanceDlg()


Soldier collision bug fixed

Soldier collision bug fixed

--- Motor2D/Soldier.cpp
+++ Motor2D/Soldier.cpp
@@ -161,57 +161,57 @@
 {
 	BROFILER_CATEGORY("DoUpdate_Soldier", Profiler::Color::Pink);
 	// STATE MACHINE ------------------
-		if (App->scene->gamestate == INGAME)
-		{
-			if (soldier_type == AGGRESSIVE)
-			{
-				switch (state)
-				{
-				case S_IDLE:
-				{
-					CheckPlayerPos();
-					Idle();
-					break;
-				}
-				case S_WALKING:
-				{
-					CheckPlayerPos();
-					Walking(dt);
-					break;
-				}
-				case S_DYING:
-				{
-					Die();
-					break;
-				}
-				case S_HIT:
-				{
-					Movebyhit(dt);
-					break;
-				}
-				case S_CHASING:
-				{
-					CheckPlayerPos();
-					Chase(dt);
-					break;
-				}
-				case S_ATTACKING:
-				{
-					Attack();
-					break;
-				}
-				default:
-				{
-					break;
-				}
-				}
-
-
-		}
-
-		collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
-
-	}
+	if (App->scene->gamestate == INGAME)
+	{
+		if (soldier_type == AGGRESSIVE)
+		{
+			switch (state)
+			{
+			case S_IDLE:
+			{
+				CheckPlayerPos();
+				Idle();
+				break;
+			}
+			case S_WALKING:
+			{
+				CheckPlayerPos();
+				Walking(dt);
+				break;
+			}
+			case S_DYING:
+			{
+				Die();
+				break;
+			}
+			case S_HIT:
+			{
+				Movebyhit(dt);
+				break;
+			}
+			case S_CHASING:
+			{
+				CheckPlayerPos();
+				Chase(dt);
+				break;
+			}
+			case S_ATTACKING:
+			{
+				Attack();
+				break;
+			}
+			default:
+			{
+				break;
+			}
+			}
+		}
+		if (collision_feet != nullptr)
+		{
+			collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
+		}
+	}
+
 	else if (App->scene->gamestate == INMENU)
 	{


Update TestingExpansion.cpp

Update TestingExpansion.cpp

Epsilon is double.

--- TestingExpansion.cpp
+++ TestingExpansion.cpp
@@ -8,7 +8,8 @@
 int main()
     {

-    ui n=1000,d=5,epsi,m,l,s;
+    ui n=1000,d=5,m,l,s;
+    double epsi;

     cout<<"Enter the number of Nodes (n) where n > 49 : "<<endl;
     cin>>n;


Fix scene replace

Fix scene replace

--- ouzel/SceneManager.cpp
+++ ouzel/SceneManager.cpp
@@ -24,7 +24,7 @@
             {
                 if (locked)
                 {
-                    nextScene = scene;
+                    nextScene = newScene;
                 }
                 else
                 {


Fixed build for minimal zorba.

Fixed build for minimal zorba.

--- src/zorbatypes/utf8/xqpString.cpp
+++ src/zorbatypes/utf8/xqpString.cpp
@@ -13,6 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+#include <zorba/config.h>
 #ifndef ZORBA_NO_UNICODE
 #include <unicode/regex.h>
 #endif


Removed retTypeStack.

Removed retTypeStack.

--- NULLC/Callbacks.cpp
+++ NULLC/Callbacks.cpp
@@ -20,21 +20,20 @@
 // Number of implicit array
 unsigned int inplaceArrayNum;

-// Stack of variable count top.
+// Stack of variable counts.
 // Used to find how many variables are to be removed when their visibility ends.
 // Also used to know how much space for local variables is required in stack frame.
 FastVector<VarTopInfo>		varInfoTop(64);

+// Stack of function counts.
+// Used to find how many functions are to be removed when their visibility ends.
+FastVector<unsigned int>	funcInfoTop(64);
+
 // Cycle depth stack is used to determine what is the depth of the loop when compiling operators break and continue
 FastVector<unsigned int>	cycleDepth(64);

-//         .
-//            .
-FastVector<unsigned int>			funcInfoTop(64);
-
-// ,    ,   .
-//
-FastVector<TypeInfo*>		retTypeStack(64);
+// Stack of functions that are being defined at the moment
+FastVector<FunctionInfo*>	currDefinedFunc(64);

 //
 TypeInfo*	currType = NULL;
@@ -43,8 +42,6 @@

 //
 TypeInfo *newType = NULL;
-
-FastVector<FunctionInfo*>	currDefinedFunc(64);

 unsigned int	TypeInfo::buildInSize = 0;
 ChunkedStackPool<4092> TypeInfo::typeInfoPool;
@@ -644,27 +641,33 @@
 	int localReturn = currDefinedFunc.size() != 0;

 	TypeInfo *realRetType = nodeList.back()->typeInfo;
-	if(!retTypeStack.back() && currDefinedFunc.size() != 0)
-	{
-		retTypeStack.back() = realRetType;
-		currDefinedFunc.back()->retType = realRetType;
-		currDefinedFunc.back()->funcType = GetFunctionType(currDefinedFunc.back());
-	}
-	if(retTypeStack.back() && (retTypeStack.back()->type == TypeInfo::TYPE_COMPLEX || realRetType->type == TypeInfo::TYPE_COMPLEX) && retTypeStack.back() != realRetType)
-	{
-		sprintf(callbackError, "ERROR: function returns %s but supposed to return %s", realRetType->GetFullTypeName(), retTypeStack.back()->GetFullTypeName());
-		ThrowError(callbackError, pos);
-	}
-	if(retTypeStack.back() && retTypeStack.back()->type == TypeInfo::TYPE_VOID && realRetType != typeVoid)
-		ThrowError("ERROR: function returning a value", pos);
-	if(retTypeStack.back() && retTypeStack.back() != typeVoid && realRetType == typeVoid)
-	{
-		sprintf(callbackError, "ERROR: function should return %s", retTypeStack.back()->GetFullTypeName());
-		ThrowError(callbackError, pos);
-	}
-	if(!retTypeStack.back() && realRetType == typeVoid)
-		ThrowError("ERROR: global return cannot accept void", pos);
-	nodeList.push_back(new NodeReturnOp(localReturn, retTypeStack.back()));
+	TypeInfo *expectedType = NULL;
+	if(currDefinedFunc.size() != 0)
+	{
+		if(!currDefinedFunc.back()->retType)
+		{
+			currDefinedFunc.back()->retType = realRetType;
+			currDefinedFunc.back()->funcType = GetFunctionType(currDefinedFunc.back());
+		}
+		expectedType = currDefinedFunc.back()->retType;
+		if((expectedType->type == TypeInfo::TYPE_COMPLEX || realRetType->type == TypeInfo::TYPE_COMPLEX) && expectedType != realRetType)
+		{
+			sprintf(callbackError, "ERROR: function returns %s but supposed to return %s", realRetType->GetFullTypeName(), expectedType->GetFullTypeName());
+			ThrowError(callbackError, pos);
+		}
+		if(expectedType->type == TypeInfo::TYPE_VOID && realRetType != typeVoid)
+			ThrowError("ERROR: function returning a value", pos);
+		if(expectedType != typeVoid && realRetType == typeVoid)
+		{
+			sprintf(callbackError, "ERROR: function should return %s", expectedType->GetFullTypeName());
+			ThrowError(callbackError, pos);
+		}
+	}else{
+		if(currDefinedFunc.size() == 0 && realRetType == typeVoid)
+			ThrowError("ERROR: global return cannot accept void", pos);
+		expectedType = realRetType;
+	}
+	nodeList.push_back(new NodeReturnOp(localReturn, expectedType));
 	nodeList.back()->SetCodeInfo(pos, end);
 }

@@ -881,7 +884,7 @@
 		}

 		//      ,
-		if((int)retTypeStack.size() > 1 && (currDefinedFunc.back()->type == FunctionInfo::LOCAL) && i < (int)varInfoTop[currDefinedFunc.back()->vTopSize].activeVarCnt)
+		if(currDefinedFunc.size() != 0 && (currDefinedFunc.back()->type == FunctionInfo::LOCAL) && i < (int)varInfoTop[currDefinedFunc.back()->vTopSize].activeVarCnt)
 		{
 			FunctionInfo *currFunc = currDefinedFunc.back();
 			//
@@ -1349,7 +1352,6 @@
 	}
 	funcInfo.push_back(new FunctionInfo(funcNameCopy));
 	funcInfo.back()->vTopSize = (unsigned int)varInfoTop.size();
-	retTypeStack.push_back(currType);
 	funcInfo.back()->retType = currType;
 	if(newType)
 		funcInfo.back()->type = FunctionInfo::THISCALL;
@@ -1440,7 +1442,6 @@
 		currDefinedFunc.back()->retType = typeVoid;
 		currDefinedFunc.back()->funcType = GetFunctionType(currDefinedFunc.back());
 	}
-	retTypeStack.pop_back();
 	currDefinedFunc.pop_back();

 	// If function is local, create function parameters block
@@ -1919,9 +1920,6 @@

 	cycleDepth.clear();
 	cycleDepth.push_back(0);
-
-	retTypeStack.clear();
-	retTypeStack.push_back(NULL);	//global return can return anything
 }

 void CallbackDeinitialize()


Compiler fixes.

Compiler fixes.

Division by zero is allowed for float and double types during constant folding.
Class members are captured correctly inside a local member function.
Local function extra parameter type is set to closure type instead of "int ref".

--- NULLC/Callbacks.cpp
+++ NULLC/Callbacks.cpp
@@ -510,12 +510,6 @@
 		return a - b;
 	if(cmd == cmdMul)
 		return a * b;
-	if(cmd == cmdDiv)
-	{
-		if(b == 0)
-			ThrowError(CodeInfo::lastKnownStartPos, "ERROR: division by zero during constant folding");
-		return a / b;
-	}
 	if(cmd == cmdPow)
 		return (T)pow((double)a, (double)b);
 	if(cmd == cmdLess)
@@ -541,6 +535,12 @@
 }
 template<> int optDoSpecial<>(CmdID cmd, int a, int b)
 {
+	if(cmd == cmdDiv)
+	{
+		if(b == 0)
+			ThrowError(CodeInfo::lastKnownStartPos, "ERROR: division by zero during constant folding");
+		return a / b;
+	}
 	if(cmd == cmdShl)
 		return a << b;
 	if(cmd == cmdShr)
@@ -568,6 +568,12 @@
 }
 template<> long long optDoSpecial<>(CmdID cmd, long long a, long long b)
 {
+	if(cmd == cmdDiv)
+	{
+		if(b == 0)
+			ThrowError(CodeInfo::lastKnownStartPos, "ERROR: division by zero during constant folding");
+		return a / b;
+	}
 	if(cmd == cmdShl)
 		return a << b;
 	if(cmd == cmdShr)
@@ -595,6 +601,8 @@
 }
 template<> double optDoSpecial<>(CmdID cmd, double a, double b)
 {
+	if(cmd == cmdDiv)
+		return a / b;
 	if(cmd == cmdMod)
 		return fmod(a,b);
 	if(cmd == cmdShl)
@@ -978,8 +986,9 @@
 		VariableInfo *vInfo = *info;
 		if(!vInfo->varType)
 			ThrowError(pos, "ERROR: variable '%.*s' is being used while its type is unknown", varName.end-varName.begin, varName.begin);
-		if(newType && currDefinedFunc.back()->type == FunctionInfo::THISCALL && vInfo->isGlobal)
-		{
+		if(newType && vInfo->isGlobal)
+		{
+			assert(currDefinedFunc.back()->type != FunctionInfo::NORMAL);
 			TypeInfo::MemberVariable *curr = newType->firstVariable;
 			for(; curr; curr = curr->next)
 				if(curr->nameHash == hash)
@@ -990,7 +999,15 @@
 				FunctionInfo *currFunc = currDefinedFunc.back();

 				TypeInfo *temp = CodeInfo::GetReferenceType(newType);
-				CodeInfo::nodeList.push_back(new NodeGetAddress(NULL, currFunc->allParamSize, false, temp));
+				if(currDefinedFunc.back()->type == FunctionInfo::LOCAL)
+				{
+					// For local function, add "this" to context and get it from upvalue
+					assert(currDefinedFunc[0]->type == FunctionInfo::THISCALL);
+					FunctionInfo::ExternalInfo *external = AddFunctionExternal(currFunc, currDefinedFunc[0]->extraParam);
+					CodeInfo::nodeList.push_back(new NodeGetUpvalue(currFunc, currFunc->allParamSize, external->closurePos, CodeInfo::GetReferenceType(vInfo->varType)));
+				}else{
+					CodeInfo::nodeList.push_back(new NodeGetAddress(NULL, currFunc->allParamSize, false, temp));
+				}
 				CodeInfo::nodeList.push_back(new NodeDereference());
 				CodeInfo::nodeList.push_back(new NodeShiftAddress(curr));
 				return;
@@ -1707,7 +1724,10 @@
 		lastFunc->parentClass = newType;
 	}
 	if(newType ? varInfoTop.size() > 2 : varInfoTop.size() > 1)
+	{
 		lastFunc->type = FunctionInfo::LOCAL;
+		lastFunc->parentClass = NULL;
+	}
 	if(funcName[0] != '$' && !(chartype_table[(unsigned char)funcName[0]] & ct_start_symbol))
 		lastFunc->visible = false;
 	currDefinedFunc.push_back(lastFunc);
@@ -1926,6 +1946,7 @@

 		// Create a pointer to array
 		currType = CodeInfo::GetReferenceType(closureType);
+		lastFunc.extraParam->varType = currType;
 		void *varInfo = AddVariable(pos, InplaceStr(hiddenHame, length));

 		// Allocate array in dynamic memory


Relaxed umeyama test. Problem was ill-posed if linear part was scaled with very small number. This should fix bug 744.

--- test/umeyama.cpp
+++ test/umeyama.cpp
@@ -130,10 +130,11 @@

   // MUST be positive because in any other case det(cR_t) may become negative for
   // odd dimensions!
-  const Scalar c = abs(internal::random<Scalar>());
+  // Also if c is to small compared to t.norm(), problem is ill-posed (cf. Bug 744)
+  const Scalar c = internal::random<Scalar>(0.5, 2.0);

   FixedMatrix R = randMatrixSpecialUnitary<Scalar>(dim);
-  FixedVector t = Scalar(50)*FixedVector::Random(dim,1);
+  FixedVector t = Scalar(32)*FixedVector::Random(dim,1);

   HomMatrix cR_t = HomMatrix::Identity(dim+1,dim+1);
   cR_t.block(0,0,dim,dim) = c*R;
@@ -149,9 +150,9 @@

   HomMatrix cR_t_umeyama = umeyama(src_block, dst_block);

-  const Scalar error = ( cR_t_umeyama*src - dst ).array().square().sum();
+  const Scalar error = ( cR_t_umeyama*src - dst ).squaredNorm();

-  VERIFY(error < Scalar(10)*std::numeric_limits<Scalar>::epsilon());
+  VERIFY(error < Scalar(16)*std::numeric_limits<Scalar>::epsilon());
 }

 void test_umeyama()


begin to think about recursive variant

begin to think about recursive variant

--- test/variant.cpp
+++ test/variant.cpp
@@ -601,4 +601,20 @@
 	BOOST_CHECK_EQUAL((Si::alignment_of<std::string>::value + sizeof(std::string)), sizeof(Si::variant<std::string, Si::nothing>));
 	BOOST_CHECK_EQUAL((sizeof(unsigned char) + sizeof(Si::nothing)), sizeof(Si::variant<Si::nothing, Si::none_t>));
 }
+
+struct leaf
+{
+};
+
+struct tree : Si::variant<leaf, std::vector<tree>>
+{
+	typedef Si::variant<leaf, std::vector<tree>> base;
+};
+
+BOOST_AUTO_TEST_CASE(variant_recursive)
+{
+	tree::base t;
+	t = leaf();
+	t = std::vector<tree>();
+}
 #endif


When preparing field defaults, give them names

Summary: [Thrift] When preparing field defaults, give them names based on the fields' names.

Reviewed By: vitaut

Differential Revision: D17518829

fbshipit-source-id: 9f77f06dd8c2d338ab7342cd6ecc6276627b783c

--- thrift/compiler/generate/t_mstch_objects.cc
+++ thrift/compiler/generate/t_mstch_objects.cc
@@ -466,8 +466,11 @@
         dynamic_cast<t_struct const*>(const_value_->get_ttype());
     for (auto member : const_value_->get_map()) {
       auto const field = strct->get_member(member.first->get_string());
-      constants.push_back(
-          new t_const(nullptr, field->get_type(), "", member.second->clone()));
+      constants.push_back(new t_const(
+          nullptr,
+          field->get_type(),
+          field->get_name(),
+          member.second->clone()));
       idx.push_back(field->get_key());
       field_names.push_back(field->get_name());
     }


Add enum class to TSPEC array

Add enum class to TSPEC array

Summary: For enums, this adds the enum class so external tools can query and validate enums
@override-unit-failures

Test Plan: build, regenerate thrift files, confirm TSPEC is structured properly

Reviewed By: alandau@fb.com

FB internal diff: D1214173

--- thrift/compiler/generate/t_php_generator.cc
+++ thrift/compiler/generate/t_php_generator.cc
@@ -957,8 +957,12 @@
   t = get_true_type(t);
   indent(out) << "'type' => " << type_to_enum(t) << "," << endl;

-  if (t->is_base_type() || t->is_enum()) {
+  if (t->is_base_type()) {
     // Noop, type is all we need
+  } else if (t->is_enum()) {
+    t_enum* tenum = (t_enum*) t;
+    indent(out) << "'enum' => '" << php_namespace(tenum->get_program())
+                << tenum->get_name() << "'," << endl;
   } else if (t->is_struct() || t->is_xception()) {
     indent(out) << "'class' => '" << php_namespace(t->get_program()) << t->get_name() <<"'," << endl;
   } else if (t->is_map()) {


Add nimble implementation of IOBuf binary field (10/n)

Reviewed By: vitaut

Differential Revision: D15203401

fbshipit-source-id: 385fc7829c3feea39290efe6adf954af855d71d2

--- thrift/lib/cpp2/protocol/NimbleProtocol.tcc
+++ thrift/lib/cpp2/protocol/NimbleProtocol.tcc
@@ -191,6 +191,22 @@
   return 0;
 }

+inline uint32_t NimbleProtocolWriter::writeBinary(
+    const std::unique_ptr<folly::IOBuf>& str) {
+  if (!str) {
+    encodeComplexTypeMetadata(0);
+    return 0;
+  }
+  return writeBinary(*str);
+}
+
+inline uint32_t NimbleProtocolWriter::writeBinary(const folly::IOBuf& str) {
+  size_t size = str.computeChainDataLength();
+  encodeComplexTypeMetadata(size);
+  encoder_.encodeBinary(str.data(), size);
+  return 0;
+}
+
 /**
  * Functions that return the serialized size
  */
@@ -434,6 +450,23 @@
 template <typename StrType>
 inline void NimbleProtocolReader::readBinary(StrType& str) {
   readString(str);
+}
+
+inline void NimbleProtocolReader::readBinary(
+    std::unique_ptr<folly::IOBuf>& str) {
+  if (!str) {
+    str = std::make_unique<folly::IOBuf>();
+  }
+  readBinary(*str);
+}
+
+inline void NimbleProtocolReader::readBinary(folly::IOBuf& str) {
+  uint32_t size = readComplexTypeSize(ComplexType::STRINGY);
+
+  if (size > static_cast<uint32_t>(string_limit_)) {
+    TProtocolException::throwExceededSizeLimit();
+  }
+  decoder_.nextBinary(str, size);
 }

 inline void NimbleProtocolReader::skip(TType type) {


Initialize mcps_indication status

Initialize mcps_indication status

_mcps_indication.status is not initialized properly and it can cause incorrect
status value to be returned.

--- features/lorawan/lorastack/mac/LoRaMac.cpp
+++ features/lorawan/lorastack/mac/LoRaMac.cpp
@@ -292,6 +292,7 @@
     _mcps_indication.is_ack_recvd = false;
     _mcps_indication.dl_frame_counter = 0;
     _mcps_indication.type = MCPS_UNCONFIRMED;
+    _mcps_indication.status = LORAMAC_EVENT_INFO_STATUS_OK;

     if (_device_class != CLASS_C) {
         _lora_phy.put_radio_to_sleep();


Moves loading of OrionAssist.dll before others plugins from Client.cuo

--- OrionUO/OrionUO.cpp
+++ OrionUO/OrionUO.cpp
@@ -1576,13 +1576,12 @@
     }
     else
     {
+        LOG("Failed to LoadLibrary %s\n", CStringFromPath(libpath));
 #if USE_WISP
-        auto errorCode = GetLastError();
+        LOG("Error code: %i\n", GetLastError());
 #else
-        auto errorCode = errno;
+        LOG("Error code: %s\n", SDL_GetError());
 #endif
-        LOG("Failed to LoadLibrary %s\n", CStringFromPath(libpath));
-        LOG("Error code: %i\n", errorCode);
     }
 }
 //----------------------------------------------------------------------------------
@@ -1598,6 +1597,8 @@
     g_PluginClientInterface.PathFinder = &g_Interface_PathFinder;
     g_PluginClientInterface.FileManager = &g_Interface_FileManager;

+    ParseCommandLine();
+
     STRING_LIST libName;
     STRING_LIST functions;
     UINT_LIST flags;
@@ -1627,8 +1628,6 @@

     IFOR (i, 0, (int)libName.size())
         LoadPlugin(g_App.ExeFilePath(libName[i].c_str()), functions[i], flags[i]);
-
-    ParseCommandLine();

     if (g_PluginManager.m_Items != NULL)
     {


Using the previous min-canonical

Using the previous min-canonical

--- nthash.hpp
+++ nthash.hpp
@@ -200,28 +200,29 @@

 // canonical ntHash, base function
 inline uint64_t NTC64(const char * kmerSeq, const unsigned k) {
-    return (getFhval(kmerSeq, k) ^ getRhval(kmerSeq, k));
+	uint64_t fhVal=0, rhVal=0;
+	fhVal=getFhval(kmerSeq, k);
+	rhVal=getRhval(kmerSeq, k);
+    return (rhVal<fhVal)? rhVal : fhVal;
 }

 // canonical ntHash
 inline uint64_t NTC64(const char * kmerSeq, const unsigned k, uint64_t& fhVal, uint64_t& rhVal) {
     fhVal = getFhval(kmerSeq, k);
     rhVal = getRhval(kmerSeq, k);
-    return (rhVal^fhVal);
+    return (rhVal<fhVal)? rhVal : fhVal;
 }

 // canonical ntHash for sliding k-mers
 inline uint64_t NTC64(uint64_t& fhVal, uint64_t& rhVal, const unsigned char charOut, const unsigned char charIn, const unsigned k) {
     fhVal = rol(fhVal, 1) ^ rol(seedTab[charOut], k) ^ seedTab[charIn];
     rhVal = ror(rhVal, 1) ^ ror(seedTab[charOut+cpOff], 1) ^ rol(seedTab[charIn+cpOff], k-1);
-    return rhVal ^ fhVal;
+    return (rhVal<fhVal)? rhVal : fhVal;
 }

 // canonical ntHash with seeding option
 inline uint64_t NTC64(const char * kmerSeq, const unsigned k, const unsigned seed) {
-    uint64_t hVal=0;
-    for(unsigned i=0; i<k; i++)
-        hVal ^= rol(seedTab[(unsigned char)kmerSeq[i]], k-1-i);
+    uint64_t hVal = NTC64(kmerSeq,k);
     hVal *= seed ^ k * multiSeed;
     hVal ^= hVal >> multiShift;
     return hVal;
@@ -257,7 +258,7 @@
         fhVal ^= msTab[(unsigned char)kmerSeq[i]][(k-1-i)%64];
         rhVal ^= msTab[(unsigned char)kmerSeq[i]+cpOff][i%64];
     }
-    return (rhVal^fhVal);
+    return (rhVal<fhVal)? rhVal : fhVal;
 }

 // canonical ntHash using pre-computed seed matrix (msTab)
@@ -267,24 +268,19 @@
         fhVal ^= msTab[(unsigned char)kmerSeq[i]][(k-1-i)%64];
         rhVal ^= msTab[(unsigned char)kmerSeq[i]+cpOff][i%64];
     }
-    return (rhVal^fhVal);
+    return (rhVal<fhVal)? rhVal : fhVal;
 }

 // canonical ntHash for sliding k-mers using pre-computed seed matrix (msTab)
 inline uint64_t NTPC64(uint64_t& fhVal, uint64_t& rhVal, const unsigned char charOut, const unsigned char charIn, const unsigned k) {
     fhVal = rol(fhVal, 1) ^ rol(seedTab[charOut], k) ^ seedTab[charIn];
-    rhVal = ror(rhVal, 1) ^ ror(seedTab[charOut+cpOff], 1) ^ rol(seedTab[charIn+cpOff], k-1);
-    return (rhVal^fhVal);
+    rhVal = ror(rhVal, 1) ^ ror(seedTab[charOut+cpOff], 1) ^ rol(seedTab[charIn+cpOff], k-1);
+    return (rhVal<fhVal)? rhVal : fhVal;
 }

 // canonical ntHash with seeding option using pre-computed seed matrix (msTab)
 inline uint64_t NTPC64(const char * kmerSeq, const unsigned k, const unsigned seed) {
-    uint64_t fhVal=0, rhVal=0, hVal=0;
-    for(unsigned i=0; i<k; i++) {
-        fhVal ^= msTab[(unsigned char)kmerSeq[i]][(k-1-i)%64];
-        rhVal ^= msTab[(unsigned char)kmerSeq[i]+cpOff][i%64];
-    }
-    hVal = rhVal^fhVal;
+    uint64_t hVal = NTPC64(kmerSeq,k);
     hVal *= seed ^ k * multiSeed;
     hVal ^= hVal >> multiShift;
     return hVal;


change TempFilename() to TempFileName().

git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@7341 27541ba8-7e3a-0410-8455-c3a389f83636

--- proof/src/TCondor.cxx
+++ proof/src/TCondor.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proof:$Name:  $:$Id: TCondor.cxx,v 1.4 2003/09/04 23:19:31 rdm Exp $
+// @(#)root/proof:$Name:  $:$Id: TCondor.cxx,v 1.5 2003/09/23 08:54:50 rdm Exp $
 // Author: Maarten Ballintijn   06/12/03

 /*************************************************************************
@@ -108,7 +108,7 @@
    PDB(kCondor,1) Info("ClaimVM","command: %s returned %d", claimCmd.Data(), r);

    TString jobad("jobad");
-   FILE *jf = gSystem->TempFilename(jobad);
+   FILE *jf = gSystem->TempFileName(jobad);

    if (jf == 0) return 0;


discovered during #105577#: wrong usage of ::rtl::OUString::copy corrected

--- toolkit/source/controls/unocontrolmodel.cxx
+++ toolkit/source/controls/unocontrolmodel.cxx
@@ -2,9 +2,9 @@
  *
  *  $RCSfile: unocontrolmodel.cxx,v $
  *
- *  $Revision: 1.30 $
- *
- *  last change: $Author: fs $ $Date: 2002-10-08 12:32:43 $
+ *  $Revision: 1.31 $
+ *
+ *  last change: $Author: fs $ $Date: 2002-12-02 10:09:04 $
  *
  *  The Contents of this file are made available subject to the terms of
  *  either of the following licenses
@@ -426,14 +426,21 @@

                 // extract the bank symbol
                 sal_Int32 nSepPos = sDefaultCurrency.indexOf( '-' );
-                ::rtl::OUString sBankSymbol = sDefaultCurrency.copy( 0, nSepPos );
-                sDefaultCurrency = sDefaultCurrency.copy( nSepPos + 1 );
+                ::rtl::OUString sBankSymbol;
+                if ( nSepPos >= 0 )
+                {
+                    sBankSymbol = sDefaultCurrency.copy( 0, nSepPos );
+                    sDefaultCurrency = sDefaultCurrency.copy( nSepPos + 1 );
+                }

                 // the remaming is the locale
                 Locale aLocale;
                 nSepPos = sDefaultCurrency.indexOf( '-' );
-                aLocale.Language = sDefaultCurrency.copy( 0, nSepPos );
-                aLocale.Country = sDefaultCurrency.copy( nSepPos + 1 );
+                if ( nSepPos >= 0 )
+                {
+                    aLocale.Language = sDefaultCurrency.copy( 0, nSepPos );
+                    aLocale.Country = sDefaultCurrency.copy( nSepPos + 1 );
+                }

                 LocaleDataWrapper aLocaleInfo( ::comphelper::getProcessServiceFactory(), aLocale );
                 if ( !sBankSymbol.getLength() )


improve corpus format support

improve corpus format support

--- src/resembla_regression.hpp
+++ src/resembla_regression.hpp
@@ -39,12 +39,12 @@
 public:
     ResemblaRegression(size_t max_candidate,
             std::shared_ptr<FeatureExtractor> feature_extractor, std::shared_ptr<ScoreFunction> score_func,
-            std::string corpus_path = "", size_t feature_col = 2):
+            std::string corpus_path = "", size_t text_col = 1, size_t features_col = 2):
         max_candidate(max_candidate), preprocess(feature_extractor), score_func(score_func),
         reranker(), preprocess_corpus(!corpus_path.empty())
     {
         if(preprocess_corpus){
-            loadCorpusFeatures(corpus_path, feature_col);
+            loadCorpusFeatures(corpus_path, text_col, features_col);
         }
     }

@@ -73,7 +73,8 @@
             if(p.first == primary_resembla_name){
                 continue;
             }
-            for(auto r: p.second->eval(query, candidate_texts, threshold / 2.0, max_candidate * 2)){
+            for(auto r: p.second->eval(query, candidate_texts, 0.0, 0)){
+                candidate_features[r.text][p.first] = Feature::toText(r.score);
                 candidate_features[r.text][p.first] = Feature::toText(r.score);
             }
         }
@@ -96,7 +97,7 @@
         }

         for(const auto& p: resemblas){
-            for(const auto& r: p.second->eval(query, targets, threshold / 2.0, max_response * 2)){
+            for(const auto& r: p.second->eval(query, targets, 0.0, 0)){
                 candidate_features[r.text][p.first] = Feature::toText(r.score);
             }
         }
@@ -105,7 +106,44 @@
     }

 protected:
-    std::vector<output_type> eval(const string_type& query, const std::unordered_map<string_type, StringFeatureMap>& candidate_features,
+    using WorkData = std::pair<string_type, typename FeatureExtractor::output_type>;
+
+    std::unordered_map<std::string, std::shared_ptr<ResemblaInterface>> resemblas;
+    std::string primary_resembla_name;
+    const size_t max_candidate;
+
+    const std::shared_ptr<FeatureExtractor> preprocess;
+    const std::shared_ptr<ScoreFunction> score_func;
+    const Reranker<string_type> reranker;
+
+    const bool preprocess_corpus;
+    std::unordered_map<string_type, typename FeatureExtractor::output_type> corpus_features;
+
+    void loadCorpusFeatures(const std::string& corpus_path, size_t text_col, size_t features_col)
+    {
+        std::ifstream ifs(corpus_path);
+        if(ifs.fail()){
+            throw std::runtime_error("input file is not available: " + corpus_path);
+        }
+
+        while(ifs.good()){
+            std::string line;
+            std::getline(ifs, line);
+            if(ifs.eof() || line.length() == 0){
+                break;
+            }
+            auto columns = split(line, '\t');
+            if(text_col - 1 < columns.size()){
+                std::string raw_features =
+                    features_col - 1 < columns.size() ? columns[features_col - 1] : "";
+                corpus_features[cast_string<string_type>(columns[text_col - 1])] =
+                    (*preprocess)(columns[text_col - 1], raw_features);
+            }
+        }
+    }
+
+    std::vector<output_type> eval(const string_type& query,
+            const std::unordered_map<string_type, StringFeatureMap>& candidate_features,
             double threshold, size_t max_response) const
     {
         // prepare data for reranking
@@ -122,38 +160,6 @@
         }
         return results;
     }
-
-    using WorkData = std::pair<string_type, typename FeatureExtractor::output_type>;
-
-    std::unordered_map<std::string, std::shared_ptr<ResemblaInterface>> resemblas;
-    std::string primary_resembla_name;
-    const size_t max_candidate;
-
-    const std::shared_ptr<FeatureExtractor> preprocess;
-    const std::shared_ptr<ScoreFunction> score_func;
-    const Reranker<string_type> reranker;
-
-    const bool preprocess_corpus;
-    std::unordered_map<string_type, typename FeatureExtractor::output_type> corpus_features;
-
-    void loadCorpusFeatures(const std::string& corpus_path, size_t features_col)
-    {
-        std::ifstream ifs(corpus_path);
-        if(ifs.fail()){
-            throw std::runtime_error("input file is not available: " + corpus_path);
-        }
-        while(ifs.good()){
-            std::string line;
-            std::getline(ifs, line);
-            if(ifs.eof() || line.length() == 0){
-                break;
-            }
-            auto columns = split(line, '\t');
-            if(features_col - 1 < columns.size()){
-                corpus_features[cast_string<string_type>(columns[0])] = (*preprocess)(columns[0], columns[features_col - 1]);
-            }
-        }
-    }
 };

 }


Fixed possible wrong index usage

Fixed possible wrong index usage

--- TranslatorHelper.cpp
+++ TranslatorHelper.cpp
@@ -61,6 +61,9 @@
 void TranslatorHelper::newItem (bool forceRotate) {
   triesLeft_ = scripts_.size ();
   currentIndex_ = forceRotate ? currentIndex_ + 1 : 0;
+  if (currentIndex_ >= scripts_.size ()) {
+    currentIndex_ = 0;
+  }
 }

 QString TranslatorHelper::nextScript () {
@@ -74,7 +77,10 @@
 }

 QString TranslatorHelper::currentScript () const {
-  return (triesLeft_ > 0 ? scripts_.at (currentIndex_) : QString ());
+  if (triesLeft_ > 0 && currentIndex_ < scripts_.size ()) {
+    return scripts_.at (currentIndex_);
+  }
+  return QString ();
 }

 bool TranslatorHelper::gotScripts () const {


tools/extra_defs_gen/generate_extra_defs.cc: Update some comments

* tools/extra_defs_gen/generate_extra_defs.cc: Change comments stating
that get_properties() fails for GVolume. GVolume is an ordinary GInterface.
If the first call is get_properties(G_TYPE_VOLUME), it fails if glib
bug #465631 has not been fixed.

--- tools/extra_defs_gen/generate_extra_defs.cc
+++ tools/extra_defs_gen/generate_extra_defs.cc
@@ -23,6 +23,9 @@
 #include "generate_extra_defs.h"
 #include <algorithm>

+// Until the glib bug https://bugzilla.gnome.org/show_bug.cgi?id=465631
+// is fixed, get_properties() must be called for a GObject before it's
+// called for a GInterface.
 std::string get_properties(GType gtype)
 {
   std::string strResult;
@@ -45,19 +48,21 @@
   else if (G_TYPE_IS_INTERFACE(gtype))
   {
     gpointer pGInterface = g_type_default_interface_ref(gtype);
-    if(pGInterface) //We check because this fails for G_TYPE_VOLUME, for some reason.
+    if(pGInterface)
     {
       ppParamSpec = g_object_interface_list_properties(pGInterface, &iCount);
       g_type_default_interface_unref(pGInterface);

       if(!ppParamSpec)
       {
-        strResult +=  ";; Warning: g_object_interface_list_properties() returned NULL for " + std::string(g_type_name(gtype)) + "\n";
+        strResult += ";; Warning: g_object_interface_list_properties() returned NULL for " + std::string(g_type_name(gtype)) + "\n";
       }
     }
-  }
-
-  //This extra check avoids an occasional crash, for instance for GVolume
+    else
+      strResult += ";; Warning: g_type_default_interface_ref() returned NULL for " + std::string(g_type_name(gtype)) + "\n";
+  }
+
+  //This extra check avoids an occasional crash
   if(!ppParamSpec)
     iCount = 0;

@@ -211,7 +216,7 @@
           GType typeParamMangled = pParameters[i];

           //Parameter name:
-          //TODO: How can we get the real parameter name?
+          //We can't get the real parameter name from the GObject system. It's not registered with g_signal_new().
           gchar* pchNum = g_strdup_printf("%d", i);
           std::string strParamName = "p" + std::string(pchNum);
           g_free(pchNum);
@@ -219,15 +224,15 @@

           //Just like above, for the return type:
           std::string strTypeName = get_type_name_signal( typeParamMangled & ~G_SIGNAL_TYPE_STATIC_SCOPE, is_a_pointer_func ); //The type is mangled with a flag. Hacky.
-          //bool bReturnTypeHasStaticScope = (typeParamMangled & G_SIGNAL_TYPE_STATIC_SCOPE) == G_SIGNAL_TYPE_STATIC_SCOPE;
+          //bool bTypeHasStaticScope = (typeParamMangled & G_SIGNAL_TYPE_STATIC_SCOPE) == G_SIGNAL_TYPE_STATIC_SCOPE;

           strResult += "    '(\"" + strTypeName + "\" \"" + strParamName + "\")\n";
         }

-        strResult += "  )\n"; //close (properties
+        strResult += "  )\n"; //close (parameters
       }

-      strResult += ")\n\n"; //close (define=signal
+      strResult += ")\n\n"; //close (define-signal
     }
   }

@@ -242,17 +247,20 @@
 }

-
 std::string get_defs(GType gtype, GTypeIsAPointerFunc is_a_pointer_func)
 {
   std::string strObjectName = g_type_name(gtype);
-  std::string strDefs = ";; From " + strObjectName + "\n\n";
+  std::string strDefs;

   if(G_TYPE_IS_OBJECT(gtype) || G_TYPE_IS_INTERFACE(gtype))
   {
+    strDefs = ";; From " + strObjectName + "\n\n";
     strDefs += get_signals(gtype, is_a_pointer_func);
     strDefs += get_properties(gtype);
   }
+  else
+    strDefs = ";; " + strObjectName +
+      " is neither a GObject nor a GInterface. Not checked for signals and properties.\n\n";

   return strDefs;
 }


change std::quick_exit to std::_Exit to see if works on MacOS

--- src/system/system.cpp
+++ src/system/system.cpp
@@ -47,7 +47,7 @@
 {
     user_input_loop_.exit(0);
     Terminal::uninitialize();
-    std::quick_exit(0);
+    std::_Exit(0);
 }

 void System::set_head(Widget* new_head)


Avoid a = a quadruple

Avoid a = a quadruple

--- src/tac/Optimizer.cpp
+++ src/tac/Optimizer.cpp
@@ -471,6 +471,12 @@
                 return true;
             }

+            //x = x is never useful
+            if(!quadruple->op && tac::equals<std::shared_ptr<Variable>>(*quadruple->arg1, quadruple->result)){
+                optimized = true;
+                return false;
+            }
+
             if(used.find(quadruple->result) == used.end()){
                 if(quadruple->result){
                     //The other kind of variables can be used in other basic block


Resolved conflicts?

Resolved conflicts?

--- opengl.hpp
+++ opengl.hpp
@@ -859,7 +859,6 @@
 	}
   #endif

-
     #if defined(GL_HPP_FUNDEF_TexSubImage3D) || defined(GL_HPP_FUNDEF_TextureSubImage3DEXT)
 	void SubImage3D(GLenum targ, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format,
 GLenum type, const GLvoid *data)


Revert 49066 - Reverting checkin in rev 48521 as creating a child window for GL rendering creates more problems than it solves.
Hopefully either we'll find a more elegant solution or the problem will go away with the introduction of ANGLE.
Review URL: http://codereview.chromium.org/2644001

TBR=vangelis@chromium.org
Review URL: http://codereview.chromium.org/2645007

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@49067 0039d316-1c4b-4281-b951-d872f2087c98

--- app/gfx/gl/gl_context_win.cc
+++ app/gfx/gl/gl_context_win.cc
@@ -20,6 +20,8 @@

 typedef HGLRC GLContextHandle;
 typedef HPBUFFERARB PbufferHandle;
+
+const wchar_t kNativeViewGLClass[] = L"NativeViewGLWindow";

 // This class is a wrapper around a GL context that renders directly to a
 // window.
@@ -27,6 +29,7 @@
  public:
   explicit NativeViewGLContext(gfx::PluginWindowHandle window)
       : window_(window),
+        content_window_(NULL),
         device_context_(NULL),
         context_(NULL) {
     DCHECK(window);
@@ -44,7 +47,10 @@
   virtual void* GetHandle();

  private:
+  HWND CreateContentWindow(HWND parent);
+
   gfx::PluginWindowHandle window_;
+  HWND content_window_;
   HDC device_context_;
   GLContextHandle context_;

@@ -283,9 +289,46 @@
   return true;
 }

+HWND NativeViewGLContext::CreateContentWindow(HWND parent) {
+  WNDCLASS window_class = {0};
+  if (!GetClassInfo(GetModuleHandle(0), kNativeViewGLClass, &window_class)) {
+    window_class.style = CS_OWNDC;
+    window_class.hInstance = GetModuleHandle(0);
+    window_class.lpfnWndProc = DefWindowProc;
+    window_class.lpszClassName = kNativeViewGLClass;
+    if (!RegisterClass(&window_class)) {
+        DLOG(ERROR) << "Failed to register window class";
+        return 0;
+    }
+  }
+
+  // The content window's size matches the size of the hosting window at
+  // creation time. If the size of the hosting window changes, SwapBuffers
+  // must be called to resize the content window appropriately.
+  RECT rect;
+  GetClientRect(window_, &rect);
+  HWND content_window = CreateWindow(kNativeViewGLClass, L"NativeViewGLcontent",
+      WS_CHILD | WS_VISIBLE | WS_DISABLED,
+      0, 0, rect.right - rect.left, rect.bottom - rect.top, parent, 0,
+      GetModuleHandle(0), 0);
+
+  if (!content_window)
+    UnregisterClass(kNativeViewGLClass, GetModuleHandle(0));
+
+  return content_window;
+}
+
 bool NativeViewGLContext::Initialize(bool multisampled) {
+  // Create a new window to be used by the GL context. The content window is a
+  // child of hosting window and renders on top of it. Currently the content
+  // window gets resized when SwapBuffers() gets called to match the size of
+  // the host.
+  content_window_ = CreateContentWindow(window_);
+  if (!content_window_)
+      return false;
+
   // The GL context will render to this window.
-  device_context_ = GetDC(window_);
+  device_context_ = GetDC(content_window_);

   int pixel_format =
       multisampled ? g_multisampled_pixel_format : g_regular_pixel_format;
@@ -328,10 +371,12 @@
     context_ = NULL;
   }

-  if (window_ && device_context_)
-    ReleaseDC(window_, device_context_);
-
-  window_ = NULL;
+  if (content_window_ && device_context_) {
+    ReleaseDC(content_window_, device_context_);
+    ::DestroyWindow(content_window_);
+    UnregisterClass(kNativeViewGLClass, GetModuleHandle(0));
+  }
+  content_window_ = NULL;
   device_context_ = NULL;
 }

@@ -358,7 +403,20 @@

 void NativeViewGLContext::SwapBuffers() {
   DCHECK(device_context_);
+
   ::SwapBuffers(device_context_);
+
+  // Adjust the size of the content window to always match that of the hosting
+  // window.
+  RECT host_window_rect;
+  GetClientRect(window_, &host_window_rect);
+  RECT content_window_rect;
+  GetClientRect(content_window_, &content_window_rect);
+  if (!EqualRect(&host_window_rect, &content_window_rect)){
+    SetWindowPos(content_window_, NULL, 0, 0,
+                 host_window_rect.right - host_window_rect.left,
+                 host_window_rect.bottom - host_window_rect.top, 0);
+  }
 }

 gfx::Size NativeViewGLContext::GetSize() {


fix variable init

fix variable init

--- src/operators.cpp
+++ src/operators.cpp
@@ -86,8 +86,8 @@
                         }
                     }
                     // find point in data
-                    point_t point1_data = { points.find (point1->first)->second };
-                    point_t point2_data = { points.find (point2->first)->second };
+                    point_t point1_data = points.find (point1->first)->second;
+                    point_t point2_data = points.find (point2->first)->second;
                     point_t Idata       = { point1_data.x +
                         ((point2_data.x - point1_data.x) * scale_p1_I),
                         point1_data.y + ((point2_data.y - point1_data.y) * scale_p1_I) };


[FIXED] rect shear

[FIXED] rect shear

--- SM_Rect.inl
+++ SM_Rect.inl
@@ -121,7 +121,6 @@
 template <typename T>
 void Rect<T>::Shear(T kx, T ky)
 {
-	MakeEmpty();
 	// x' = x + y*kx
 	// y' = x*ky + y
 	sm ::vec2 v[4];
@@ -133,6 +132,8 @@
 	v[2].y = xmax * ky + ymax;
 	v[3].x = xmin + ymax * kx;
 	v[3].y = xmin * ky + ymax;
+
+	MakeEmpty();
 	for (int i = 0; i < 4; ++i) {
 		Combine(v[i]);
 	}


Fix compilation

Fix compilation

--- Cutelyst/dispatcher.cpp
+++ Cutelyst/dispatcher.cpp
@@ -63,7 +63,7 @@
             if (method.methodType() == QMetaMethod::Method ||
                     method.methodType() == QMetaMethod::Slot) {
                 bool registered = false;
-                Action *action = new Action(method, controller, this);
+                Action *action = new Action(method, controller);
                 if (action->isValid() && !d->actionHash.contains(action->privateName())) {
                     if (!action->attributes().contains("Private")) {
                         // Register the action with each dispatcher


reverted change again, to be tackled in a separate bug.

--- Modules/Python/mitkPythonService.cpp
+++ Modules/Python/mitkPythonService.cpp
@@ -795,11 +795,7 @@

 bool mitk::PythonService::IsOpenCvPythonWrappingAvailable()
 {
-  QString command;
-  command.append( QString("try:\n   import cv2\nexcept:\n   pass\n"));
-  this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND );
-
-  //this->Execute( "import cv2\n", IPythonService::SINGLE_LINE_COMMAND );
+  this->Execute( "import cv2\n", IPythonService::SINGLE_LINE_COMMAND );
   m_OpenCVWrappingAvailable = !this->PythonErrorOccured();

   return m_OpenCVWrappingAvailable;


From Colin McDonald, "Multi-texturing fails with recent osg on older graphics cards, due to use of parameter GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS which is only part of the standard from 2.0 onwards.  I've updated src/osg/State.cpp, so that it attempts to be more rigorous regarding OpenGL version and extension checking."

--- src/osg/State.cpp
+++ src/osg/State.cpp
@@ -23,6 +23,10 @@
 #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
 #endif

+#ifndef GL_MAX_TEXTURE_UNITS
+#define GL_MAX_TEXTURE_UNITS 0x84E2
+#endif
+
 using namespace std;
 using namespace osg;

@@ -742,17 +746,24 @@
     _glDisableVertexAttribArray =  (DisableVertexAttribProc) osg::getGLExtensionFuncPtr("glDisableVertexAttribArray","glDisableVertexAttribArrayARB");
     _glBindBuffer = (BindBufferProc) osg::getGLExtensionFuncPtr("glBindBuffer","glBindBufferARB");

-    _glMaxTextureUnits = 1;
-    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS,&_glMaxTextureUnits);
-
-    if (osg::getGLVersionNumber() < 2.0)
-    {
-        _glMaxTextureCoords = _glMaxTextureUnits;
+    if ( osg::getGLVersionNumber() >= 2.0 || osg::isGLExtensionSupported(_contextID,"GL_ARB_vertex_shader") )
+    {
+        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS,&_glMaxTextureUnits);
+        glGetIntegerv(GL_MAX_TEXTURE_COORDS,&_glMaxTextureCoords);
+    }
+    else if ( osg::getGLVersionNumber() >= 1.3 ||
+                                 osg::isGLExtensionSupported(_contextID,"GL_ARB_multitexture") ||
+                                 osg::isGLExtensionSupported(_contextID,"GL_EXT_multitexture") )
+    {
+        GLint maxTextureUnits;
+        glGetIntegerv(GL_MAX_TEXTURE_UNITS,&maxTextureUnits);
+        _glMaxTextureUnits = maxTextureUnits;
+        _glMaxTextureCoords = maxTextureUnits;
     }
     else
     {
-        glGetIntegerv(GL_MAX_TEXTURE_COORDS,&_glMaxTextureCoords);
-        _glMaxTextureUnits = maximum(_glMaxTextureCoords,_glMaxTextureUnits);
+        _glMaxTextureUnits = 1;
+        _glMaxTextureCoords = 1;
     }

     _extensionProcsInitialized = true;
@@ -782,7 +793,7 @@
 {
     if (unit!=_currentActiveTextureUnit)
     {
-        if (_glActiveTexture && unit < (unsigned int)_glMaxTextureUnits)
+        if (_glActiveTexture && unit < (unsigned int)(maximum(_glMaxTextureCoords,_glMaxTextureUnits)) )
         {
             _glActiveTexture(GL_TEXTURE0+unit);
             _currentActiveTextureUnit = unit;


Fix XRP accounts from being created with account index = 0.

@onyb

--- core/src/wallet/ripple/RippleLikeWallet.cpp
+++ core/src/wallet/ripple/RippleLikeWallet.cpp
@@ -121,6 +121,7 @@

         FuturePtr<ledger::core::api::Account>
         RippleLikeWallet::newAccountWithExtendedKeyInfo(const api::ExtendedKeyAccountCreationInfo &info) {
+            logger()->debug("Creating new XRP account (index = {}) with extended key info", info.index);

             if (info.extendedKeys.empty()) {
                 throw make_exception(api::ErrorCode::INVALID_ARGUMENT,
@@ -129,7 +130,7 @@

             auto self = getSelf();
             auto scheme = getDerivationScheme();
-            auto accountIndex = getAccountIndex(scheme, info.index);
+            auto accountIndex = info.index;
             scheme.setCoinType(getCurrency().bip44CoinType).setAccountIndex(accountIndex);
             auto xpubPath = scheme.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX).getPath();
             return async<std::shared_ptr<api::Account> >([=]() -> std::shared_ptr<api::Account> {


parser sops after the last line

parser sops after the last line

--- engine/src/csparser.cpp
+++ engine/src/csparser.cpp
@@ -300,11 +300,12 @@
         if (!parseInt(line, &(step.duration)))
             return false;
         line = readline(i);
-        while(i != eof &&
-              line.find(":") != std::string::npos &&
+        while(line.find(":") != std::string::npos &&
               line.find("->") == std::string::npos){
             if (!parseStepContent(line, step))
                 return false;
+            if (i == eof)
+                break;
             line = readline(i);
         }
         if (*n > 0){


Code cleanup (Universe):

Code cleanup (Universe):

- rewrite Univere::reset using memset/memcpy
- apply channel modifiers after writeRelative (there was a bug)
- move channel modifiers processing to singleplace in applyGM

--- engine/src/universe.cpp
+++ engine/src/universe.cpp
@@ -200,15 +200,14 @@

 void Universe::reset(int address, int range)
 {
-    for (int i = address; i < address + range && i < UNIVERSE_SIZE; i++)
-    {
-        (*m_preGMValues)[i] = 0;
-        if (m_modifiers.at(i) != NULL)
-            (*m_postGMValues)[i] = m_modifiers.at(i)->getValue(0);
-        else
-            (*m_postGMValues)[i] = 0;
-        m_relativeValues[i] = 0;
-    }
+    if (address >= UNIVERSE_SIZE)
+        return;
+    if (address + range > UNIVERSE_SIZE)
+       range = UNIVERSE_SIZE - address;
+
+    memset(m_preGMValues->data() + address, 0, range * sizeof(*m_preGMValues->data()));
+    memset(m_relativeValues.data() + address, 0, range * sizeof(*m_relativeValues.data()));
+    memcpy(m_postGMValues->data() + address, m_modifiedZeroValues->data() + address, range * sizeof(*m_postGMValues->data()));
 }

 void Universe::zeroIntensityChannels()
@@ -304,7 +303,7 @@
 uchar Universe::applyGM(int channel, uchar value)
 {
     if (value == 0)
-        return 0;
+        return (uchar)(*m_modifiedZeroValues)[channel];

     if ((m_grandMaster->channelMode() == GrandMaster::Intensity && m_channelsMask->at(channel) & Intensity) ||
         (m_grandMaster->channelMode() == GrandMaster::AllChannels))
@@ -314,6 +313,9 @@
         else
             value = char(floor((double(value) * m_grandMaster->fraction()) + 0.5));
     }
+
+    if (m_modifiers.at(channel) != NULL)
+        value = m_modifiers.at(channel)->getValue(value);

     return value;
 }
@@ -620,12 +622,7 @@
         value = CLAMP(val, 0, (int)UCHAR_MAX);
     }

-    value = applyGM(channel, value);
-
-    if (m_modifiers.at(channel) != NULL)
-        value = m_modifiers.at(channel)->getValue(value);
-
-    (*m_postGMValues)[channel] = char(value);
+    (*m_postGMValues)[channel] = applyGM(channel, value);

     return true;
 }
@@ -646,8 +643,7 @@
     val += (uchar)m_preGMValues->at(channel);
     value = CLAMP(val, 0, (int)UCHAR_MAX);

-    value = applyGM(channel, value);
-    (*m_postGMValues)[channel] = char(value);
+    (*m_postGMValues)[channel] = applyGM(channel, value);

     return true;
 }
@@ -698,12 +694,7 @@
         break;
     }

-    value = applyGM(channel, value);
-
-    if (m_modifiers.at(channel) != NULL)
-        value = m_modifiers.at(channel)->getValue(value);
-
-    (*m_postGMValues)[channel] = char(value);
+    (*m_postGMValues)[channel] = applyGM(channel, value);

     return true;
 }


got second redirection symbol working

got second redirection symbol working

--- src/output_IO.cpp
+++ src/output_IO.cpp
@@ -76,7 +76,7 @@
 }
 int exec_status;
 bool str_continue = true;
-bool execute(char* command, char* command_list[], int conect_type, bool redir)
+bool execute(char* command, char* command_list[], int conect_type, int redir)
 {
     cout << "conect:type: " << conect_type << endl;
     int status;
@@ -88,11 +88,36 @@
     }
     else if(process_ID == 0) //child process
     {
-        if(redir)
+        if(redir == 1)
         {
             cout << "did this output" << endl;
             int fd;
             if((fd = open("outfile", O_RDWR | O_CREAT | O_TRUNC, 0744)) == -1)
+            {
+                perror("open");
+            }
+            if(close(1) == -1)
+            {
+                perror("close");
+            }
+            if(dup(fd) == -1)
+            {
+                perror("dup");
+            }
+            exec_status = (execvp(command, command_list));
+            //cout << "output exec status: " << exec_status << endl;
+            if(exec_status == -1)
+            {
+                perror("error with passed in argument list");
+                return exec_status;
+                exit(1);
+            }
+        }
+        if(redir == 2)
+        {
+            cout << "yay this should output now" << endl;
+            int fd;
+            if((fd = open("outfile", O_RDWR | O_CREAT | O_APPEND, 0744)) == -1)
             {
                 perror("open");
             }
@@ -151,16 +176,24 @@
     }
 }

-bool chk_redir(string s)
+int chk_redir(string s)
 {
     for(int x = 0; x < s.size(); x++)
     {
+        //cout << "output x: " << x << endl;
         if(s.at(x) == '>')
         {
-            return true;
-        }
-    }
-    return false;
+            //cout << "output x: " << endl;
+            int y = x;
+            if(y++ < s.size() && s.at(x) == '>')
+            {
+                return 2;
+            }
+            else
+            {return 1;}
+        }
+    }
+    return 0;
 }

 int main(int argc, char **argv)
@@ -206,7 +239,7 @@

         getline(cin, to_be_tokenized);
-        bool to_redir;
+        int to_redir;           //certain number corresponds to what redirection it is
         to_redir = chk_redir(to_be_tokenized);//checks if there is redirection sign in command
         for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
         {


issue=#907 bugfix of replication sdk

issue=#907 bugfix of replication sdk

--- src/sdk/tera_replication.cc
+++ src/sdk/tera_replication.cc
@@ -188,10 +188,6 @@

     virtual void SetCallBack(Callback callback) {
         _user_callback = callback;
-        for (size_t i = 0; i < _row_readers.size(); i++) {
-            _row_readers[i]->SetCallBack(RowReaderCallback);
-            _row_readers[i]->SetContext(this);
-        }
     }

     virtual void SetContext(void* context) {
@@ -298,7 +294,11 @@
         bool is_async = mutation_rep_impl->IsAsync();
         const std::vector<RowMutation*>& mutation_list = mutation_rep_impl->GetRowMutationList();
         const std::vector<Table*>& table_list = mutation_rep_impl->GetTableList();
-        for (size_t i = 0; i < mutation_list.size(); i++) {
+        // in async mode, after the last call of ApplyMutation, we should not access
+        // 'mutation_rep_impl' anymore, that's why we assign the value of 'mutation_list.size()'
+        // to a local variable 'mutation_num'
+        size_t mutation_num = mutation_list.size();
+        for (size_t i = 0; i < mutation_num; i++) {
             table_list[i]->ApplyMutation(mutation_list[i]);
         }
         if (!is_async) {
@@ -327,7 +327,8 @@
         bool is_async = reader_rep_impl->IsAsync();
         const std::vector<RowReader*>& reader_list = reader_rep_impl->GetRowReaderList();
         const std::vector<Table*>& table_list = reader_rep_impl->GetTableList();
-        for (size_t i = 0; i < reader_list.size(); i++) {
+        size_t reader_num = reader_list.size();
+        for (size_t i = 0; i < reader_num; i++) {
             table_list[i]->Get(reader_list[i]);
         }
         if (!is_async) {


Don't mark argument as moved when passing copyable type as vararg

--- src/sema/typecheck-expr.cpp
+++ src/sema/typecheck-expr.cpp
@@ -1189,7 +1189,7 @@
     }

     for (auto&& [param, arg] : llvm::zip_longest(params, expr.getArgs())) {
-        if (arg && (!param || !param->getType().isImplicitlyCopyable())) {
+        if (arg && !arg->getValue()->getType().isImplicitlyCopyable() && (!param || !param->getType().isImplicitlyCopyable())) {
             setMoved(arg->getValue(), true);
         }
     }


Minor changes and Test

Minor changes and Test

--- env/SelectStatement.cpp
+++ env/SelectStatement.cpp
@@ -413,8 +413,8 @@
                 for (auto it = this->selections.begin(); it != this->selections.end(); it++) {
                     Selection *s = *it;
                     (*ofs) << tab << "\t\t\t\t" << s->print(ofs, ofl) << endl;
-                    (*ofs) << tab << "\t\t\t\t" << func_name << "_add(iter, inserted);" << endl;
-                }
+                }
+                (*ofs) << tab << "\t\t\t\t" << func_name << "_add(iter, inserted);" << endl;
             } //else рекурсия
         }
     }


Update constexpr_variable.cpp

Update constexpr_variable.cpp

--- compile-time-constants/constexpr_variable.cpp
+++ compile-time-constants/constexpr_variable.cpp
@@ -7,5 +7,5 @@
 int main()
 {
   constexpr uint32_t MEMORY_SIZE{ 512 };
-
+  std::cout << MEMORY_SIZE << std::endl;
 }


THRIFT-1527. java: Generated implementation of tupleReadStruct in unions return null when the setfield is unrecognized

Unrecognized fields will now result in a TProtocolException when reading with the TupleProtocol.

git-svn-id: e03702e31dc1037215618ef8d1dc0ebc5b0b17e5@1295997 13f79535-47bb-0310-9956-ffa450edef68

--- compiler/cpp/src/generate/t_java_generator.cc
+++ compiler/cpp/src/generate/t_java_generator.cc
@@ -353,6 +353,7 @@
     "import org.apache.thrift.scheme.StandardScheme;\n\n" +
     "import org.apache.thrift.scheme.TupleScheme;\n" +
     "import org.apache.thrift.protocol.TTupleProtocol;\n" +
+    "import org.apache.thrift.protocol.TProtocolException;\n" +
     "import org.apache.thrift.EncodingUtils;\n" +
     "import java.util.List;\n" +
     "import java.util.ArrayList;\n" +
@@ -1082,7 +1083,7 @@
   indent_down();
   indent(out) << "} else {" << endl;
   indent_up();
-  indent(out) << "return null;" << endl;
+  indent(out) << "throw new TProtocolException(\"Couldn't find a field with field id \" + fieldID);" << endl;
   indent_down();
   indent(out) << "}" << endl;
   indent_down();


Fix Transpose test

Fix Transpose test

--- xchainer/array_test.cc
+++ xchainer/array_test.cc
@@ -15,6 +15,8 @@
 #include "xchainer/context.h"
 #include "xchainer/device.h"
 #include "xchainer/error.h"
+#include "xchainer/indexable_array.h"
+#include "xchainer/indexer.h"
 #include "xchainer/native_backend.h"
 #include "xchainer/op_node.h"
 #include "xchainer/testing/array.h"
@@ -71,8 +73,20 @@

     template <typename T>
     void ExpectDataEqual(const Array& expected, const Array& actual) {
-        const T* expected_data = static_cast<const T*>(expected.data().get());
-        ExpectDataEqual(expected_data, actual);
+        actual.device().Synchronize();
+        IndexableArray<const T> expected_iarray{expected};
+        IndexableArray<const T> actual_iarray{actual};
+        Indexer<> indexer{actual.shape()};
+        for (int64_t i = 0; i < indexer.total_size(); i++) {
+            indexer.Set(i);
+            const auto& expected = expected_iarray[indexer];
+            const auto& actual = actual_iarray[indexer];
+            if (std::isnan(expected)) {
+                EXPECT_TRUE(std::isnan(actual)) << "where i is " << i;
+            } else {
+                EXPECT_EQ(expected, actual) << "where i is " << i;
+            }
+        }
     }

     template <typename T>
@@ -923,13 +937,14 @@
 TEST_P(ArrayTest, Transpose) {
     // as a member function
     {
-        Array a = Array::Zeros({2, 3, 4}, Dtype::kBool);
-
+        Array a = testing::MakeArray<int32_t>({2, 3}, {0, 1, 2, 3, 4, 5});
         Array b = a.Transpose();
-        EXPECT_EQ(Shape({4, 3, 2}), b.shape());
-        EXPECT_EQ(Strides({1, 4, 12}), b.strides());
-
-        ExpectEqual<bool>(a, a.Transpose().Transpose());
+
+        EXPECT_EQ(Shape({3, 2}), b.shape());
+        EXPECT_EQ(Strides({4, 12}), b.strides());
+
+        Array e = testing::MakeArray<int32_t>({3, 2}, {0, 3, 1, 4, 2, 5});
+        ExpectEqual<int32_t>(e, b);
     }
     // as a free function
     {


fix compilation error when api key is included.

--- platform/android/Rhodes/jni/src/mapview.cpp
+++ platform/android/Rhodes/jni/src/mapview.cpp
@@ -64,7 +64,7 @@
     JNIEnv *env = jnienv();
     jclass cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
     if (!cls) return 0;
-    jmethod mid = getJNIClassStaticMethod(env, cls, "getCenterLatitude", "()D");
+    jmethodID mid = getJNIClassStaticMethod(env, cls, "getCenterLatitude", "()D");
     if (!mid) return 0;

     return env->CallStaticDoubleMethod(cls, mid);
@@ -79,7 +79,7 @@
     JNIEnv *env = jnienv();
     jclass cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
     if (!cls) return 0;
-    jmethod mid = getJNIClassStaticMethod(env, cls, "getCenterLongitude", "()D");
+    jmethodID mid = getJNIClassStaticMethod(env, cls, "getCenterLongitude", "()D");
     if (!mid) return 0;

     return env->CallStaticDoubleMethod(cls, mid);


getWallDist working for all tested cases thus far.

--- src/particles.cpp
+++ src/particles.cpp
@@ -95,6 +95,7 @@
 }

+//TODO: make this function shorter.
 float Particles::getWallDist( float scannerX, float scannerY, float scannerTheta,
                             float segX1, float segY1, float segX2, float segY2)
 {
@@ -104,7 +105,8 @@
     float segmentM = (segY2 - segY1)/(segX2 - segX1);
     float intersectionX, intersectionY;

-    // Handle the case where angles point in opposite vertical directions.
+    // Handle special case where parallel vertical lines could round to
+    // opposite slopes.
     if((laserM == std::numeric_limits<float>::infinity() ||
        (laserM == -std::numeric_limits<float>::infinity())) &&
        (segmentM == std::numeric_limits<float>::infinity() ||
@@ -115,75 +117,50 @@
     if (approxEqual(laserM, segmentM, 1))
         return std::numeric_limits<float>::infinity();

-    // Use geometry when a vertical line is involved.
-    // Old triangle formula: R = x/cos(theta).
+    // Special easy-algebra cases when either scan line or wall is vertical.
+    // TODO: shrink these two big if-blocks
     if(segmentM == std::numeric_limits<float>::infinity())
     {
-        // FIXME: double-check if off-segment check works
-        // FIXME: intersectionDist should be positive!!
-        float intersectionDist = std::abs((std::max(segX1,scannerX) -
-                                 std::min(segX1, scannerX))/
-                                 cos(tuneAngle(scannerTheta)));
-/*
-        std::cout <<"intersectionDist:" <<  intersectionDist << std::endl;
-*/
-        intersectionX = round(scannerX +
-                        intersectionDist *
-                        std::abs(cos(tuneAngle(scannerTheta))));
-        intersectionY = round(scannerY +
-                        intersectionDist *
-                        std::abs(sin(tuneAngle(scannerTheta))));
-/*
-        std::cout << "intersection: (" << intersectionX << ", "
-                  << intersectionY << ")" << std::endl;
-*/
+        float laserYInt = laserM * (-scannerX) + scannerY;
+        intersectionX = segX1;
+        intersectionY = laserM * segX1 + laserYInt;
+
+        float intersectionDist = sqrt(pow((scannerX - intersectionX), 2) +
+                                      pow((scannerY - intersectionY), 2));
+        std::cout << "intersectionDist: " << intersectionDist << std::endl;

         // Calculate if intersection is on wall segment.
         if (scanOffSegment(intersectionX, intersectionY,
                             segX1, segY1, segX2, segY2))
-        {
-/*
-            std::cout << "scan off segment" << std::endl;
-*/
-            return std::numeric_limits<float>::infinity();
-        }
+            return std::numeric_limits<float>::infinity();

         if (scanBackwards(scannerX, scannerY, scannerTheta, intersectionX,
                           intersectionY))
-        {
-/*
-            std::cout << "scan backwards!" << std::endl;
-*/
-            return std::numeric_limits<float>::infinity();
-        }
+            return std::numeric_limits<float>::infinity();

         return intersectionDist;
     }
+
     if(laserM == std::numeric_limits<float>::infinity())
     {
-        // FIXME: double-check if off-segment check works
-        float wallAngle = atan2((segY2 - segY1), (segX2 - segX1));
-        float intersectionDist = std::abs((std::max(segX1,scannerX) -
-                                 std::min(segX1, scannerX))/
-                                 cos(wallAngle));
-        intersectionX = round(scannerX +
-                        intersectionDist *
-                        std::abs(cos(tuneAngle(scannerTheta))));
-        intersectionY = round(scannerY +
-                        intersectionDist *
-                        std::abs(sin(tuneAngle(scannerTheta))));
+        float wallYInt = segmentM * (-segX1) + segY1;
+
+        intersectionX = scannerX;   ///< nice benefit of a vertical laser.
+        intersectionY = segmentM * scannerX + wallYInt;
+        float intersectionDist = sqrt(pow((scannerX - intersectionX), 2) +
+                                      pow((scannerY - intersectionY), 2));
+
         if (scanOffSegment(intersectionX, intersectionY,
                     segX1, segY1, segX2, segY2))
             return std::numeric_limits<float>::infinity();
-
         if (scanBackwards(scannerX, scannerY, scannerTheta, intersectionX,
                           intersectionY))
             return std::numeric_limits<float>::infinity();

-        else
-            return intersectionDist;
-    }
-    // Use algebra for all other cases.
+        return intersectionDist;
+    }
+
+    // Use slopes and intercepts with algebra for all other cases.
     float laserYInt = laserM*(-scannerX) + scannerY;
     float segmentYInt = segmentM * (-segX1) + segY1;
     intersectionX = (segmentYInt - laserYInt)/(laserM - segmentM);
@@ -286,6 +263,7 @@
     if ((intersectionY < std::min(segY1,segY2)) ||
           (intersectionY > std::max(segY1,segY2)))
     {
+        std::cout << "Y triggered" << std::endl;
         // handle rounding error cases for narrow ranges of segY1 and segY2
         if (!(approxEqual(segY1, segY2, 3) &&
             approxEqual(segY1, intersectionY, 3)))


Fix stats.cpp test on 32-bit Windows.

Fix stats.cpp test on 32-bit Windows.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@257981 91177308-0d34-0410-b5e6-96231b3b80d8

--- test/cfi/stats.cpp
+++ test/cfi/stats.cpp
@@ -10,22 +10,22 @@
 };

 extern "C" __attribute__((noinline)) void vcall(A *a) {
-  // CHECK: stats.cpp:[[@LINE+1]] vcall cfi-vcall 37
+  // CHECK: stats.cpp:[[@LINE+1]] {{_?}}vcall cfi-vcall 37
   a->vf();
 }

 extern "C" __attribute__((noinline)) void nvcall(A *a) {
-  // CHECK: stats.cpp:[[@LINE+1]] nvcall cfi-nvcall 51
+  // CHECK: stats.cpp:[[@LINE+1]] {{_?}}nvcall cfi-nvcall 51
   a->nvf();
 }

 extern "C" __attribute__((noinline)) A *dcast(A *a) {
-  // CHECK: stats.cpp:[[@LINE+1]] dcast cfi-derived-cast 24
+  // CHECK: stats.cpp:[[@LINE+1]] {{_?}}dcast cfi-derived-cast 24
   return (A *)(ABase *)a;
 }

 extern "C" __attribute__((noinline)) A *ucast(A *a) {
-  // CHECK: stats.cpp:[[@LINE+1]] ucast cfi-unrelated-cast 81
+  // CHECK: stats.cpp:[[@LINE+1]] {{_?}}ucast cfi-unrelated-cast 81
   return (A *)(char *)a;
 }