//////////////////////////////
760578
public function
	Run($cmd=null) {
	/*//
	@argv string HandlerName
	@argv array CommandArgumentList

	if given a string it will execute the handler defined under as that name.
	if given an array then it will process that array as though it was the
	_SERVER['argv'] data and execute as if that was the original command line
	given to the object creation.
	//*/

		$restore = false;
		$return = 0;

		////////
		////////

		if(is_array($cmd)) {
			// rewrite our input and option data with this subcommand
			// that was given to us. execute as though this array defined
			// the original command input.

			$restore = [ 'Inputs'=>$this->Inputs, 'Options'=>$this->Options ];

			$data = static::ParseCommandArgs($cmd,false);
			$this->Inputs = $data['Inputs'];
			$this->Options = $data['Options'];

			$cmd = $this->GetInputs();
		}

		////////
		////////

		if(!$cmd && !($cmd = $this->GetInput(1))) {
			if(!$this->DefaultHandlerName) {
				echo "No input provided.", PHP_EOL;
				return static::ErrorNoInput;

			}

			$cmd = [$this->DefaultHandlerName];
		}

		else {
			$cmd = $this->GetInputs();
		}

		////////
		////////

		$Commanded = FALSE;

		foreach($cmd as $cur) {
			$method = static::GetMethodFromCommand($cur);
			try {
				$return = $this->Run_ByMethod($method);
				$Commanded = TRUE;
			}
			catch(ClientHandlerException $e) {
				try {
					$return = $this->Run_ByCallable($cur);
					$Commanded = TRUE;
				}
				catch(ClientHandlerException $e) { }
			}

			if($Commanded && !$this->ChainCommands)
			break;
		}

		if(!$Commanded) {
			echo "no handler or method found for {$cur}", PHP_EOL;
			return static::ErrorNoHandler;
		}

		////////
		////////

		if($restore) {
			// restore the original input data before continuing on so that
			// we could continue processing the cli input data if needed.
			$this->Inputs = $restore['Inputs'];
			$this->Options = $restore['Options'];
		}

		return $return;
	}
1327643
public static void main(String[] args) throws Exception {
		// parse the parameters
		final ParameterTool params = ParameterTool.fromArgs(args);
		final long windowSize = params.getLong("windowSize", 2000);
		final long rate = params.getLong("rate", 3L);

		System.out.println("Using windowSize=" + windowSize + ", data rate=" + rate);
		System.out.println("To customize example, use: WindowJoin [--windowSize <window-size-in-millis>] [--rate <elements-per-second>]");

		// obtain execution environment, run this example in "ingestion time"
		StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
		env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime);

		// make parameters available in the web interface
		env.getConfig().setGlobalJobParameters(params);

		// create the data sources for both grades and salaries
		DataStream<Tuple2<String, Integer>> grades = GradeSource.getSource(env, rate);
		DataStream<Tuple2<String, Integer>> salaries = SalarySource.getSource(env, rate);

		// run the actual window join program
		// for testability, this functionality is in a separate method.
		DataStream<Tuple3<String, Integer, Integer>> joinedStream = runWindowJoin(grades, salaries, windowSize);

		// print the results with a single thread, rather than in parallel
		joinedStream.print().setParallelism(1);

		// execute program
		env.execute("Windowed Join Example");
	}
789904
public static void main(String[] args)
    {
    	
    	// Override CQL version while instantiating entity manager factory.

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("twissandra,twingo,twirdbms");
        EntityManager em = emf.createEntityManager();

        try
        {
        	
        //populate user set from excel sheet.
        Set<User> users = UserBroker.brokeUserList(args[0]);

        for (Iterator<User> iterator = users.iterator(); iterator.hasNext();)
        {
            User user = (User) iterator.next();

            // on Persist
            ExecutorService.onPersist(em, user);
            
                 
            // on find by id.
            ExecutorService.findByKey(em,"BigDataUser");
            
            List<User> fetchedUsers = ExecutorService.onQueryByEmail(em, user);
            
            if (fetchedUsers != null && fetchedUsers.size() > 0)
            {
                logger.info(user.toString());
            }

            logger.info("");
            System.out.println("#######################Querying##########################################");
            logger.info("");
            logger.info("");

        }

        // Execute wild search query.
        String query = "Select u from User u";
        logger.info(query);
        ExecutorService.findByQuery(em, query);

        // // Execute native CQL. Fetch tweets for given user.
        logger.info("");
        System.out.println("#######################Querying##########################################");
        logger.info("");
        logger.info("");

        query = "Select * from tweets where user_id='RDBMSUser'";
        logger.info(query);
        ExecutorService.findByNativeQuery(em,query);
    	} finally
    	{
    		onDestroyDBResources(emf, em);
    	}
    }
1234050
@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        lblMessage = new javax.swing.JLabel();
        barProgressActivity = new javax.swing.JProgressBar();
        cmdCancelOperation = new javax.swing.JButton();

        setLayout(new java.awt.GridBagLayout());

        lblMessage.setText("Executing Query");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        add(lblMessage, gridBagConstraints);

        barProgressActivity.setIndeterminate(true);
        barProgressActivity.setMinimumSize(new java.awt.Dimension(200, 15));
        barProgressActivity.setPreferredSize(new java.awt.Dimension(300, 18));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
        add(barProgressActivity, gridBagConstraints);

        cmdCancelOperation.setText("Cancel Operation");
        cmdCancelOperation.setEnabled(false);
        cmdCancelOperation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	cmdCancelOperationActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0);
        add(cmdCancelOperation, gridBagConstraints);
    }
1183142
function onCreating(model, attrs, options) {
            if (!model.get('author_id')) {
                if (model.get('authors')) {
                    model.set('author_id', model.get('authors')[0].id);
                } else {
                    model.set('author_id', this.contextUser(options));
                }
            }

            if (!model.get('authors')) {
                model.set('authors', [{
                    id: model.get('author_id')
                }]);
            }

            return this._handleOptions('onCreating')(model, attrs, options);
        }
1095389
function(options)
        {
            if (!this._o) {
                this._o = extend({}, defaults, true);
            }

            var opts = extend(this._o, options, true);

            opts.isRTL = !!opts.isRTL;

            opts.field = (opts.field && opts.field.nodeName) ? opts.field : null;

            opts.bound = !!(opts.bound !== undefined ? opts.field && opts.bound : opts.field);

            opts.trigger = (opts.trigger && opts.trigger.nodeName) ? opts.trigger : opts.field;

            var nom = parseInt(opts.numberOfMonths, 10) || 1;
            opts.numberOfMonths = nom > 4 ? 4 : nom;

            if (!isDate(opts.minDate)) {
                opts.minDate = false;
            }
            if (!isDate(opts.maxDate)) {
                opts.maxDate = false;
            }
            if ((opts.minDate && opts.maxDate) && opts.maxDate < opts.minDate) {
                opts.maxDate = opts.minDate = false;
            }
            if (opts.minDate) {
                setToStartOfDay(opts.minDate);
                opts.minYear  = opts.minDate.getFullYear();
                opts.minMonth = opts.minDate.getMonth();
            }
            if (opts.maxDate) {
                setToStartOfDay(opts.maxDate);
                opts.maxYear  = opts.maxDate.getFullYear();
                opts.maxMonth = opts.maxDate.getMonth();
            }

            if (isArray(opts.yearRange)) {
                var fallback = new Date().getFullYear() - 10;
                opts.yearRange[0] = parseInt(opts.yearRange[0], 10) || fallback;
                opts.yearRange[1] = parseInt(opts.yearRange[1], 10) || fallback;
            } else {
                opts.yearRange = Math.abs(parseInt(opts.yearRange, 10)) || defaults.yearRange;
                if (opts.yearRange > 100) {
                    opts.yearRange = 100;
                }
            }

            return opts;
        }
593192
@Override
    public <P> void pojoDaoCreated(PojoDaoFactoryEvent<P> event) {
        String tableName = event.getTableName();
        Schema schema = new Schema();
        event.getPojoBinding().describe(schema.createTable(tableName), schema);

        schema.items().forEach(schemaItem -> {
            final String key = schemaItem.getKey();
            final String claimId = UUID.randomUUID().toString();
            session.execute(insertStatement.bind(key, claimId));
            Row row = session.execute(selectStatement.bind(key)).one();
            if (StringUtils.equals(claimId, row.getString(0))) {
                final SchemaStatement statement = schemaItem.createStatement();
                LOGGER.info("Creating table(s) to support \"{}\":\n\t{}\n", event.getPojoBinding().getPojoType().getSimpleName(), statement);
                session.execute(statement);
            }
        });
    }
317625
public static void main(String[] args) throws Exception {
    Builder processingGraphBuilder = Builder.newBuilder();

    // A KVStreamlet is produced. Each element is a KeyValue object where the key
    // is the impression ID and the user ID is the value.
    Streamlet<AdImpression> impressions = processingGraphBuilder
        .newSource(AdImpression::new);

    // A KVStreamlet is produced. Each element is a KeyValue object where the key
    // is the ad ID and the user ID is the value.
    Streamlet<AdClick> clicks = processingGraphBuilder
        .newSource(AdClick::new);

    /**
     * Here, the impressions KVStreamlet is joined to the clicks KVStreamlet.
     */
    impressions
        // The join function here essentially provides the reduce function with a streamlet
        // of KeyValue objects where the userId matches across an impression and a click
        // (meaning that the user has clicked on the ad).
        .join(
            // The other streamlet that's being joined to
            clicks,
            // Key extractor for the impressions streamlet
            impression -> impression.getUserId(),
            // Key extractor for the clicks streamlet
            click -> click.getUserId(),
            // Window configuration for the join operation
            WindowConfig.TumblingCountWindow(25),
            // Join type (inner join means that all elements from both streams will be included)
            JoinType.INNER,
            // For each element resulting from the join operation, a value of 1 will be provided
            // if the ad IDs match between the elements (or a value of 0 if they don't).
            (user1, user2) -> (user1.getAdId().equals(user2.getAdId())) ? 1 : 0
        )
        // The reduce function counts the number of ad clicks per user.
        .reduceByKeyAndWindow(
            // Key extractor for the reduce operation
            kv -> String.format("user-%s", kv.getKey().getKey()),
            // Value extractor for the reduce operation
            kv -> kv.getValue(),
            // Window configuration for the reduce operation
            WindowConfig.TumblingCountWindow(50),
            // A running cumulative total is calculated for each key
            (cumulative, incoming) -> cumulative + incoming
        )
        // Finally, the consumer operation provides formatted log output
        .consume(kw -> {
          LOG.info(String.format("(user: %s, clicks: %d)",
              kw.getKey().getKey(),
              kw.getValue()));
        });

    Config config = Config.defaultConfig();

    // Fetches the topology name from the first command-line argument
    String topologyName = StreamletUtils.getTopologyName(args);

    // Finally, the processing graph and configuration are passed to the Runner, which converts
    // the graph into a Heron topology that can be run in a Heron cluster.
    new Runner().run(topologyName, config, processingGraphBuilder);
  }
810362
function (source, opts, cb) {
        var callback,
            options;

        if (arguments.length === 2) {
            options = defaults();
            callback = opts;
        } else {
            options = defaults(opts);
            callback = cb;
        }

        try {
            source = api.clean(source);
            callback(null, api.insert(source, getToc(source, options)));
        } catch (err) {
            callback(err, null);
        }
    }
507817
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {

        KuduSession session = kuduClient.newSession();
        KuduTable table = null;
        try
        {
            table = kuduClient.openTable(entityMetadata.getTableName());
        }
        catch (Exception e)
        {
            logger.error("Cannot open table : " + entityMetadata.getTableName(), e);
            throw new KunderaException("Cannot open table : " + entityMetadata.getTableName(), e);
        }
        Operation operation = isUpdate ? table.newUpdate() : table.newInsert();
        PartialRow row = operation.getRow();
        populatePartialRow(row, entityMetadata, entity);
        try
        {
            session.apply(operation);
        }
        catch (Exception e)
        {
            logger.error("Cannot insert/update row in table : " + entityMetadata.getTableName(), e);
            throw new KunderaException("Cannot insert/update row in table : " + entityMetadata.getTableName(), e);
        }
        finally
        {
            try
            {
                session.close();
            }
            catch (Exception e)
            {
                logger.error("Cannot close session", e);
                throw new KunderaException("Cannot close session", e);
            }
        }
    }
343426
@Override
    public void handleDocType(
            final char[] buffer,
            final int keywordOffset, final int keywordLen, final int keywordLine, final int keywordCol,
            final int elementNameOffset, final int elementNameLen, final int elementNameLine, final int elementNameCol,
            final int typeOffset, final int typeLen, final int typeLine, final int typeCol,
            final int publicIdOffset, final int publicIdLen, final int publicIdLine, final int publicIdCol,
            final int systemIdOffset, final int systemIdLen, final int systemIdLine, final int systemIdCol,
            final int internalSubsetOffset, final int internalSubsetLen, final int internalSubsetLine, final int internalSubsetCol,
            final int outerOffset, final int outerLen, final int outerLine, final int outerCol)
            throws ParseException {

        if (!this.insideAllSelectorMatchingBlock) {

            this.someSelectorsMatch = false;
            for (int i = 0; i < this.selectorsLen; i++) {

                if (this.matchingMarkupLevelsPerSelector[i] > this.markupLevel) {
                    this.selectorMatches[i] =
                            this.selectorFilters[i].matchDocTypeClause(true, this.markupLevel, this.markupBlocks[this.markupLevel]);
                    if (this.selectorMatches[i]) {
                        this.someSelectorsMatch = true;
                    }
                } else {
                    this.selectorMatches[i] = true;
                    this.someSelectorsMatch = true;
                }

            }

            if (this.someSelectorsMatch) {
                markCurrentSelection();
                this.selectedHandler.handleDocType(
                        buffer,
                        keywordOffset, keywordLen, keywordLine, keywordCol,
                        elementNameOffset, elementNameLen, elementNameLine, elementNameCol,
                        typeOffset, typeLen, typeLine, typeCol,
                        publicIdOffset, publicIdLen, publicIdLine, publicIdCol,
                        systemIdOffset, systemIdLen, systemIdLine, systemIdCol,
                        internalSubsetOffset, internalSubsetLen, internalSubsetLine, internalSubsetCol,
                        outerOffset, outerLen, outerLine, outerCol);
                unmarkCurrentSelection();
                return;
            }

            unmarkCurrentSelection();
            this.nonSelectedHandler.handleDocType(
                    buffer,
                    keywordOffset, keywordLen, keywordLine, keywordCol,
                    elementNameOffset, elementNameLen, elementNameLine, elementNameCol,
                    typeOffset, typeLen, typeLine, typeCol,
                    publicIdOffset, publicIdLen, publicIdLine, publicIdCol,
                    systemIdOffset, systemIdLen, systemIdLine, systemIdCol,
                    internalSubsetOffset, internalSubsetLen, internalSubsetLine, internalSubsetCol,
                    outerOffset, outerLen, outerLine, outerCol);
            return;

        }

        markCurrentSelection();
        this.selectedHandler.handleDocType(
                buffer,
                keywordOffset, keywordLen, keywordLine, keywordCol,
                elementNameOffset, elementNameLen, elementNameLine, elementNameCol,
                typeOffset, typeLen, typeLine, typeCol,
                publicIdOffset, publicIdLen, publicIdLine, publicIdCol,
                systemIdOffset, systemIdLen, systemIdLine, systemIdCol,
                internalSubsetOffset, internalSubsetLen, internalSubsetLine, internalSubsetCol,
                outerOffset, outerLen, outerLine, outerCol);
        unmarkCurrentSelection();

    }
1276100
@Override
  protected void reserveInternal(int newCapacity) {
    if (isArray() || type instanceof MapType) {
      int[] newLengths = new int[newCapacity];
      int[] newOffsets = new int[newCapacity];
      if (this.arrayLengths != null) {
        System.arraycopy(this.arrayLengths, 0, newLengths, 0, capacity);
        System.arraycopy(this.arrayOffsets, 0, newOffsets, 0, capacity);
      }
      arrayLengths = newLengths;
      arrayOffsets = newOffsets;
    } else if (type instanceof BooleanType) {
      if (byteData == null || byteData.length < newCapacity) {
        byte[] newData = new byte[newCapacity];
        if (byteData != null) System.arraycopy(byteData, 0, newData, 0, capacity);
        byteData = newData;
      }
    } else if (type instanceof ByteType) {
      if (byteData == null || byteData.length < newCapacity) {
        byte[] newData = new byte[newCapacity];
        if (byteData != null) System.arraycopy(byteData, 0, newData, 0, capacity);
        byteData = newData;
      }
    } else if (type instanceof ShortType) {
      if (shortData == null || shortData.length < newCapacity) {
        short[] newData = new short[newCapacity];
        if (shortData != null) System.arraycopy(shortData, 0, newData, 0, capacity);
        shortData = newData;
      }
    } else if (type instanceof IntegerType || type instanceof DateType ||
      DecimalType.is32BitDecimalType(type)) {
      if (intData == null || intData.length < newCapacity) {
        int[] newData = new int[newCapacity];
        if (intData != null) System.arraycopy(intData, 0, newData, 0, capacity);
        intData = newData;
      }
    } else if (type instanceof LongType || type instanceof TimestampType ||
        DecimalType.is64BitDecimalType(type)) {
      if (longData == null || longData.length < newCapacity) {
        long[] newData = new long[newCapacity];
        if (longData != null) System.arraycopy(longData, 0, newData, 0, capacity);
        longData = newData;
      }
    } else if (type instanceof FloatType) {
      if (floatData == null || floatData.length < newCapacity) {
        float[] newData = new float[newCapacity];
        if (floatData != null) System.arraycopy(floatData, 0, newData, 0, capacity);
        floatData = newData;
      }
    } else if (type instanceof DoubleType) {
      if (doubleData == null || doubleData.length < newCapacity) {
        double[] newData = new double[newCapacity];
        if (doubleData != null) System.arraycopy(doubleData, 0, newData, 0, capacity);
        doubleData = newData;
      }
    } else if (childColumns != null) {
      // Nothing to store.
    } else {
      throw new RuntimeException("Unhandled " + type);
    }

    byte[] newNulls = new byte[newCapacity];
    if (nulls != null) System.arraycopy(nulls, 0, newNulls, 0, capacity);
    nulls = newNulls;

    capacity = newCapacity;
  }
676495
static int execute(String source, String target) {
    if (source.length() == 0) {
      return target.length() * INSERT_COST;
    }
    if (target.length() == 0) {
      return source.length() * DELETE_COST;
    }
    int[][] table = new int[source.length()][target.length()];
    Map<Character, Integer> sourceIndexByCharacter = new HashMap<>();
    if (source.charAt(0) != target.charAt(0)) {
      table[0][0] = Math.min(REPLACE_COST, DELETE_COST + INSERT_COST);
    }
    sourceIndexByCharacter.put(source.charAt(0), 0);
    for (int i = 1; i < source.length(); i++) {
      int deleteDistance = table[i - 1][0] + DELETE_COST;
      int insertDistance = (i + 1) * DELETE_COST + INSERT_COST;
      int matchDistance = i * DELETE_COST + (source.charAt(i) == target.charAt(0) ? 0 : REPLACE_COST);
      table[i][0] = Math.min(Math.min(deleteDistance, insertDistance), matchDistance);
    }
    for (int j = 1; j < target.length(); j++) {
      int deleteDistance = (j + 1) * INSERT_COST + DELETE_COST;
      int insertDistance = table[0][j - 1] + INSERT_COST;
      int matchDistance = j * INSERT_COST + (source.charAt(0) == target.charAt(j) ? 0 : REPLACE_COST);
      table[0][j] = Math.min(Math.min(deleteDistance, insertDistance), matchDistance);
    }
    for (int i = 1; i < source.length(); i++) {
      int maxSourceLetterMatchIndex = source.charAt(i) == target.charAt(0) ? 0 : -1;
      for (int j = 1; j < target.length(); j++) {
        Integer candidateSwapIndex = sourceIndexByCharacter.get(target.charAt(j));
        int indexJSwap = maxSourceLetterMatchIndex;
        int deleteDistance = table[i - 1][j] + DELETE_COST;
        int insertDistance = table[i][j - 1] + INSERT_COST;
        int matchDistance = table[i - 1][j - 1];
        if (source.charAt(i) != target.charAt(j)) {
          matchDistance += REPLACE_COST;
        } else {
          maxSourceLetterMatchIndex = j;
        }
        int swapDistance;
        if (candidateSwapIndex != null && indexJSwap != -1) {
          int indexISwap = candidateSwapIndex;
          int preSwapCost;
          if (indexISwap == 0 && indexJSwap == 0) {
            preSwapCost = 0;
          } else {
            preSwapCost = table[Math.max(0, indexISwap - 1)][Math.max(0, indexJSwap - 1)];
          }
          swapDistance = preSwapCost + (i - indexISwap - 1) * DELETE_COST + (j - indexJSwap - 1) * INSERT_COST
            + SWAP_COST;
        } else {
          swapDistance = Integer.MAX_VALUE;
        }
        table[i][j] = Math.min(Math.min(Math.min(deleteDistance, insertDistance), matchDistance), swapDistance);
      }
      sourceIndexByCharacter.put(source.charAt(i), i);
    }
    return table[source.length() - 1][target.length() - 1];
  }
1122932
@Override
    public void run() {
        switch (type) {
          case OPEN_FILE:
            try {
                debugGui.dim.compileScript(fileName, text);
            } catch (RuntimeException ex) {
                MessageDialogWrapper.showMessageDialog(
                    debugGui, ex.getMessage(), "Error Compiling "+fileName,
                    JOptionPane.ERROR_MESSAGE);
            }
            break;

          case LOAD_FILE:
            try {
                debugGui.dim.evalScript(fileName, text);
            } catch (RuntimeException ex) {
                MessageDialogWrapper.showMessageDialog(
                    debugGui, ex.getMessage(), "Run error for "+fileName,
                    JOptionPane.ERROR_MESSAGE);
            }
            break;

          case UPDATE_SOURCE_TEXT:
            {
                String fileName = sourceInfo.url();
                if (!debugGui.updateFileWindow(sourceInfo) &&
                        !fileName.equals("<stdin>")) {
                    debugGui.createFileWindow(sourceInfo, -1);
                }
            }
            break;

          case ENTER_INTERRUPT:
            debugGui.enterInterruptImpl(lastFrame, threadTitle, alertMessage);
            break;

          default:
            throw new IllegalArgumentException(String.valueOf(type));

        }
    }
93900
@Override
  public final void makeEntries(final Map<String, Object> pAddParam,
    final IDoc pEntity) throws Exception {
    Calendar calCurrYear = Calendar.getInstance(new Locale("en", "US"));
    calCurrYear.setTime(getSrvAccSettings().lazyGetAccSettings(pAddParam)
      .getCurrentAccYear());
    calCurrYear.set(Calendar.MONTH, 0);
    calCurrYear.set(Calendar.DAY_OF_MONTH, 1);
    calCurrYear.set(Calendar.HOUR_OF_DAY, 0);
    calCurrYear.set(Calendar.MINUTE, 0);
    calCurrYear.set(Calendar.SECOND, 0);
    calCurrYear.set(Calendar.MILLISECOND, 0);
    Calendar calDoc = Calendar.getInstance(new Locale("en", "US"));
    calDoc.setTime(pEntity.getItsDate());
    calDoc.set(Calendar.MONTH, 0);
    calDoc.set(Calendar.DAY_OF_MONTH, 1);
    calDoc.set(Calendar.HOUR_OF_DAY, 0);
    calDoc.set(Calendar.MINUTE, 0);
    calDoc.set(Calendar.SECOND, 0);
    calDoc.set(Calendar.MILLISECOND, 0);
    if (calCurrYear.getTime().getTime() != calDoc.getTime().getTime()) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "wrong_year");
    }
    StringBuffer sb = new StringBuffer();
    List<AccEntriesSourcesLine> sourcesLines = srvAccSettings
      .lazyGetAccSettings(pAddParam).getAccEntriesSources();
    java.util.Collections.sort(sourcesLines, this.cmprAccSourcesByType);
    int i = 0;
    for (AccEntriesSourcesLine sourcesLine : sourcesLines) {
      if (sourcesLine.getIsUsed()
        && sourcesLine.getSourceType().equals(pEntity.constTypeCode())) {
        String query = lazyGetQuery(sourcesLine.getFileName());
        String idName = "ITSID";
        if (pEntity.getIdBirth() != null) {
          idName = "IDBIRTH";
        }
        query = query.replace(":IDNAME", idName);
        //for foreign document this algorithm is also right:
        String strWhereDocId = sourcesLine.getSourceIdName() + " = "
          + pEntity.getItsId().toString();
        if (query.contains(":WHEREADD")) {
          query = query.replace(":WHEREADD", " and " + strWhereDocId);
        } else if (query.contains(":WHERE")) {
          query = query.replace(":WHERE", " where " + strWhereDocId);
        }
        if (i++ > 0) {
          sb.append("\nunion all\n\n");
        }
        sb.append(query);
      }
    }
    String langDef = (String) pAddParam.get("langDef");
    DateFormat dateFormat = DateFormat.getDateTimeInstance(
      DateFormat.MEDIUM, DateFormat.SHORT, new Locale(langDef));
    String query = sb.toString();
    if (query.trim().length() == 0) {
      throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
        "there_is_no_accounting_sources");
    }
    IRecordSet<RS> recordSet = null;
    try {
      recordSet = getSrvDatabase().retrieveRecords(query);
      if (recordSet.moveToFirst()) {
        Long itsDateLong = null;
        do {
          AccountingEntry accEntry = new AccountingEntry();
          accEntry.setIdDatabaseBirth(getSrvDatabase().getIdDatabase());
          if (itsDateLong == null) {
            itsDateLong = pEntity.getItsDate().getTime();
            getSrvBalance().handleNewAccountEntry(pAddParam, null, null,
              new Date(itsDateLong)); //This is for SrvBalanceStd only!!!
          }
          Date itsDate = new Date(itsDateLong++);
          accEntry.setItsDate(itsDate);
          accEntry.setSourceType(pEntity.constTypeCode());
          if (pEntity.getIdBirth() != null) { //accounting foreign document
            accEntry.setSourceId(pEntity.getIdBirth());
          } else {
            accEntry.setSourceId(pEntity.getItsId());
          }
          accEntry.setSourceDatabaseBirth(pEntity.getIdDatabaseBirth());
          String accDebitId = recordSet.getString("ACCDEBIT");
          Account accDebit = new Account();
          accDebit.setItsId(accDebitId);
          accEntry.setAccDebit(accDebit);
          accEntry.setSubaccDebitType(recordSet.getInteger("SUBACCDEBITTYPE"));
          accEntry.setSubaccDebitId(recordSet.getLong("SUBACCDEBITID"));
          accEntry.setSubaccDebit(recordSet.getString("SUBACCDEBIT"));
          accEntry.setDebit(BigDecimal.valueOf(recordSet.getDouble("DEBIT"))
            .setScale(getSrvAccSettings().lazyGetAccSettings(pAddParam)
              .getCostPrecision(), getSrvAccSettings()
                .lazyGetAccSettings(pAddParam).getRoundingMode()));
          String accCreditId = recordSet.getString("ACCCREDIT");
          Account accCredit = new Account();
          accCredit.setItsId(accCreditId);
          accEntry.setAccCredit(accCredit);
          accEntry
            .setSubaccCreditType(recordSet.getInteger("SUBACCCREDITTYPE"));
          accEntry.setSubaccCreditId(recordSet.getLong("SUBACCCREDITID"));
          accEntry.setSubaccCredit(recordSet.getString("SUBACCCREDIT"));
          accEntry.setCredit(BigDecimal
            .valueOf(recordSet.getDouble("CREDIT")).setScale(
              getSrvAccSettings().lazyGetAccSettings(pAddParam)
                .getCostPrecision(), getSrvAccSettings()
                  .lazyGetAccSettings(pAddParam).getRoundingMode()));
          String docId = pEntity.getItsId().toString();
          if (pEntity.getIdBirth() != null) {
            docId = pEntity.getIdBirth().toString();
          }
          String descr = "";
          if (pEntity.getDescription() != null) {
            descr = " " + pEntity.getDescription();
          }
          accEntry.setDescription(getSrvI18n().getMsg(pEntity.getClass().
      getSimpleName() + "short", langDef) + " #" + pEntity.getIdDatabaseBirth()
    + "-" + docId + ", " + dateFormat.format(pEntity.getItsDate()) + descr);
          this.srvOrm.insertEntity(pAddParam, accEntry);
          accEntry.setIsNew(false);
        } while (recordSet.moveToNext());
      }
    } finally {
      if (recordSet != null) {
        recordSet.close();
      }
    }
    pEntity.setHasMadeAccEntries(true);
    srvOrm.updateEntity(pAddParam, pEntity);
  }
540186
protected void onSuperColumn(EntityMetadata m, boolean isRelation, List<String> relations, List<Object> entities,
        List<SuperColumn> superColumns, ByteBuffer key) {
        Object e = null;
        Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key.array());

        ThriftRow tr = new ThriftRow(id, m.getTableName(), new ArrayList<Column>(0), superColumns,
            new ArrayList<CounterColumn>(0), new ArrayList<CounterSuperColumn>(0));

        e = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isRelation);
        if (log.isInfoEnabled()) {
            log.info("Populating data for super column family of clazz {} and row key {}.", m.getEntityClazz(),
                tr.getId());
        }

        if (e != null) {
            entities.add(e);
        }
    }
357945
private int colRefSegments(TypedElementDefinition<?> column) {
        if (column != null && column.getContainer() instanceof UDTDefinition)
            return 2;

        if (!getStrategy().getInstanceFields())
            return 2;

        return 3;
    }