Helper function that cycles through db results and setups the BAT_HOUR itemized array
@param $db_events
@param $itemized
@param $unit
@param $keyed_units

@return array
977382
private function itemizeHours($db_events, $itemized, $unit, $keyed_units) {

    $result = array();

    if (isset($itemized[Event::BAT_HOUR])) {
      foreach ($itemized[Event::BAT_HOUR] as $year => $months) {
        foreach ($months as $month => $days) {
          foreach ($days as $day => $hours) {
            foreach ($hours as $hour => $value) {
              if (isset($db_events[$unit][Event::BAT_HOUR][$year][$month][$day][$hour])) {
                $result[$year][$month][$day][$hour] = ((int) $db_events[$unit][Event::BAT_HOUR][$year][$month][$day][$hour] == 0 ? $keyed_units[$unit]->getDefaultValue() : (int) $db_events[$unit][Event::BAT_HOUR][$year][$month][$day][$hour]);
              }
              else {
                // If nothing from db - then revert to the defaults
                $result[$year][$month][$day][$hour] = (int) $keyed_units[$unit]->getDefaultValue();
              }
            }
          }
        }
      }
    }

    // Now fill in hour data coming from the database which the mock event did *not* cater for in the data structure
    if (isset($db_events[$unit][Event::BAT_HOUR])) {
      foreach ($db_events[$unit][Event::BAT_HOUR] as $year => $months) {
        foreach ($months as $month => $days) {
          foreach ($days as $day => $hours) {
            foreach ($hours as $hour => $value) {
              $result[$year][$month][$day][$hour] = ((int) $value == 0 ? $keyed_units[$unit]->getDefaultValue() : (int) $value);
            }
            ksort($result[$year][$month][$day], SORT_NATURAL);
          }
        }
      }
    }

    return $result;
  }
1244866
private List<InvoiceItem> processRecurringEvent(final UUID invoiceId, final UUID accountId, final BillingEvent thisEvent, @Nullable final BillingEvent nextEvent,
                                                    final LocalDate targetDate, final Currency currency,
                                                    final InvoiceItemGeneratorLogger invoiceItemGeneratorLogger, final BillingMode billingMode,
                                                    final Map<UUID, SubscriptionFutureNotificationDates> perSubscriptionFutureNotificationDate,
                                                    final InternalCallContext internalCallContext) throws InvoiceApiException {

        try {
            final List<InvoiceItem> items = new ArrayList<InvoiceItem>();

            // For FIXEDTERM phases we need to stop when the specified duration has been reached
            final LocalDate maxEndDate = thisEvent.getPlanPhase().getPhaseType() == PhaseType.FIXEDTERM ?
                                         thisEvent.getPlanPhase().getDuration().addToLocalDate(internalCallContext.toLocalDate(thisEvent.getEffectiveDate())) :
                                         null;

            // Handle recurring items
            final BillingPeriod billingPeriod = thisEvent.getBillingPeriod();
            if (billingPeriod != BillingPeriod.NO_BILLING_PERIOD) {
                final LocalDate startDate = internalCallContext.toLocalDate(thisEvent.getEffectiveDate());

                if (!startDate.isAfter(targetDate)) {
                    final LocalDate endDate = (nextEvent == null) ? null : internalCallContext.toLocalDate(nextEvent.getEffectiveDate());

                    final int billCycleDayLocal = thisEvent.getBillCycleDayLocal();

                    final RecurringInvoiceItemDataWithNextBillingCycleDate itemDataWithNextBillingCycleDate;
                    try {
                        itemDataWithNextBillingCycleDate = generateInvoiceItemData(startDate, endDate, targetDate, billCycleDayLocal, billingPeriod, billingMode);
                    } catch (final InvalidDateSequenceException e) {
                        throw new InvoiceApiException(ErrorCode.INVOICE_INVALID_DATE_SEQUENCE, startDate, endDate, targetDate);
                    }
                    for (final RecurringInvoiceItemData itemDatum : itemDataWithNextBillingCycleDate.getItemData()) {

                        // Stop if there a maxEndDate and we have reached it
                        if (maxEndDate != null && maxEndDate.compareTo(itemDatum.getEndDate()) < 0) {
                            break;
                        }

                        final BigDecimal rate = thisEvent.getRecurringPrice(internalCallContext.toUTCDateTime(itemDatum.getStartDate()));
                        if (rate != null) {
                            final BigDecimal amount = KillBillMoney.of(itemDatum.getNumberOfCycles().multiply(rate), currency);
                            final RecurringInvoiceItem recurringItem = new RecurringInvoiceItem(invoiceId,
                                                                                                accountId,
                                                                                                thisEvent.getBundleId(),
                                                                                                thisEvent.getSubscriptionId(),
                                                                                                thisEvent.getPlan().getProduct().getName(),
                                                                                                thisEvent.getPlan().getName(),
                                                                                                thisEvent.getPlanPhase().getName(),
                                                                                                itemDatum.getStartDate(),
                                                                                                itemDatum.getEndDate(),
                                                                                                amount, rate, currency);
                            items.add(recurringItem);
                        }
                    }
                    updatePerSubscriptionNextNotificationDate(thisEvent.getSubscriptionId(), itemDataWithNextBillingCycleDate.getNextBillingCycleDate(), items, billingMode,
                                                              perSubscriptionFutureNotificationDate);
                }
            }

            // For debugging purposes
            invoiceItemGeneratorLogger.append(thisEvent, items);

            return items;
        } catch (final CatalogApiException e) {
            throw new InvoiceApiException(e);
        }
    }
237832
function mapXSetItems (items) {
  let results = [];
  for (let i = 0; i < items.length; i += 1) {
    results.push({
      timestamp: items[i][0],
      field: items[i][1][0],
      value: items[i][1][1]
    });
  }
  return results;
}
630358
public function convertSubitems($columnToTake, $keepId = false,
                                    $keepCode = false, $keepAccountig = false)
    {
        $subitemRules = $this->rules[$columnToTake];
        if (self::isAssoc($this->input->data[$columnToTake])) {
            $sourceData = [$this->input->data[$columnToTake]];
        } else {
            $sourceData = $this->input->getDataValue($columnToTake);
        }

        $typUcOp = $this->input->getDataValue('typUcOp');

        foreach ($sourceData as $subItemData) {
            foreach (array_keys($subItemData) as $subitemColumn) {
                if (!array_key_exists($subitemColumn, $subitemRules)) {
                    unset($subItemData[$subitemColumn]);
                }
            }

            if ($keepAccountig && array_key_exists('ucetni', $subItemData) && array_key_exists('ucetni',
                    $this->output->getData())) {
                $subItemData['ucetni'] = $this->output->getDataValue('ucetni');
            } else {
                unset($subItemData['ucetni']);
            }

            if ($typUcOp) {
                $subItemData['typUcOp'] = $typUcOp;
            } else {
                unset($subItemData['typUcOp']);
            }

            if ($keepCode === false) {
                unset($subItemData['kod']);
            }
            if ($keepId === false) {
                unset($subItemData['id']);
                unset($subItemData['external-ids']);
            }
            $this->output->addArrayToBranch($subItemData);
        }
    }
441496
public void processResources(List<Row> rows)
   {
      for (Row row : rows)
      {
         Resource resource = m_project.addResource();
         processFields(m_resourceFields, row, resource);
         resource.setResourceCalendar(getResourceCalendar(row.getInteger("clndr_id")));

         // Even though we're not filling in a rate, filling in a time unit can still be useful
         // so that we know what rate time unit was originally used in Primavera.
         TimeUnit timeUnit = TIME_UNIT_MAP.get(row.getString("cost_qty_type"));
         resource.setStandardRateUnits(timeUnit);
         resource.setOvertimeRateUnits(timeUnit);

         // Add User Defined Fields
         populateUserDefinedFieldValues("RSRC", FieldTypeClass.RESOURCE, resource, resource.getUniqueID());

         m_eventManager.fireResourceReadEvent(resource);
      }
   }
1310933
public function createEvent(
        $event,
        $entityType,
        $entityId,
        $targetEntityType=null,
        $targetEntityId=null,
        array $properties=null,
        $eventTime=null
    ) {
        if (!isset($eventTime)) {
            $eventTime = new \DateTime();
        } elseif (!($eventTime instanceof \DateTime)) {
            $eventTime = new \DateTime($eventTime);
        }
        $eventTime = $eventTime->format(\DateTime::ISO8601);

        $data = [
            'event' => $event,
            'entityType' => $entityType,
            'entityId' => $entityId,
            'eventTime' => $eventTime,
        ];

        if (isset($targetEntityType)) {
            $data['targetEntityType'] = $targetEntityType;
        }

        if (isset($targetEntityId)) {
            $data['targetEntityId'] = $targetEntityId;
        }

        if (isset($properties)) {
            $data['properties'] = $properties;
        }

        $json = $this->jsonEncode($data);

        $this->export($json);
    }
247537
public function group($columns)
	{
		if (!($this->db instanceof DatabaseDriver))
		{
			throw new \RuntimeException('JLIB_DATABASE_ERROR_INVALID_DB_OBJECT');
		}

		// Transform $columns into an array for filtering purposes
		\is_string($columns) && $columns = explode(',', str_replace(' ', '', $columns));

		// Get the _formatted_ FROM string and remove everything except `table AS alias`
		$fromStr = str_replace(array('[', ']'), '', str_replace('#__', $this->db->getPrefix(), str_replace('FROM ', '', (string) $this->from)));

		// Start setting up an array of alias => table
		list($table, $alias) = preg_split("/\sAS\s/i", $fromStr);

		$tmpCols = $this->db->getTableColumns(trim($table));
		$cols    = array();

		foreach ($tmpCols as $name => $type)
		{
			$cols[] = $alias . '.' . $name;
		}

		// Now we need to get all tables from any joins
		// Go through all joins and add them to the tables array
		foreach ($this->join as $join)
		{
			$joinTbl = str_replace(
				'#__',
				$this->db->getPrefix(),
				str_replace(
					']',
					'',
					preg_replace("/.*(#.+\sAS\s[^\s]*).*/i", '$1', (string) $join)
				)
			);

			list($table, $alias) = preg_split("/\sAS\s/i", $joinTbl);

			$tmpCols = $this->db->getTableColumns(trim($table));

			foreach ($tmpCols as $name => $tmpColType)
			{
				$cols[] = $alias . '.' . $name;
			}
		}

		$selectStr = str_replace('SELECT ', '', (string) $this->select);

		// Remove any functions (e.g. COUNT(), SUM(), CONCAT())
		$selectCols = preg_replace("/([^,]*\([^\)]*\)[^,]*,?)/", '', $selectStr);

		// Remove any "as alias" statements
		$selectCols = preg_replace("/(\sas\s[^,]*)/i", '', $selectCols);

		// Remove any extra commas
		$selectCols = preg_replace('/,{2,}/', ',', $selectCols);

		// Remove any trailing commas and all whitespaces
		$selectCols = trim(str_replace(' ', '', preg_replace('/,?$/', '', $selectCols)));

		// Get an array to compare against
		$selectCols = explode(',', $selectCols);

		// Find all alias.* and fill with proper table column names
		foreach ($selectCols as $key => $aliasColName)
		{
			if (preg_match("/.+\*/", $aliasColName, $match))
			{
				// Grab the table alias minus the .*
				$aliasStar = preg_replace("/(.+)\.\*/", '$1', $aliasColName);

				// Unset the array key
				unset($selectCols[$key]);

				// Get the table name
				$tableColumns = preg_grep("/{$aliasStar}\.+/", $cols);
				$columns      = array_merge($columns, $tableColumns);
			}
		}

		// Finally, get a unique string of all column names that need to be included in the group statement
		$columns = array_unique(array_merge($columns, $selectCols));
		$columns = implode(',', $columns);

		// Recreate it every time, to ensure we have checked _all_ select statements
		$this->group = new QueryElement('GROUP BY', $columns);

		return $this;
	}
788405
def _batch_write_item(self, items):
        
        kwargs = {
            'RequestItems': {
                self.tablename: items,
            },
            'ReturnConsumedCapacity': self.return_capacity,
            'ReturnItemCollectionMetrics': self.return_item_collection_metrics,
        }
        return self.connection.call('batch_write_item', **kwargs)
429879
public function mapDatabase(array $databaseMapping, $itemClass, array $hitPositions)
	{
		$this->databaseMapping = $databaseMapping;
		$this->loadFinalType($hitPositions);
		$this->loadResultSetMappingAndScorePosition($itemClass, $hitPositions);
		$this->finalTypes[$this->scorePos] = Type::INTEGER;
	}
646862
public static function column(array $array, $column_key)
    {
        $retarr = [];
        foreach ($array as $arr) {
            if (is_array($column_key)) {
                $ret = [];
                foreach ($column_key as $key) {
                    $ret[] = isset($arr[$key]) ? $arr[$key] : null;
                }
                $retarr[] = $ret;
            } else {
                $retarr[] = $arr[$column_key];
            }
        }
        return $retarr;
    }
316689
static function active( $asObject = true, $offset, $limit, $sortField = "created", $sortOrder = "asc", $show = eZOrder::SHOW_NORMAL )
    {
        if ( $sortField == "user_name" )
        {
            $db = eZDB::instance();

            $db_params = array();
            $db_params["offset"] =(int) $offset;
            $db_params["limit"] =(int) $limit;
            $sortOrder = $db->escapeString( $sortOrder );

            $query = "SELECT ezorder.*
                      FROM
                            ezorder,
                            ezcontentobject
                      WHERE
                            ".eZOrder::getShowOrdersQuery( $show, "ezorder" )." AND
                            ezorder.is_temporary = '0' AND
                            ezcontentobject.id = ezorder.user_id
                      ORDER BY ezcontentobject.name $sortOrder";
            $orderArray = $db->arrayQuery( $query, $db_params );
            if ( $asObject )
            {
                $retOrders = array();
                foreach ( $orderArray as $order )
                {
                    $order = new eZOrder( $order );
                    $retOrders[] = $order;
                }
                return $retOrders;
            }
            else
            {
                return $orderArray;
            }
        }
        else
        {
            $where['is_temporary'] = 0;
            if ( $show != eZOrder::SHOW_ALL )
            {
                $where['is_archived'] = $show;
            }

            return eZPersistentObject::fetchObjectList( eZOrder::definition(),
                                                        null,
                                                        $where ,
                                                        array( $sortField => $sortOrder ),
                                                        array( 'offset' => $offset,
                                                               'length' => $limit ), $asObject );
        }
    }
793057
public function dbInsert($table, $item, $key = 'id')
    {
        Eresus_CMS::getLegacyKernel()->db->insert($this->__table($table), $item);
        $result = $this->dbItem($table, Eresus_CMS::getLegacyKernel()->db->getInsertedId(), $key);

        return $result;
    }
37120
public static function getlastDays($nb = 5, League $league = null, $include_archived = false) {
    $day_storage = \Drupal::entityTypeManager()->getStorage('day');
    $injected_database = Database::getConnection();
    $now = new \DateTime(null, new \DateTimeZone("UTC"));

    $query = $injected_database->select('mespronos__game', 'g');
    $query->addExpression('min(game_date)', 'day_date');
    $query->addExpression('count(g.id)', 'nb_game_over');
    $query->groupBy('day');
    $query->fields('g', array('day'));
    $query->join('mespronos__day', 'd', 'd.id = g.day');
    if ($league) {
      $query->condition('d.league', $league->id());
    }
    else {
      $query->join('mespronos__league', 'l', 'l.id = d.league');
      if (!$include_archived) {
        $query->condition('l.status', 'active');
      }
    }
    $query->condition('game_date', $now->format('Y-m-d\TH:i:s'), '<');
    $query->orderBy('day_date', 'DESC');
    $query->range(0, $nb);
    $results = $query->execute();
    $results = $results->fetchAllAssoc('day');
    $days = $day_storage->loadMultiple(array_keys($results));

    foreach ($results as $key => &$day_data) {
      $day_data->nb_game = $days[$key]->getNbGame();
      $day_data->nb_game_with_score = $days[$key]->getNbGameWIthScore();
      $day_data->entity = $days[$key];
    }
    return $results;
  }
1171061
protected function populateFromResultset(Resultset $resultset = null, $classname = null, $id_column = null, $index_column = null)
        {
            $items = array();
            if ($resultset instanceof Resultset) {
                if (Core::isDebugMode()) {
                    $previous_time = Core::getDebugTime();
                    $populated_classnames = array();
                    $populated_classes = 0;
                }

                $query = $resultset->getQuery();
                $id_column = ($id_column) ?? $query->getTable()->getIdColumn();
                if ($index_column === null) {
                    $index_column = ($query->getIndexBy()) ? $query->getIndexBy() : $id_column;
                }
                $classnames = Core::getCachedTableEntityClasses('\\'.get_class($this));
                if ($classname === null) {
                    $classname = Core::getCachedTableEntityClass('\\'.get_class($this));
                }
                while ($row = $resultset->getNextRow()) {
                    if ($classnames) {
                        $classname = $this->getSubclassNameFromRow($row, $classnames);
                    }
                    $row_id = $row->get($id_column);
                    $is_cached = $classname::getB2DBTable()->hasCachedB2DBObject($row_id);
                    $item = $this->populateFromRow($row, $classname, $id_column, $row_id, true);
                    $items[$row->get($index_column)] = $item;
                    if (!$is_cached && Core::isDebugMode()) {
                        $populated_classnames[$classname] = $classname;
                        $populated_classes++;
                    }
                }

                if (Core::isDebugMode()) {
                    Core::objectPopulationHit($populated_classes, $populated_classnames, $previous_time);
                }
            }
            return $items;
        }
464094
public function pluck(string $column, string $keyBy = ''): array
    {
        $pdoStatement = $this->provideStatement();
        $pdoStatement = $this->execute($pdoStatement);
        $rows = $pdoStatement->fetchAll(\PDO::FETCH_ASSOC);
        if (empty($rows)) {
            return [];
        }
        if (!isset($rows[0][$column])) {
            throw new DatabaseException('Column not found in result.');
        }
        if (!empty($keyBy) && !isset($rows[0][$keyBy])) {
            throw new DatabaseException('Column to use as key not found in result.');
        }
        $indexKey = (!empty($keyBy)) ? $keyBy : null;
        return array_column($rows, $column, $indexKey);
    }
1095000
private function _get_cache($item, $mode = 'columns', $force = false): ?array
  {
    $cache_name = $this->_db_cache_name($item, $mode);
    if ( $force && isset($this->cache[$cache_name]) ){
      unset($this->cache[$cache_name]);
    }
    if ( !isset($this->cache[$cache_name]) ){
      if ( $force || !($tmp = $this->cache_get($cache_name)) ){
        switch ( $mode ){
          case 'columns':
            $keys = $this->language->get_keys($item);
            $cols = $this->language->get_columns($item);
            if ( \is_array($keys) && \is_array($cols) ){
              $tmp = [
                'keys' => $keys['keys'],
                'cols' => $keys['cols'],
                'fields' => $cols
              ];
            }
            break;
          case 'tables':
            $tmp = $this->language->get_tables($item);
            break;
          case 'databases':
            $tmp = $this->language->get_databases();
            break;
        }
        if ( !\is_array($tmp) ){
          die("Error while creating the cache for the table $item in mode $mode");
        }
        if ( $tmp ){
          $this->cache_set($cache_name, '', $tmp, $this->cache_renewal);
        }
      }
      if ( $tmp ){
        $this->cache[$cache_name] = $tmp;
      }
    }
    return $this->cache[$cache_name] ?? null;
  }
1049806
public function storeEvent(EventInterface $event, $granularity = Event::BAT_HOURLY) {
    $stored = TRUE;
    $transaction = db_transaction();

    try {
      // Itemize an event so we can save it
      $itemized = $event->itemize(new EventItemizer($event, $granularity));

      //Write days
      foreach ($itemized[Event::BAT_DAY] as $year => $months) {
        foreach ($months as $month => $days) {
          db_merge($this->day_table_no_prefix)
            ->key(array(
              'unit_id' => $event->getUnitId(),
              'year' => $year,
              'month' => $month
            ))
            ->fields($days)
            ->execute();
        }
      }

      if (($granularity == Event::BAT_HOURLY) && isset($itemized[Event::BAT_HOUR])) {
        // Write Hours
        foreach ($itemized[Event::BAT_HOUR] as $year => $months) {
          foreach ($months as $month => $days) {
            foreach ($days as $day => $hours) {
              // Count required as we may receive empty hours for granular events that start and end on midnight
              if (count($hours) > 0) {
                db_merge($this->hour_table_no_prefix)
                  ->key(array(
                    'unit_id' => $event->getUnitId(),
                    'year' => $year,
                    'month' => $month,
                    'day' => substr($day, 1)
                  ))
                  ->fields($hours)
                  ->execute();
              }
            }
          }
        }

        // If we have minutes write minutes
        foreach ($itemized[Event::BAT_MINUTE] as $year => $months) {
          foreach ($months as $month => $days) {
            foreach ($days as $day => $hours) {
              foreach ($hours as $hour => $minutes) {
                db_merge($this->minute_table_no_prefix)
                  ->key(array(
                    'unit_id' => $event->getUnitId(),
                    'year' => $year,
                    'month' => $month,
                    'day' => substr($day, 1),
                    'hour' => substr($hour, 1)
                  ))
                  ->fields($minutes)
                  ->execute();
              }
            }
          }
        }
      }
    } catch (\Exception $e) {
      $stored = FALSE;
      $transaction->rollback();
      watchdog_exception('BAT Event Save Exception', $e);
    }

    return $stored;
  }