vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
     intervals.push_back(newInterval);
     return merge(intervals);
 }
Exemplo n.º 2
0
void pkgRepository::GetPackageList( const char *dname )
{
  /* Helper to retrieve and recursively process a named package list.
   *
   * FIXME: having made this recursively process multiple catalogues,
   * potentially from multiple independent repositories, we may have
   * introduced potential for catalogue name clashes; we need to add
   * name hashing in the local catalogue cache, to avoid conflicts.
   */
  if( dname != NULL )
  {
    const char *dfile;
    if( (dfile = xmlfile( dname )) != NULL )
    {
      /* Check for a locally cached copy of the "package-list" file...
       */
      if( force_update || (access( dfile, F_OK ) != 0) )
      {
	/* When performing an "update", or if no local copy is available...
	 * Force a "sync", to fetch a copy from the public host.
	 */
	dmh_printf( "Update catalogue: %s.xml\n", dname );
	owner->SyncRepository( dname, repository );
      }

      /* We SHOULD now have a locally cached copy of the package-list;
       * attempt to merge it into the active profile database...
       */
      pkgXmlDocument merge( dfile );
      if( merge.IsOk() )
      {
	/* We successfully loaded the XML catalogue; refer to its
	 * root element...
	 */
	if( pkgOptions()->Test( OPTION_VERBOSE ) > 1 )
	  dmh_printf( "Load catalogue: %s.xml\n", dname );
	pkgXmlNode *catalogue, *pkglist;
	if( (catalogue = merge.GetRoot()) != NULL )
	{
	  /* ...read it, selecting each of the "package-collection"
	   * records contained within it...
	   */
	  pkglist = catalogue->FindFirstAssociate( package_collection_key );
	  while( pkglist != NULL )
	  {
	    /* ...and append a copy of each to the active profile...
	     */
	    dbase->LinkEndChild( pkglist->Clone() );

	    /* Move on to the next "package-collection" (if any)
	     * within the current catalogue...
	     */
	    pkglist = pkglist->FindNextAssociate( package_collection_key );
	  }

	  /* Recursively incorporate any additional package lists,
	   * which may be specified within the current catalogue...
	   */
	  GetPackageList( catalogue->FindFirstAssociate( package_list_key ) );
	}
      }
      else
      { /* The specified catalogue could not be successfully loaded;
	 * emit a warning diagnostic message, and otherwise ignore it.
	 */
	dmh_notify( DMH_WARNING, "Load catalogue: FAILED: %s.xml\n", dname );
      }

      /* However we handled it, the XML file's path name in "dfile" was
       * allocated on the heap; we lose its reference on termination of
       * this loop, so we must free it to avoid a memory leak.
       */
      free( (void *)(dfile) );
    }
  }
}
Exemplo n.º 3
0
void cv::merge(InputArrayOfArrays _mv, OutputArray _dst)
{
    vector<Mat> mv;
    _mv.getMatVector(mv);
    merge(!mv.empty() ? &mv[0] : 0, mv.size(), _dst);
}
Exemplo n.º 4
0
        __device__ static void reduce(Pointer smem, Reference val, uint tid, Op op)
        {
            loadToSmem(smem, val, tid);
            if (N >= 32)
                __syncthreads();

            if (N >= 2048)
            {
                if (tid < 1024)
                    merge(smem, val, tid, 1024, op);

                __syncthreads();
            }
            if (N >= 1024)
            {
                if (tid < 512)
                    merge(smem, val, tid, 512, op);

                __syncthreads();
            }
            if (N >= 512)
            {
                if (tid < 256)
                    merge(smem, val, tid, 256, op);

                __syncthreads();
            }
            if (N >= 256)
            {
                if (tid < 128)
                    merge(smem, val, tid, 128, op);

                __syncthreads();
            }
            if (N >= 128)
            {
                if (tid < 64)
                    merge(smem, val, tid, 64, op);

                __syncthreads();
            }
            if (N >= 64)
            {
                if (tid < 32)
                    merge(smem, val, tid, 32, op);
            }

            if (tid < 16)
            {
                merge(smem, val, tid, 16, op);
                merge(smem, val, tid, 8, op);
                merge(smem, val, tid, 4, op);
                merge(smem, val, tid, 2, op);
                merge(smem, val, tid, 1, op);
            }
        }
Exemplo n.º 5
0
		/**
		 * Append a null terminated string to the buffer. The buffer is stretched
		 * if necessary.
		 * @return SUCCESS or FAILURE if no memory is available
		 * to stretch the buffer.
		 */
		int32 merge(char* string)
		{
			return merge(string, (uint32) strlen(string));
		}
Exemplo n.º 6
0
Arquivo: sort.cpp Projeto: PJBoy/cpp
void merge(T(&a)[n]) {
    merge(a, n);
}
int main()
{
    char ch[10];
    int x,i,c,r,y;
    while(scanf("%d%d%d",&n,&k,&m)!=EOF)
    {
        chu();
        for(i=0;i<k;i++)
        {
            scanf("%d%d",&r,&c);
            if(-1 == low[c])
            {
                low[c]=r;
                continue;
            }
            low[c]=min(low[c],r);
        }
        for(i=0;i<m;i++)
        {
            scanf("%s",ch);
            if('G' == ch[0])
            {
                scanf("%d",&x);
                if(x == set[x])
                {
                    if(-1 == low[x])
                    {
                        printf("Company %d is empty.\n",x);
                    }
                    else
                    {
                        printf("Lowest rate: %d.\n",low[x]);                    
                    }
                }
                else
                {
                    printf("Company %d is a part of company %d.\n",x,find(x));
                }
            }
            else if('A' == ch[0])
            {
                scanf("%d%d",&x,&y);
                if(y == set[y])
                {
                    if(-1 == low[y])
                    {
                        low[y]=x;
                    }
                    else
                    {
                        low[y]=min(low[y],x);
                    }
                    printf("Accept\n");
                }
                else
                {
                    printf("Reject\n");
                }
            }
            else
            {
                scanf("%d%d",&x,&y);
                if(x == y)
                {
                    printf("Reject\n");
                    continue;
                }
        
                if(x==set[x] && y==set[y])
                {
                    printf("Accept\n");
                    if(low[x] < 0 || low[y] < 0)
                    {
                        low[x]=max(low[x],low[y]);    
                    }
                    else
                    {
                        low[x]=min(low[x],low[y]);
                    }
                    merge(x,y);
                }
                else
                {
                    printf("Reject\n");
                }
            }
        }
        printf("\n");    
    }
    return 0;
}
Exemplo n.º 8
0
void cv::merge(const vector<Mat>& mv, OutputArray _dst)
{
    merge(!mv.empty() ? &mv[0] : 0, mv.size(), _dst);
}    
Exemplo n.º 9
0
void erase(pnode &t,int key){
	if(!t)return;
	else if(t->val==key){pnode temp=t;merge(t,t->l,t->r);free(temp);}
	else erase(t->val<key?t->r:t->l,key);
	upd_sz(t);
}
Exemplo n.º 10
0
static void* my_merge_server_conf(apr_pool_t* pool, void* BASE, void* ADD) {
    log_debug("Merging server config");
    return merge(pool, BASE, ADD);
}
Exemplo n.º 11
0
Arquivo: dip4.cpp Projeto: hoijui/DIP
static Mat inverseAndWiener(Mat& s, Mat& p, double snr, bool inverse) {

	const bool wiener = !inverse;

	// Pad input image to avoid ringing artifacts along image borders.
	int bH = p.cols;
	int bV = p.rows;
	Mat sBorder;
	copyMakeBorder(s, sBorder, bV, bV, bH, bH, BORDER_REPLICATE);

	// Allocate some memory like it is going out of style.
	Mat pBigShifted = Mat::zeros(sBorder.size(), CV_32F);
	Mat P = Mat::zeros(sBorder.size(), CV_32F);
	Mat S = Mat::zeros(sBorder.size(), CV_32F);
	Mat OApprox = Mat::zeros(sBorder.size(), CV_32F);
	Mat oApprox = Mat::zeros(sBorder.size(), CV_32F);

	// Shift kernel.
	const int pHalf = p.rows / 2;
	circShiftXXX(p, pBigShifted, -pHalf, -pHalf);

	// Transform shifted kernel and degrated input image into frequency domain.
	// Note: DFT_COMPLEX_OUTPUT means that we want the complex result to be stored
	//       in a two-channel matrix as opposed to the default compressed output.
	dft(pBigShifted, P, DFT_COMPLEX_OUTPUT);
	dft(sBorder, S, DFT_COMPLEX_OUTPUT);

	if (inverse) {
		const double epsilon = 0.05f;

		// Remove frequencies whose magnitude is below epsilon * max(freqKernel magnitude).
		double maxMagnitude;
		minMaxLoc(abs(P), 0, &maxMagnitude);

		const double threshold =  maxMagnitude * epsilon;
		for (int ri = 0; ri < P.rows; ri++) {
			for (int ci = 0; ci < P.cols; ci++) {
				if (norm(P.at<Vec2f>(ri, ci)) < threshold) {
					P.at<Vec2f>(ri, ci) = threshold;
				}
			}
		}
	}

	// OpenCV only provides a multiplication operation for complex matrices, so we need
	// to calculate the inverse (1/H) of our filter spectrum first. Since it is complex
	// we need to compute 1/H = H*/(HH*) = H*/(Re(H)^2+Im(H)^2), where H* -> complex conjugate of H.

	// Multiply spectrum of the degrated image with the complex conjugate of the frequency spectrum
	// of the filter.
	const bool conjFreqKernel = true;
	mulSpectrums(S, P, OApprox, DFT_COMPLEX_OUTPUT, conjFreqKernel); // I * H*

	// Split kernel spectrum into real and imaginary parts.
	Mat PChannels[] = {Mat::zeros(sBorder.size(), CV_32F), Mat::zeros(sBorder.size(), CV_32F)};
	split(P, PChannels); // 0:real, 1:imaginary

	// Calculate squared magnitude (Re(H)^2 + Im(H)^2) of filter spectrum.
	Mat freqKernelSqMagnitude = Mat::zeros(sBorder.rows, sBorder.cols, CV_32F);
	magnitude(PChannels[0], PChannels[1], freqKernelSqMagnitude); // freqKernelSqMagnitude = magnitude
	pow(PChannels[0], 2, freqKernelSqMagnitude); // freqKernelSqMagnitude = magnitude^2 = Re(H)^2 + Im(H)^2

	if (wiener) {
		// Add 1 / SNR^2 to the squared filter kernel magnitude.
		freqKernelSqMagnitude += 1 / pow(snr, 2.0);
	}

	// Split frequency spectrum of degradedPadded image into real and imaginary parts.
	Mat OApproxChannels[] = {Mat::zeros(sBorder.size(), CV_32FC1), Mat::zeros(sBorder.size(), CV_32F)};
	split(OApprox, OApproxChannels);

	// Divide each plane by the squared magnitude of the kernel frequency spectrum.
	// What we have done up to this point: (I * H*) / (Re(H)^2 + Im(H)^2) = I/H
	divide(OApproxChannels[0], freqKernelSqMagnitude, OApproxChannels[0]); // Re(I) / (Re(H)^2 + Im(H)^2)
	divide(OApproxChannels[1], freqKernelSqMagnitude, OApproxChannels[1]); // Im(I) / (Re(H)^2 + Im(H)^2)

	// Merge real and imaginary parts of the image frequency spectrum.
	merge(OApproxChannels, 2, OApprox);

	// Inverse DFT.
	// Note: DFT_REAL_OUTPUT means that we want the output to be a one-channel matrix again.
	dft(OApprox, oApprox, DFT_INVERSE | DFT_SCALE | DFT_REAL_OUTPUT);

	// Crop output image to original size.
	oApprox = oApprox(Rect(bH, bV, oApprox.cols - (bH * 2), oApprox.rows - (bV * 2)));

	return oApprox;
}
Exemplo n.º 12
0
static void* my_merge_dir_conf(apr_pool_t* pool, void* BASE, void* ADD) {
    log_debug("Merging directory config");
    return merge(pool, BASE, ADD);
}
Exemplo n.º 13
0
void MergeStore::executePlanOperation() {
  auto t = checked_pointer_cast<const storage::Store>(getInputTable());
  auto store = std::const_pointer_cast<storage::Store>(t);
  store->merge();
  addResult(store);
}
Exemplo n.º 14
0
void multisort(long n, T data[n], T tmp[n]) {       
 if (n >= MIN_SORT_SIZE*4L) {
                // Recursive decomposition

		// Una tasca de tareador por cada llamada
#if _TAREADOR_
		tareador_start_task("multisort1");
#endif
                multisort(n/4L, &data[0], &tmp[0]);
#if _TAREADOR_
		tareador_end_task();
		tareador_start_task("multisort2");
#endif
                multisort(n/4L, &data[n/4L], &tmp[n/4L]);
#if _TAREADOR_
		tareador_end_task();
		tareador_start_task("multisort3");
#endif
                multisort(n/4L, &data[n/2L], &tmp[n/2L]);

#if _TAREADOR_
		tareador_end_task();
		tareador_start_task("multisort4");
#endif
                multisort(n/4L, &data[3L*n/4L], &tmp[3L*n/4L]);
#if _TAREADOR_
		tareador_end_task();
		tareador_start_task("merge1");
#endif
                merge(n/4L, &data[0], &data[n/4L], &tmp[0], 0, n/2L);

#if _TAREADOR_
                tareador_end_task();
                tareador_start_task("merge2");    
#endif
                merge(n/4L, &data[n/2L], &data[3L*n/4L], &tmp[n/2L], 0, n/2L);
#if _TAREADOR_
                tareador_end_task();
                tareador_start_task("merge3");    
#endif
                merge(n/2L, &tmp[0], &tmp[n/2L], &data[0], 0, n);
#if _TAREADOR_
                tareador_end_task();    
#endif

	} else {
		// Base case
#if _EXTRAE_
		Extrae_event(PROGRAM, SORT);
#endif
#if _TAREADOR_
		tareador_start_task("basesort");
#endif
		basicsort(n, data);
#if _TAREADOR_
		tareador_end_task();
#endif
#if _EXTRAE_
		Extrae_event(PROGRAM, END);
#endif
	}
}
Exemplo n.º 15
0
void AlmostCliqueRule::apply() {
  init();
  
  bool terminate = false;
  
  while (!terminate && _connectivity.size() > 0) {
    WorkingCopyGraph::NodeMap<bool> candidate(_instance.getGraph(), false);
    WorkingCopyGraph::NodeMap<double> connectivityCandidate(_instance.getGraph(), 0.0);
    
    
    
    WorkingCopyGraph::Node start = _connectivity.top();
    _connectivity.pop();
    
    
    candidate[start] = true;
    
    double prevConnectivity = 0;
    
    
    WorkingCopyGraph::Node u = findNodeMaxConnectivity(start, candidate, connectivityCandidate);
    if(u == INVALID) {
      terminate = true;
      
    }
    while (u != INVALID && connectivityCandidate[u] >= prevConnectivity && !terminate) {
      candidate[u] = true;
      
      prevConnectivity = connectivityCandidate[u];
      
      //if u is connected to more nodes in V\C than to nodes in C terminate!
      int internal = 0;
      int external = 0;
      
      for(WorkingCopyGraph::IncEdgeIt uv(_instance.getGraph(), u); uv != INVALID; ++uv) {
        if(_instance.getWeight(uv) <= 0) {
          continue;
        }
        
        WorkingCopyGraph::Node v = _instance.getGraph().oppositeNode(u, uv);
        if(candidate[v]) {
          internal++;
        } else {
          external++;
        }
      }
      
      int bound = (int) ceil((double) countNodes(_instance.getGraph()) / 2)* internal;
      if(bound <= external) {
        terminate = true;
      } else {
        u = findNodeMaxConnectivity(u, candidate, connectivityCandidate);
        if(u == INVALID) {
          terminate = true;
        }
      }
    }
    
    if(mapCount(_instance.getGraph(), candidate, true) < 2) {
      continue;
    }
    
    double cost = computeCost(candidate);
    double minCutValue = computeMinCutValue(candidate);
    
    if ((cost <= minCutValue && !_conserveMultipleSolutions) || (cost < minCutValue && _conserveMultipleSolutions)) {
      _success = true;
      merge(candidate);
    }
  }
}
Exemplo n.º 16
0
/*
|| Extract the file from the tape
*/
int
getfile( FILE *outf )
{
    SLFMT fmt;
    SLLABEL lab;
    unsigned char *ptr;
    int fileno;
    int rc;
    
    /*
    || Skip to the desired file
    */
    if( opts.flags & O_NL )
    {
        /*
        || For NL tapes, just use the specified file number
        */
        fileno = opts.fileno;

        /*
        || Start skipping
        */
        while( --fileno )
        {
            /*
            || Forward space to beginning of next file
            */
            if ( opts.faketape )
                rc = fet_fsf ( opts.fetb );
            else
                rc = het_fsf( opts.hetb );
            if( rc < 0 )
            {
                char msgbuf[128];
                MSGBUF( msgbuf, "%set_fsf() while positioning to file '%d'", 
                    opts.faketape ? "f" : "h",
                    opts.fileno ); 
                WRMSG( HHC00075, "E", msgbuf, het_error( rc ) );
                return( rc );
            }
        }
    }
    else
    {
        /*
        || First block should be a VOL1 record
        */
        rc = get_sl( &lab );
        if( rc < 0 || !sl_isvol( &lab, 1 ) )
        {
            WRMSG( HHC02753, "E", "VOL1" );
            return( -1 );
        }

        /*
        || For SL, adjust the file # so we end up on the label before the data
        */
        fileno = ( opts.fileno * 3 ) - 2;

        /*
        || Start skipping
        */
        while( --fileno )
        {
            /*
            || Forward space to beginning of next file
            */
            if ( opts.faketape )
                rc = fet_fsf ( opts.fetb );
            else
                rc = het_fsf( opts.hetb );
            if( rc < 0 )
            {
                char msgbuf[128];
                MSGBUF( msgbuf, "%set_fsf() while positioning to file '%d'", 
                    opts.faketape ? "f" : "h",
                    opts.fileno ); 
                WRMSG( HHC00075, "E", msgbuf, het_error( rc ) );
                return( rc );
            }
        }

        /*
        || Get the HDR1 label.
        */
        rc = get_sl( &lab );
        if( rc < 0 || !sl_ishdr( &lab, 1 ) )
        {
            WRMSG( HHC02753, "E", "HDR1" );
            return( -1 );
        }

        /*
        || Make the label more managable
        */
        sl_fmtlab( &fmt, &lab );
        WRMSG( HHC02754, "E", fmt.slds1.dsid ); 
    
        /*
        || Get the HDR2 label.
        */
        rc = get_sl( &lab );
        if( rc < 0 || !sl_ishdr( &lab, 2 ) )
        {
            WRMSG( HHC02753, "E", "HDR2" );
            return( -1 );
        }
    
        /*
        || Merge the DCB information
        */
        merge( &lab );

        /*
        || Hop over the tapemark
        */
        if ( opts.faketape )
            rc = fet_fsf( opts.fetb );
        else
            rc = het_fsf( opts.hetb );
        if( rc < 0 )
        {
            if ( opts.faketape )
                WRMSG( HHC00075, "E", "fet_fsf()", fet_error( rc ) );
            else
                WRMSG( HHC00075, "E", "het_fsf()", het_error( rc ) );
            return( rc );
        }
    }

    /*
    || Different processing when converting to ASCII
    */
    if( opts.flags & ( O_ASCII | O_UNBLOCK ) )
    {
        /*
        || Get a record
        */
        while( ( rc = getrecord( ) ) >= 0 )
        {
#ifdef EXTERNALGUI
            if( extgui )
            {
                off_t curpos;
                /* Report progress every nnnK */
                if ( opts.faketape )
                    curpos = ftell( opts.fetb->fd ); 
                else
                    curpos = ftell( opts.hetb->fd );
                if( ( curpos & PROGRESS_MASK ) != ( prevpos & PROGRESS_MASK ) )
                {
                    prevpos = curpos;
                    fprintf( stderr, "IPOS=%" I64_FMT "d\n", (U64)curpos );
                }
            }
#endif /*EXTERNALGUI*/
            /*
            || Get working copy of record ptr
            */
            ptr = recptr;

            /*
            || Only want data portion for RECFM=V records
            */
            if( opts.recfm & O_VARIABLE )
            {
                ptr += 4;
                rc -= 4;
            }

            /*
            || Convert record to ASCII
            */
            if( opts.flags & O_ASCII )
            {
                sl_etoa( NULL, ptr, rc );
            }

            /*
            || Strip trailing blanks
            */
            if( opts.flags & O_STRIP )
            {
                while( rc > 0 && ptr[ rc - 1 ] == ' ' )
                {
                    rc--;
                }
            }
            
            /*
            || Write the record out
            */
            fwrite( ptr, rc, 1, outf );

            /*
            || Put out a linefeed when converting
            */
            if( opts.flags & O_ASCII )
            {
                fwrite( "\n", 1, 1, outf );
            }
        }
    }
    else
    {
        /*
        || Get a record
        */
        while( ( rc = getblock( ) ) >= 0 )
        {
#ifdef EXTERNALGUI
            if( extgui )
            {
                off_t curpos;
                /* Report progress every nnnK */
                if ( opts.faketape )
                    curpos = ftell( opts.fetb->fd );
                else
                    curpos = ftell( opts.hetb->fd );
                if( ( curpos & PROGRESS_MASK ) != ( prevpos & PROGRESS_MASK ) )
                {
                    prevpos = curpos;
                    fprintf( stderr, "IPOS=%" I64_FMT "d\n", (U64)curpos );
                }
            }
#endif /*EXTERNALGUI*/
            /*
            || Write the record out
            */
            fwrite( blkptr, blklen, 1, outf );
        }
    }

    return( rc );
}
Exemplo n.º 17
0
void solve(int lim) {

	if ( lim < 10 ) {
		if ( TABLE[lim] == -1 )
			printf("IMPOSSIBLE\n");
		else
			printf("%d 1\n", TABLE[lim]);
		return;
	}

	static int dig[12];
	int n_dig = 0;
	{
		int tmp = lim;
		while ( tmp ) {
			dig[++ n_dig] = tmp % 10, tmp /= 10;
		}
	}
	Matrix res;
	bool first = true;
	int cur_s = 0, pre_s = 0;
	bool pre_nine = false;
	for ( int i = n_dig; i >= 2; i -- ) {
		if ( i != n_dig )
			cur_s |= 1 << dig[i + 1];
		if ( first ) {
			res = dp(i - 1, cur_s);
			pre_nine = i > 2;
			first = false;
		} else if ( dig[i] != 0 ) {
			res = merge(res, dp(i - 1, cur_s), pre_s, pre_nine);
			pre_nine = i > 2;
			pre_s = cur_s;
		}
		for ( int j = 1; j < dig[i]; j ++ ) {
			res = merge(res, dp(i - 1, cur_s | (1 << j)), pre_s, pre_nine);
			pre_nine = i > 2;
			pre_s = cur_s | (1 << j);
		}
	}

	int delta;
	for ( int i = 2; i <= n_dig; i ++ ) {
		if ( dig[i] != 0 ) {
			int tmp = 0;
			for ( int j = n_dig; j > i; j -- )
				tmp = tmp * 10 + dig[j];
			tmp = tmp * 10 + dig[i] - 1;
			for ( int j = i - 1; j >= 2; j -- )
				tmp = tmp * 10 + 9;
			tmp *= 10;
			delta = tmp;
			break;
		}
	}
	Info f[10];
	for ( int i = 0; i <= 9; i ++ ) {
		Info I = res.ele[1][i];
		I.val ++;
		int real = delta + i;
		int s = get_mask(real);
		for ( int x = 1; x <= 9; x ++ )
			if ( s & (1 << x) ) 
				if ( x + i >= 10 ) {
					f[x + i - 10].update(I);
				}
	}

	for ( int i = 0; delta + 10 + i <= lim; i ++ ) {
		int real = delta + 10 + i;
		int s = get_mask(real);
		Info I = f[i];
		I.val ++;
		for ( int x = 1; x <= 9; x ++ )
			if ( s & (1 << x) ) 
				if ( x + i <= 9 ) {
					f[x + i].update(I);
				}
	}
	int des = lim - delta - 10;
	if ( f[des].val == inf )
		printf("IMPOSSIBLE\n");
	else
		printf("%d %d\n", f[des].val, f[des].ways);
}
Exemplo n.º 18
0
static void updateTsFiles(const Translator &fetchedTor, const QStringList &tsFileNames,
    const QByteArray &codecForTr, const QString &sourceLanguage, const QString &targetLanguage,
    UpdateOptions options, bool *fail)
{
    QDir dir;
    QString err;
    foreach (const QString &fileName, tsFileNames) {
        QString fn = dir.relativeFilePath(fileName);
        ConversionData cd;
        Translator tor;
        cd.m_sortContexts = !(options & NoSort);
        if (QFile(fileName).exists()) {
            if (!tor.load(fileName, cd, QLatin1String("auto"))) {
                qWarning( "%s", qPrintable( cd.error() ) );
                *fail = true;
                continue;
            }
            tor.resolveDuplicates();
            cd.clearErrors();
            if (!codecForTr.isEmpty() && codecForTr != tor.codecName())
                qWarning("lupdate warning: Codec for tr() '%s' disagrees with "
                         "existing file's codec '%s'. Expect trouble.",
                         codecForTr.constData(), tor.codecName().constData());
            if (!targetLanguage.isEmpty() && targetLanguage != tor.languageCode())
                qWarning("lupdate warning: Specified target language '%s' disagrees with "
                         "existing file's language '%s'. Ignoring.",
                         qPrintable(targetLanguage), qPrintable(tor.languageCode()));
            if (!sourceLanguage.isEmpty() && sourceLanguage != tor.sourceLanguageCode())
                qWarning("lupdate warning: Specified source language '%s' disagrees with "
                         "existing file's language '%s'. Ignoring.",
                         qPrintable(sourceLanguage), qPrintable(tor.sourceLanguageCode()));
        } else {
            if (!codecForTr.isEmpty())
                tor.setCodecName(codecForTr);
            if (!targetLanguage.isEmpty())
                tor.setLanguageCode(targetLanguage);
            if (!sourceLanguage.isEmpty())
                tor.setSourceLanguageCode(sourceLanguage);
        }
        tor.makeFileNamesAbsolute(QFileInfo(fileName).absoluteDir());
        if (options & NoLocations)
            tor.setLocationsType(Translator::NoLocations);
        else if (options & RelativeLocations)
            tor.setLocationsType(Translator::RelativeLocations);
        else if (options & AbsoluteLocations)
            tor.setLocationsType(Translator::AbsoluteLocations);
        if (options & Verbose)
            printOut(QObject::tr("Updating '%1'...\n").arg(fn));

        if (tor.locationsType() == Translator::NoLocations) // Could be set from file
            options |= NoLocations;
        Translator out = merge(tor, fetchedTor, options, err);
        if (!codecForTr.isEmpty())
            out.setCodecName(codecForTr);

        if ((options & Verbose) && !err.isEmpty()) {
            printOut( qPrintable( err ) );
            err.clear();
        }
        if (options & PluralOnly) {
            if (options & Verbose)
                printOut(QObject::tr("Stripping non plural forms in '%1'...\n").arg(fn));
            out.stripNonPluralForms();
        }
        if (options & NoObsolete)
            out.stripObsoleteMessages();
        out.stripEmptyContexts();

        if (!out.save(fileName, cd, QLatin1String("auto"))) {
            qWarning( "%s", qPrintable( cd.error() ) );
            *fail = true;
        }
    }
Exemplo n.º 19
0
void BVHBuild::rotate(BVHNode *node, int max_depth)
{
	/* nothing to rotate if we reached a leaf node. */
	if(node->is_leaf() || max_depth < 0)
		return;
	
	InnerNode *parent = (InnerNode*)node;

	/* rotate all children first */
	for(size_t c = 0; c < 2; c++)
		rotate(parent->children[c], max_depth-1);

	/* compute current area of all children */
	BoundBox bounds0 = parent->children[0]->m_bounds;
	BoundBox bounds1 = parent->children[1]->m_bounds;

	float area0 = bounds0.half_area();
	float area1 = bounds1.half_area();
	float4 child_area = make_float4(area0, area1, 0.0f, 0.0f);

	/* find best rotation. we pick a target child of a first child, and swap
	 * this with an other child. we perform the best such swap. */
	float best_cost = FLT_MAX;
	int best_child = -1, bets_target = -1, best_other = -1;

	for(size_t c = 0; c < 2; c++) {
		/* ignore leaf nodes as we cannot descent into */
		if(parent->children[c]->is_leaf())
			continue;

		InnerNode *child = (InnerNode*)parent->children[c];
		BoundBox& other = (c == 0)? bounds1: bounds0;

		/* transpose child bounds */
		BoundBox target0 = child->children[0]->m_bounds;
		BoundBox target1 = child->children[1]->m_bounds;

		/* compute cost for both possible swaps */
		float cost0 = merge(other, target1).half_area() - child_area[c];
		float cost1 = merge(target0, other).half_area() - child_area[c];

		if(min(cost0,cost1) < best_cost) {
			best_child = (int)c;
			best_other = (int)(1-c);

			if(cost0 < cost1) {
				best_cost = cost0;
				bets_target = 0;
			}
			else {
				best_cost = cost0;
				bets_target = 1;
			}
		}
	}

	/* if we did not find a swap that improves the SAH then do nothing */
	if(best_cost >= 0)
		return;

	/* perform the best found tree rotation */
	InnerNode *child = (InnerNode*)parent->children[best_child];

	swap(parent->children[best_other], child->children[bets_target]);
	child->m_bounds = merge(child->children[0]->m_bounds, child->children[1]->m_bounds);
}
Exemplo n.º 20
0
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
	return merge(lists,0,listsSize-1);
}
Exemplo n.º 21
0
	bbox_t& merge(const bbox_t &box) {
		merge(box.min_point);
		merge(box.max_point);
		return *this;
	}
Exemplo n.º 22
0
LeftistHeap< Comparable > ::LeftistHeap( const LeftistHeap<Comparable> & rhs )
{
    root = NULL;
    root = merge(root,rhs.root);
}
Exemplo n.º 23
0
 __device__ static void loop(Pointer smem, Reference val, uint tid, Op op)
 {
     merge(smem, val, tid, I, op);
     Unroll<I / 2, Pointer, Reference, Op>::loop(smem, val, tid, op);
 }
Exemplo n.º 24
0
void LeftistHeap< Comparable >::Insert(const Comparable &x)
{
    root = merge(new LeftistNode< Comparable >(x),root);
}
Exemplo n.º 25
0
		/**
		 * Append bytes to the buffer. The buffer is stretched if necessary.
		 * Bytes are read from a source databuf.
		 * @return SUCCESS or FAILURE if no memory is available
		 * to stretch the buffer.
		 */
		int32 merge(DataBuf* b)
		{
			return merge((char *) b->getAddr(), b->getCount());
		}
Exemplo n.º 26
0
void ParallelSort::Sorter(vector<T> & array)
{
	int size=array.size();
	int sortsize=size/8;

	#pragma omp parallel sections
	{
		#pragma omp section
		{
			modified_quicksort(array, 0, sortsize-1);
		}
		#pragma omp section
		{
			modified_quicksort(array, sortsize, sortsize*2-1);
		}
		#pragma omp section
		{
			modified_quicksort(array, sortsize*2, sortsize*3-1);
		}
		#pragma omp section
		{
			modified_quicksort(array, sortsize*3, sortsize*4-1);
		}
		#pragma omp section
		{
			modified_quicksort(array, sortsize*4, sortsize*5-1);
		}
		#pragma omp section
		{
			modified_quicksort(array, sortsize*5, sortsize*6-1);
		}
		#pragma omp section
		{
			modified_quicksort(array, sortsize*6, sortsize*7-1);
		}
		#pragma omp section
		{
			modified_quicksort(array, sortsize*7, size-1);
		}
	}

	#pragma omp parallel sections
	{
		#pragma omp section
		{
			merge(array, 0, (2*sortsize-1)/2, sortsize*2-1);
		}
		#pragma omp section
		{
			merge(array, sortsize*2, (6*sortsize-1)/2, sortsize*4-1);
		}
		#pragma omp section
		{
			merge(array, sortsize*4, (10*sortsize-1)/2, sortsize*6-1);
		}
		#pragma omp section
		{
			merge(array, sortsize*6, sortsize*7-1, size-1);
		}
	}

	#pragma omp parallel sections
	{
		#pragma omp section
		{
			merge(array, 0, (4*sortsize-1)/2, sortsize*4-1);
		}
		#pragma omp section
		{
			merge(array, sortsize*4, sortsize*6-1, size-1);
		}
	}
	//#pragma omp single
			merge(array, 0, sortsize*4-1, size-1);
}
Exemplo n.º 27
0
//--------------------------------------------------------------------------
void BoundingBoxTests::testOperations()
{
  // Check the center
  CPPUNIT_ASSERT_EQUAL(true, vector::eq(Vector3f(1.5f, 1.5f, 1.5f), a2.center()));
  CPPUNIT_ASSERT_EQUAL(true, vector::eq(Vector3f(0), a4.center()));
  Vector3f c(AABB3f::DUMMY.center());
  for (size_t i = 0_z; i < 3_z; ++i)
    {
      CPPUNIT_ASSERT_EQUAL(true, std::isnan(c[i]));
    }

  // Check volume comparaison
  CPPUNIT_ASSERT_EQUAL(1.0f, a2.volume());
  CPPUNIT_ASSERT_EQUAL(4.0f * 4.0f * 4.0f, (a2 * 4.0f).volume());
  a5 =  a2 * 4.0f;
  CPPUNIT_ASSERT_EQUAL(true, (a5 > a2));
  CPPUNIT_ASSERT_EQUAL(false, (a5 < a2));
  CPPUNIT_ASSERT_EQUAL(true, (a2 >= a3));
  CPPUNIT_ASSERT_EQUAL(true, (a2 <= a3));
  CPPUNIT_ASSERT_EQUAL(true, (a2 == a3));
  CPPUNIT_ASSERT_EQUAL(true, (a6 > a3));

  // Check if a point is contained or not to an AABB.
  CPPUNIT_ASSERT_EQUAL(true, a2.contains(Vector3f(1.5f, 1.5f, 1.5f)));
  CPPUNIT_ASSERT_EQUAL(true, a2.contains(a2.center()));
  CPPUNIT_ASSERT_EQUAL(false, a2.contains(a2.center() * 3.0f));
  CPPUNIT_ASSERT_EQUAL(true, a6.contains(a2.center() * 3.0f));

  // Box containing others
  CPPUNIT_ASSERT_EQUAL(true, a1.contains(a1));
  CPPUNIT_ASSERT_EQUAL(false, a8.contains(a1));
  CPPUNIT_ASSERT_EQUAL(true, a6.contains(a1));
  CPPUNIT_ASSERT_EQUAL(false, AABB3f(0, 1).contains(AABB3f(1, 2))); // corner case

  // Clamp
  //checkBox(clamp(a1, a1.m_bbmin, a1.m_bbmax), a1.m_bbmin, a1.m_bbmax);
  //checkBox(clamp(a1 * 4.0f, a1.m_bbmin, a1.m_bbmax), a1.m_bbmin, a1.m_bbmax);

  // Box collisions
  CPPUNIT_ASSERT_EQUAL(false, a2.collides(a4));
  CPPUNIT_ASSERT_EQUAL(true, a2.collides(AABB3f(Vector3f(2,2,2), Vector3f(3,3,3))));
  CPPUNIT_ASSERT_EQUAL(true, a6.collides(a4));

  checkBox(intersection(a3, a3), a3.m_bbmin, a3.m_bbmax);
  checkBox(merge(a3, a3), a3.m_bbmin, a3.m_bbmax);
  checkBox(intersection(a3, a6), a3.m_bbmin, a3.m_bbmax);

  checkBox(merge(a6, a6), a6.m_bbmin, a6.m_bbmax);
  checkBox(merge(a6, a3), a6.m_bbmin, a6.m_bbmax);
  checkBox(merge(a3, a6), a6.m_bbmin, a6.m_bbmax);
  checkBox(intersection(a6, a3), a3.m_bbmin, a3.m_bbmax);
  checkBox(intersection(a3, a6), a3.m_bbmin, a3.m_bbmax);
  checkBox(merge(a2, a3), a3.m_bbmin, a2.m_bbmax);

  // Try intersection with disjoint AABB.
  checkBoxDummy(intersection(a2, a3));
  checkBoxDummy(intersection(a5, a3));

  // Check intersecation at an AABB corner.
  checkBox(intersection(a7, AABB3f(0, 1)), Vector3f(1), Vector3f(1));
  checkBox(intersection(AABB3f(0, 1), AABB3f(-1, 0)), Vector3f(0), Vector3f(0));

  // AABB collisions
  CPPUNIT_ASSERT_EQUAL(true, a4.collides(a4));
  CPPUNIT_ASSERT_EQUAL(false, a4.collides(a2));
  CPPUNIT_ASSERT_EQUAL(false, a2.collides(a4));
  CPPUNIT_ASSERT_EQUAL(true, a2.collides(AABB3f(Vector3f(2,2,2), Vector3f(3,3,3))));
  CPPUNIT_ASSERT_EQUAL(true, a6.collides(a4));
  CPPUNIT_ASSERT_EQUAL(true, a4.collides(a6));

  //

  CPPUNIT_ASSERT_EQUAL(std::numeric_limits<float>::infinity(), a6.volume());
  CPPUNIT_ASSERT_EQUAL(true, vector::eq(Vector3f(std::numeric_limits<float>::infinity()),
                                        a6.size()));
}
Exemplo n.º 28
0
// resolves collisions between bodies, returning new body count
int collide(int n, body bodies[]) {
  // initialize disjoint set and bodies to include
  set* bsets[n];
  int include[n];
  for (int i = 0; i < n; i++) {
    bsets[i] = make_set(i);
    include[i] = 1;
  }

  // find largest object
  double maxrad = RADIUS(bodies[0].m);
  for (int i = 0; i < n; i++) {
    double rad = RADIUS(bodies[i].m);
    if (rad > maxrad)
      maxrad = rad;
  }

  // form mesh for collision detection
  mesh* m = mesh_new(maxrad * 2);
  for (int i = 0; i < n; i++)
    mesh_put(m, bodies[i].pos, i);

  // find collisions
  for (int i = 0; i < n; i++) {
    vector ipos = bodies[i].pos;
    double irad = RADIUS(bodies[i].m);

    // which bodies are in contact with this one?
    // look up position in mesh
    body_list* next = mesh_get(m, ipos, 1);
    for (body_list* cur = next; cur; cur = next) {
      // get candidate collider
      int j = cur->index;
      vector jpos = bodies[j].pos;
      double jrad = RADIUS(bodies[j].m);

      // merge sets of colliding objects
      if (dist(ipos, jpos) < (irad + jrad) * (irad + jrad))
        merge(bsets[i], bsets[j]);

      // traverse and free
      next = cur->next;
      free(cur);
    }
  }

  // free the mesh
  mesh_free(m);

  // merge objects
  for (int i = 0; i < n; i++) {
    int rootidx = get_value(find(bsets[i]));
    if (rootidx != i) {
      include[i] = 0;
      bodies[rootidx] = body_merge(bodies[rootidx], bodies[i]);
    }
  }

  // free sets
  for (int i = 0; i < n; i++)
    free(bsets[i]);

  // copy down
  int j = 0;
  for (int i = 0; i < n; i++) {
    if (include[i])
      bodies[j++] = bodies[i];
  }

  return j;
}
Exemplo n.º 29
0
void cv::merge(const vector<Mat>& _mv, OutputArray _dst)
{
    merge(_InputArray(_mv), _dst);
}
Exemplo n.º 30
0
MergeResult *SparseOps::mergeProxy(JNIEnv *env, //
        jintArray slices, //
        jarray srcV, jintArray srcD, jintArray srcS, jintArray srcDo, //
        jintArray srcI, jintArray srcIo, jintArray srcIi, //
        jarray dstV, jintArray dstD, jintArray dstS, jintArray dstDo, //
        jintArray dstI, jintArray dstIo, jintArray dstIi) {

    MergeResult *mergeResult = NULL;

    try {

        jint srcLen = env->GetArrayLength(srcV);
        jint dstLen = env->GetArrayLength(dstV);
        jint nDims = env->GetArrayLength(srcD);
        jint srcIoLen = env->GetArrayLength(srcIo);
        jint dstIoLen = env->GetArrayLength(dstIo);

        jint nSlices = env->GetArrayLength(slices) / 3;

        if ((nDims != env->GetArrayLength(srcS))
                || (nDims != env->GetArrayLength(dstD))
                || (nDims != env->GetArrayLength(dstS))
                || (env->GetArrayLength(slices) % 3)
                || (srcLen != env->GetArrayLength(srcI))
                || (dstLen != env->GetArrayLength(dstI))
                || (nDims + 1 != env->GetArrayLength(srcDo))
                || (nDims * srcLen != env->GetArrayLength(srcIi))
                || (nDims + 1 != env->GetArrayLength(dstDo))
                || (nDims * dstLen != env->GetArrayLength(dstIi))) {
            throw std::runtime_error("Invalid arguments");
        }

        ArrayPinHandler slicesH(env, slices, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler srcDh(env, srcD, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler srcSh(env, srcS, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler srcIh(env, srcI, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler srcDoh(env, srcDo, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler srcIoh(env, srcIo, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler srcIih(env, srcIi, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler dstDh(env, dstD, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler dstSh(env, dstS, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler dstIh(env, dstI, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler dstDoh(env, dstDo, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler dstIoh(env, dstIo, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);
        ArrayPinHandler dstIih(env, dstIi, ArrayPinHandler::PRIMITIVE, ArrayPinHandler::READ_ONLY);

        jint *slicesArr = (jint *) slicesH.get();
        jint *srcDArr = (jint *) srcDh.get();
        jint *srcSArr = (jint *) srcSh.get();
        jint *srcIArr = (jint *) srcIh.get();
        jint *srcDoArr = (jint *) srcDoh.get();
        jint *srcIoArr = (jint *) srcIoh.get();
        jint *srcIiArr = (jint *) srcIih.get();
        jint *dstDArr = (jint *) dstDh.get();
        jint *dstSArr = (jint *) dstSh.get();
        jint *dstIArr = (jint *) dstIh.get();
        jint *dstDoArr = (jint *) dstDoh.get();
        jint *dstIoArr = (jint *) dstIoh.get();
        jint *dstIiArr = (jint *) dstIih.get();

        if ((srcIoLen != Common::sum(srcDArr, nDims, (jint) 0) + nDims)
                || (dstIoLen != Common::sum(dstDArr, nDims, (jint) 0) + nDims)) {
            throw std::runtime_error("Invalid arguments");
        }

        MappingOps::checkDimensions(srcDArr, srcSArr, nDims, Common::product(srcDArr, nDims, (jint) 1));
        MappingOps::checkDimensions(dstDArr, dstSArr, nDims, Common::product(dstDArr, nDims, (jint) 1));

        for (jint i = 0, n = 3 * nSlices; i < n; i += 3) {

            jint srcIndex = slicesArr[i];
            jint dstIndex = slicesArr[i + 1];
            jint dim = slicesArr[i + 2];

            if (!(dim >= 0 && dim < nDims)) {
                throw std::runtime_error("Invalid dimension");
            }

            if (!(srcIndex >= 0 && srcIndex < srcDArr[dim])
                    || !(dstIndex >= 0 && dstIndex < dstDArr[dim])) {
                throw std::runtime_error("Invalid index");
            }
        }

        for (jint dim = 0; dim < nDims; dim++) {

            if ((srcDoArr[dim + 1] - srcDoArr[dim] - 1 != srcDArr[dim])
                    || (dstDoArr[dim + 1] - dstDoArr[dim] - 1 != dstDArr[dim])) {
                throw std::runtime_error("Invalid arguments");
            }
        }

        //

        jint offsetArrayLen = srcDoArr[nDims];

        MallocHandler all0H(sizeof(jint) * (2 * nDims + 2 * offsetArrayLen + 1 + srcLen + dstLen));
        jint *all0 = (jint *) all0H.get();
        jint *srcSliceCounts = all0;
        jint *lookupCounts = all0 + nDims;
        jint *sliceOffsets = all0 + nDims + offsetArrayLen;
        jint *lookupOffsets = all0 + 2 * nDims + offsetArrayLen + 1;
        jint *srcIndirections = all0 + 2 * nDims + 2 * offsetArrayLen + 1;
        jint *dstIndirections = all0 + 2 * nDims + 2 * offsetArrayLen + 1 + srcLen;

        memset(srcSliceCounts, 0, sizeof(jint) * nDims);
        memset(lookupCounts, 0, sizeof(jint) * offsetArrayLen);

        for (jint i = 0, n = 3 * nSlices; i < n; i += 3) {

            jint srcIndex = slicesArr[i];
            jint dim = slicesArr[i + 2];

            srcSliceCounts[dim]++;
            lookupCounts[srcDoArr[dim] + srcIndex]++;
        }

        //

        jint sliceOffset = 0;
        jint lookupOffset = 0;

        for (jint dim = 0; dim < nDims; dim++) {

            sliceOffsets[dim] = sliceOffset;
            sliceOffset += srcSliceCounts[dim];

            jint dimSize = srcDArr[dim];

            for (jint dimIndex = 0; dimIndex < dimSize; dimIndex++) {

                lookupOffsets[srcDoArr[dim] + dimIndex] = lookupOffset;
                lookupOffset += lookupCounts[srcDoArr[dim] + dimIndex];
            }

            lookupOffsets[srcDoArr[dim] + dimSize] = lookupOffset;
        }

        sliceOffsets[nDims] = sliceOffset;

        //

        MallocHandler all1H(sizeof(jint) * (2 * sliceOffset + nDims + lookupOffset));
        jint *all1 = (jint *) all1H.get();
        jint *srcSlices = all1;
        jint *dstSlices = all1 + sliceOffset;
        jint *dstSliceCounts = all1 + 2 * sliceOffset;
        jint *dstLookups = all1 + 2 * sliceOffset + nDims;

        memset(srcSliceCounts, 0, sizeof(jint) * nDims);
        memset(lookupCounts, 0, sizeof(jint) * offsetArrayLen);

        for (jint i = 0, n = 3 * nSlices; i < n; i += 3) {

            jint srcIndex = slicesArr[i];
            jint dstIndex = slicesArr[i + 1];
            jint dim = slicesArr[i + 2];

            srcSlices[sliceOffsets[dim] + srcSliceCounts[dim]] = srcIndex;
            dstSlices[sliceOffsets[dim] + srcSliceCounts[dim]] = dstIndex;
            dstLookups[lookupOffsets[srcDoArr[dim] + srcIndex] + lookupCounts[srcDoArr[dim] + srcIndex]] = dstIndex;

            srcSliceCounts[dim]++;
            lookupCounts[srcDoArr[dim] + srcIndex]++;
        }

        //

        memset(srcSliceCounts, 0, sizeof(jint) * nDims);
        memset(lookupCounts, 0, sizeof(jint) * offsetArrayLen);

        for (jint dim = 0; dim < nDims; dim++) {

            srcSliceCounts[dim] = normalize(srcSlices, sliceOffsets[dim], sliceOffsets[dim + 1]);
            dstSliceCounts[dim] = normalize(dstSlices, sliceOffsets[dim], sliceOffsets[dim + 1]);

            for (jint dimIndex = 0, dimSize = srcDArr[dim]; dimIndex < dimSize; dimIndex++) {
                lookupCounts[srcDoArr[dim] + dimIndex] = normalize(dstLookups, //
                        lookupOffsets[srcDoArr[dim] + dimIndex], //
                        lookupOffsets[srcDoArr[dim] + dimIndex + 1]);
            }
        }

        //

        jint nSrcIndirections;

        getSlicedIndirections(sliceOffsets, srcSliceCounts, srcSlices, //
                srcDoArr, srcIoArr, srcIiArr, srcLen, //
                srcDArr, nDims, //
                srcIndirections, nSrcIndirections);

        jint nDstIndirections;

        getSlicedIndirections(sliceOffsets, dstSliceCounts, dstSlices, //
                dstDoArr, dstIoArr, dstIiArr, dstLen, //
                dstDArr, nDims, //
                dstIndirections, nDstIndirections);

        //

        MallocHandler all2H(sizeof(jint) * (nSrcIndirections + 1 + 2 * dstLen - 2 * nDstIndirections));
        jint *all2 = (jint *) all2H.get();
        jint *indirectionOffsets = all2;
        jint *oldIndices = all2 + nSrcIndirections + 1;
        jint *oldIndirections = all2 + nSrcIndirections + 1 + dstLen - nDstIndirections;

        jint indirectionOffset = 0;

        for (jint i = 0, prodD = Common::product(srcDArr, nDims, (jint) 1); i < nSrcIndirections; i++) {

            jint indirection = srcIndirections[i];

            if (!(indirection >= 0 && indirection < srcLen)) {
                throw std::runtime_error("Invalid indirection index");
            }

            jint physical = srcIArr[indirection];

            if (!(physical >= 0 && physical < prodD)) {
                throw std::runtime_error("Invalid physical index");
            }

            jint mapLen = 1;

            for (jint dim = 0; dim < nDims; dim++) {

                jint logicalIndex = physical / srcSArr[dim];

                mapLen *= lookupCounts[srcDoArr[dim] + logicalIndex];

                physical %= srcSArr[dim];
            }

            indirectionOffsets[i] = indirectionOffset;
            indirectionOffset += mapLen;
        }

        indirectionOffsets[nSrcIndirections] = indirectionOffset;

        //

        MallocHandler all3H(sizeof(jint) * (4 * indirectionOffset + nDims));
        jint *all3 = (jint *) all3H.get();
        jint *newIndirections = all3;
        jint *newIndices = all3 + indirectionOffset;
        jint *resNewIndirections = all3 + 2 * indirectionOffset;
        jint *resNewIndices = all3 + 3 * indirectionOffset;
        jint *logical = all3 + 4 * indirectionOffset;

        for (jint i = 0; i < nSrcIndirections; i++) {

            jint indirection = srcIndirections[i];
            jint physical = srcIArr[indirection];

            indirectionOffset = indirectionOffsets[i];

            newIndices[indirectionOffset] = 0;

            for (jint dim = 0; dim < nDims; dim++) {

                logical[dim] = physical / srcSArr[dim];

                newIndices[indirectionOffset] += dstSArr[dim] * dstLookups[lookupOffsets[srcDoArr[dim] + logical[dim]]];

                physical %= srcSArr[dim];
            }

            std::fill( //
                    newIndirections + indirectionOffsets[i], //
                    newIndirections + indirectionOffsets[i + 1], //
                    indirection);

            for (jint dim = nDims - 1, blockSize = 1, size; dim >= 0; blockSize *= size, dim--) {

                jint start = lookupOffsets[srcDoArr[dim] + logical[dim]];
                size = lookupCounts[srcDoArr[dim] + logical[dim]];

                for (jint offset = indirectionOffset + blockSize,
                        offsetEnd = indirectionOffset + blockSize * size, n = start + 1;
                        offset < offsetEnd;
                        offset += blockSize, n++) {

                    jint strideOffset = dstSArr[dim] * (dstLookups[n] - dstLookups[n - 1]);

                    for (jint j = offset - blockSize, k = offset; j < offset; j++, k++) {
                        newIndices[k] = newIndices[j] + strideOffset;
                    }
                }
            }
        }

        //

        if (nDstIndirections > 0) {

            jint count = 0;

            for (jint i = 0, n = dstIndirections[0]; i < n; i++, count++) {

                oldIndices[count] = dstIArr[i];
                oldIndirections[count] = i;
            }

            for (jint i = 0, n = nDstIndirections - 1; i < n; i++) {

                for (jint j = dstIndirections[i] + 1, m = dstIndirections[i + 1]; j < m; j++, count++) {

                    oldIndices[count] = dstIArr[j];
                    oldIndirections[count] = j;
                }
            }

            for (jint i = dstIndirections[nDstIndirections - 1] + 1, n = dstLen; i < n; i++, count++) {

                oldIndices[count] = dstIArr[i];
                oldIndirections[count] = i;
            }

        } else {

            memcpy(oldIndices, dstIArr, sizeof(jint) * dstLen);

            for (jint i = 0; i < dstLen; i++) {
                oldIndirections[i] = i;
            }
        }

        //

        jint resLen;

        merge(newIndices, newIndirections, indirectionOffsets[nSrcIndirections], //
                resNewIndices, resNewIndirections, resLen);

        mergeResult = merge(oldIndices, oldIndirections, dstLen - nDstIndirections,
                resNewIndices, resNewIndirections, resLen,
                dstDArr, dstSArr, dstDoArr, nDims);

        return mergeResult;

    } catch (...) {

        if (mergeResult) {
            delete mergeResult;
        }

        throw;
    }
}