Snippets Collections
<?php

namespace Drupal\maintenance_2020_01\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'Maintenance Documents' formatter.
 *
 * @FieldFormatter(
 *   id = "maintenance_documents",
 *   label = @Translation("Maintenance Documents"),
 *   field_types = {
 *     "file"
 *   }
 * )
 */
class MaintenanceDocumentsFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
      $description = $item->getValue()['description'];
      $file = $item->entity;
      $created_timestamp = $file->get('created')->value;
      $element[$delta] = [
        '#theme' => 'file_link',
        '#file' => $file,
        '#description' => $description . ' (' . \Drupal::service('date.formatter')->format($created_timestamp, 'custom', 'Y.m.d') . ')',
        '#cache' => [
          'tags' => $file->getCacheTags(),
        ],
      ];
    }

    return $element;
  }

}
SELECT
    TABLE_NAME,
    COLUMN_NAME,
    CONSTRAINT_NAME,
    REFERENCED_TABLE_NAME,
    REFERENCED_COLUMN_NAME
FROM
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
    REFERENCED_TABLE_NAME = 'table_name';
$host = '127.0.0.1';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
function pos_core_update_9014($sandbox) {
  $user_ids_to_delete = [32, 30, 29, 28, 27, 24, 22, 20, 16, 15, 14, 13];

  // Delete all cfps where the users are going to be deleted.
  \Drupal::database()->delete('cfp')
    ->condition('user_id', $user_ids_to_delete, 'IN')
    ->execute();

  // Delete all applicants associated to the user that is going to be deleted.
  foreach ($user_ids_to_delete as $user_id_to_delete) {
    $user = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->load($user_id_to_delete);

    if ($applicant_id = $user->get('applicant')->target_id) {
      \Drupal::database()
        ->delete('applicant')
        ->condition('id', $applicant_id)
        ->execute();
    }
    // Delete users.
    $user->delete();
  }
}
// Ovo ide ispod prethodnog filtera (koji ću verovatno i obrisati).
$data['views']['applicant_cfp'] = [
    'title' => t('Did the applicant start cfp - NEW Custom filter'),
    'filter' => [
      'title' => t('Did the applicant start cfp - NEW Custom filter'),
      'field' => 'id',
      'id' => 'applicant_cfp'
    ],
  ];
<?php

namespace Drupal\pos_entity_applicant\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\filter\FilterPluginBase;
use Symfony\Contracts\Translation\TranslatorTrait;

/**
 * Class ProgramCoordinatorFilter
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("applicant_cfp")
 */
class ApplicantCfpFilter extends FilterPluginBase {

  use TranslatorTrait;

  /**
   * {@inheritDoc}
   */
  public function acceptExposedInput($input) {
    return TRUE;
  }

  public function buildExposedForm(&$form, FormStateInterface $form_state) {
    if (empty($this->options['exposed'])) {
      return;
    }
    $identifier = $this->options['expose']['identifier'];
    $exposed_input = $this->view->getExposedInput();

    $form[$identifier] = [
      '#type' => 'select',
      '#title' => $this->t('Da li aplikant ima konkurs?'),
      '#options' => [
        NULL => $this->t('- Any -'),
        'yes' => $this->t('Da'),
        'no' => $this->t('Ne'),
      ],
      '#default_value' => $exposed_input,
      '#validated' => TRUE,
    ];
    return $form;
  }

  public function query() {
    $this->ensureMyTable();
    /** @var \Drupal\views\Plugin\views\query\Sql $query */
    $query = $this->query;
    $input = $this->view->getExposedInput();

    if (isset($input['applicant_cfp']) && !empty($input['applicant_cfp'])) {
      $input['applicant_cfp'] === 'yes' ?
        $query->addWhereExpression(0,"users_field_data.uid IN (SELECT DISTINCT user_id FROM users_field_data JOIN cfp ON cfp.user_id)")
      : $query->addWhereExpression(0,"users_field_data.uid NOT IN (SELECT DISTINCT user_id FROM users_field_data JOIN cfp ON cfp.user_id)");
    }
  }
}
<?php

//The example selects and prints a specific row.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$id = 12;

//This time we use named placeholder (:id) and bindParam.
$stm = $pdo->prepare("SELECT * FROM countries WHERE id = :id");
$stm->bindParam(":id", $id, PDO::PARAM_INT);
$stm->execute();

$row = $stm->fetch(PDO::FETCH_ASSOC);

echo "Id: " . $row['id'] . PHP_EOL;
echo "Name: " . $row['name'] . PHP_EOL;
echo "Population: " . $row['population'] . PHP_EOL;

?>
<?php

//In the example, we use bindValue to create a parameterized query. We use question mark placeholder.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "root";
$passwd = "andrea";

$pdo = new PDO($dsn, $user, $passwd);


$id = 12;

//Say this input comes from a user.
$stm = $pdo->prepare("SELECT * FROM countries WHERE id = ?");
$stm->bindValue(1, $id);
$stm->execute();

//The select statement fetches a specific row from the table. We bind the value with bindValue to a question mark placeholder.
$row = $stm->fetch(PDO::FETCH_ASSOC);

echo "Id: " . $row['id'] . PHP_EOL;
echo "Name: " . $row['name'] . PHP_EOL;
echo "Population: " . $row['population'] . PHP_EOL;

?>
<?php

//In this example, we fetch data as an associative array.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$stm = $pdo->query("SELECT * FROM countries");

//In the fetchAll method, we use the PDO::FETCH_ASSOC style.
$rows = $stm->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $row) {

    printf("{$row['id']} {$row['name']} {$row['population']}\n");
}

?>
<?php

//In this code example, we get data in an indexed array.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

//We select all data from the countries table.
$stm = $pdo->query("SELECT * FROM countries");

//We pass the PDO:FETCH_NUM style to the fetchAll method.
$rows = $stm->fetchAll(PDO::FETCH_NUM);

//We go over the $rows array and print the fields. The fields are accessed via array indexes.
foreach($rows as $row) {
    printf("$row[0] $row[1] $row[2]\n");
}

?>
<?php
//The code example deletes three rows. It prints the number of affected rows.


$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$id = 12;

//In this SQL statement, we delete rows with ids 1, 2, and 3. The number of deleted rows is stored in the $nrows variable.
$nrows = $pdo->exec("DELETE FROM countries WHERE id IN (1, 2, 3)");

//We print the number of deleted rows.
echo "The statement affected $nrows rows\n";

?>
<?php

//These variables are used to create a connection string to the database. The dsn is the Data Source Name, which contains the information required to connect to the database.
$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

//A new PDO object is created. We pass the constructor the data source name and the user name and password. The PDO class represents a connection between PHP and a database server.
$pdo = new PDO($dsn, $user, $passwd);

//The query method executes an SQL statement in a single function call. It returns the result set.
$stm = $pdo->query("SELECT VERSION()");

//The PDO statement's fetch method fetches the next row from a result set. In our case it is a version of MySQL.
$version = $stm->fetch();

//The $version is an array; we get its first value.
echo $version[0] . PHP_EOL;

?>
# connection name == any name we can give 
#ex: connection name = Mysql_connection
#connection_method = standard(tcp/ip)
#host name  = localhost , port = 3306
#username = root (for local then only it work)
#password = root (for local server we much give the root as password )
#test connection
[root@mysql-in-servicecloud-consolidated-slave-1 ~]# cat /usr/local/scripts/check_slave_status.py
import commands
import os
import time

for x in range(0, 4):
        status = commands.getoutput("mysql --login-path=statuser -sN -e \"show slave status\"")
#        SLACK_URL="https://hooks.slack.com/services/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"
        SLACK_URL="https://hooks.slack.com/services/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"       

        for row in status.split("\n"):
                SERVER_NAME = "mysql-in-servicecloud-consolidated-slave-01"
                SLACK_MESSAGE = "<!channel> Problem in \`[Azure] "+SERVER_NAME+" \`: "
                Slave_IO_Running = row.split("\t")[10]
                Slave_SQL_Running = row.split("\t")[11]
                Seconds_Behind_Master = row.split("\t")[32]
                if Slave_IO_Running.find("No")!=-1 or Slave_SQL_Running.find("No")!=-1 or int(Seconds_Behind_Master)>5:
                        SLACK_MESSAGE = SLACK_MESSAGE + "\`Slave_SQL_Running: "+Slave_SQL_Running+"\`; \`Slave_IO_Running: "+Slave_IO_Running+"\`; \`Seconds_Behind_Master: "+Seconds_Behind_Master+"\`"
                        os.system("curl -X POST --data \"payload={\'text\':\'"+SLACK_MESSAGE+"\', \'username\':\'gcp-watchman\', \'icon_emoji\':\':bangbang:\'}\" "+SLACK_URL)
                os.system("curl -i -XPOST 'http://gcp-in-int-grafana.onedirect.in:8086/write?db=collectd' --data-binary 'mysql_slave_lag,slave_name='"+SERVER_NAME+"' value='"+Seconds_Behind_Master+"''")
                time.sleep(10);#!/usr/bin/python
mydate=`date +"%m/%d/%Y -%H:%M:%S"`
current_time=$(date "+%Y.%m.%d-%H.%M.%S")
mytime=`date +%T`

USER=anirban
PW=Bose9711
filename="/var/lib/mysql-files/VFS_Ticket_data.csv"


rm -rf "/var/lib/mysql-files/VFS_Ticket_data.csv"
reportname="/tmp/VFS_Ticket_data_$current_time.csv"
mysql -u$USER -p$PW -e"call onedirect.get_export_to_excel_summary(8112,current_timestamp - interval 2 hour,current_timestamp)">/var/lib/mysql-files/VFS_Ticket_data.csv


mv /var/lib/mysql-files/VFS_Ticket_data.csv $reportname
echo " ****TRANSFER START**** "
echo $reportname
azcopy cp "$reportname" "https://prjdwuatadls.dfs.core.windows.net/vfsbiproject?sp=rwle&st=2022-08-05T05:47:28Z&se=2022-09-05T13:47:28Z&spr=https&sv=2021-06-08&sr=c&sig=GuyhDRcueFwQUdtL7%2FQ%2Bq5IdRFnd3QKpud1dusF%2Bu0E%3D"

echo " ****TRANSFER END**** "
mydate=`date +"%m/%d/%Y -%H:%M:%S"`
current_time=$(date "+%Y.%m.%d-%H.%M.%S")
mytime=`date +%T`

USER=anirban
PW=Bose9711
filename="/var/lib/mysql-files/VFS_Ticket_data.csv"


rm -rf "/var/lib/mysql-files/VFS_Ticket_data.csv"
reportname="/tmp/VFS_Ticket_data_$current_time.csv"
mysql -u$USER -p$PW -e"call onedirect.get_export_to_excel_summary(8112,current_timestamp - interval 2 hour,current_timestamp)">/var/lib/mysql-files/VFS_Ticket_data.csv


mv /var/lib/mysql-files/VFS_Ticket_data.csv $reportname
echo " ****TRANSFER START**** "
echo $reportname
azcopy cp "$reportname" "https://prjdwuatadls.dfs.core.windows.net/vfsbiproject?sp=rwle&st=2022-08-05T05:47:28Z&se=2022-09-05T13:47:28Z&spr=https&sv=2021-06-08&sr=c&sig=GuyhDRcueFwQUdtL7%2FQ%2Bq5IdRFnd3QKpud1dusF%2Bu0E%3D"

echo " ****TRANSFER END**** "
services:
  hederavita_core.event_subscriber:
    class: Drupal\hederavita_core\EventSubscriber\OderPlacedSubscriber
    arguments: ['@messenger', '@marketing_tools.google_event_storage', '@path.current']
    tags:
      - { name: event_subscriber }
<?php

namespace Drupal\hederavita_core\EventSubscriber;

use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Path\CurrentPathStack;
use Drupal\marketing_tools\GoogleEventStorage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Hederavita Core event subscriber.
 */
class OderPlacedSubscriber implements EventSubscriberInterface {

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The marketing tool.
   *
   * @var \Drupal\marketing_tools\GoogleEventStorage
   */
  protected $marketing_tool;

  /**
   * The current path.
   *
   * @var \Drupal\Core\Path\CurrentPathStack
   */
  protected $current_path;

  /**
   * Constructs event subscriber.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   * @param \Drupal\marketing_tools\GoogleEventStorage $marketing_tool
   *   The marketing tool.
   * @param \Drupal\Core\Path\CurrentPathStack $current_path
   */
  public function __construct(MessengerInterface $messenger, GoogleEventStorage $marketing_tool, CurrentPathStack $current_path) {
    $this->messenger = $messenger;
    $this->marketing_tool = $marketing_tool;
    $this->current_path = $current_path;
  }

  /**
   * Kernel request event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   Response event.
   */
  public function onKernelRequest(GetResponseEvent $event) {
    $this->messenger->addStatus(__FUNCTION__);
  }

  /**
   * Kernel response event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
   *   Response event.
   */
  public function onKernelResponse(FilterResponseEvent $event) {
    $this->messenger->addStatus(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [
      'commerce_order.place.pre_transition' => ['addEvent', 50],
    ];
    return $events;
  }

  /**
   * Create google event
   *
   * @return void
   */
  public function addEvent() {
    $path = $this->current_path->getPath();
    $path_parts = explode('/', $path);
    foreach ($path_parts as $path_part) {
      if (is_numeric($path_part)) {
        $order = \Drupal::entityTypeManager()
          ->getStorage('commerce_order')
          ->load($path_part);
      }
    }

    /** @var \Drupal\commerce_order\Entity\Order $order */
    $value = $order->getTotalPrice()->getNumber();
    $order_id = $order->id();

    $this->marketing_tool->addEvent([
      'event'  => 'conversion',
      'sendTo' => 'GTM-PZQ4TQZ',
      'value' => $value,
      'currency' => 'RSD',
      'transaction_id' => $order_id,
    ]);
  }

}
SELECT Id_card, COUNT(Id_card)
FROM user_application_tbl
GROUP BY Id_card
HAVING COUNT(Id_card) > 1
name: Baross core
type: module
description: Baross Core module
package: Custom
core: 8.x
core_version_requirement: ^8 || ^9
<?php

/**
 * Implements hook_install().
 */
function baross_core_install() {
  if (!\Drupal::moduleHandler()->moduleExists('path_alias')) {
    \Drupal::database()->delete('key_value')
      ->condition('name', 'path_alias')
      ->execute();
  }
}

/**
 * Implements hook_update_N().
 */
function baross_core_update_8002(&$sandbox) {
  \Drupal::database()->schema()->dropTable('menu_link_content_revision');
}
<?php

/**
 * @file
 * Contains belmil_product_rating.module.
 */

use Drupal\block\Entity\Block;
use Drupal\commerce_product\Entity\ProductInterface;
use Drupal\commerce_product\Entity\ProductType;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Routing\RouteMatchInterface;
use \Drupal\user\EntityOwnerInterface;
/**
 * Implements hook_help().
 */
function belmil_product_rating_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the belmil_product_rating module.
    case 'help.page.belmil_product_rating':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('This module provides custom rating functionalities for products.') . '</p>';
      return $output;

    default:
  }

  return '';
}

/**
 * Implements hook_theme().
 */
function belmil_product_rating_theme() {
  return [
    'belmil_product_rating' => [
      'render element' => 'children',
    ],
    'belmil_product_rating_statistics_widget' => [
      'render element' => 'children',
    ]
  ];
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function belmil_product_rating_comment_insert(EntityInterface $entity) {
  $userRoles = \Drupal::currentUser()->getRoles();
  if ($entity instanceof EntityOwnerInterface) {
      $ownerEmail = $entity->getOwner()->getEmail();
    if (!in_array('administrator', $userRoles) && $ownerEmail != 'trustami@studiopresent.com') {
      $link = '/comment/' . $entity->id() . '/edit';
      $body = t('There is new comment on your site') . '<br> <a target="_blank" href="' . $link . '">' . t('Show') . ' </a>';

      // Send mail.
      /** @var \Drupal\Core\Mail\MailManagerInterface $mailManager */
      $mailManager = \Drupal::service('plugin.manager.mail');

      $module = $key = 'belmil_product_rating';
      // Get email from config and remove whitespaces.
      $to = \Drupal::config('system.site')->get('mail');
      $params['subject'] = t('New comment on website');
      $params['body'] = $body;
      $params['format'] = 'text/html';
      $langcode = \Drupal::currentUser()->getPreferredLangcode();

      $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, TRUE);

      // Log result.
      if ($result['result'] != TRUE) {
        $message = t('There was a problem sending your email notification to @email.', ['@email' => $to]);
        \Drupal::logger('mail')->error($message);
      }
      else {
        $message = t('An email notification for new comment has been sent to @email.', ['@email' => $to]);
        \Drupal::logger('mail')->notice($message);
      }
    }
  }
}

/**
 * Implements hook_mail().
 */
function belmil_product_rating_mail($key, &$message, $params) {
  switch ($key) {
    case 'belmil_product_rating':
      $message['subject'] = $params['subject'];
      $message['body'][] = Markup::create($params['body']);
      $message['headers']['Content-Type'] = $params['format'];
      break;
  }
}

/**
 * Implements hook_form_alter().
 */
function belmil_product_rating_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Open details for admin comment approval.
  if ($form_id == "comment_product_comment_form") {
    $form['#validate'][] = 'belmil_product_rating_settings_validate';
    if (isset($form['author'])) {
      $form['author']['#open'] = TRUE;
    }
  }
}

/**
 * Implements hook_form_submit().
 */
function belmil_product_rating_settings_validate(&$form, FormStateInterface $form_state) {
  $uid = \Drupal::currentUser()->id();
  if (empty($form_state->getValue('uid'))) {
    $form['author']['uid']['#value'] = $uid;
    $form['author']['name']['#value'] = 'Anonymous';
  }
}

/**
 * Implements hook_entity_extra_field_info().
 */
function belmil_product_rating_entity_extra_field_info() {
  $stars_field = [];

  foreach (ProductType::loadMultiple() as $bundle) {
    $stars_field['commerce_product'][$bundle->id()]['display']['trustamiproductreview'] = [
      'label' => t('Trustami product review'),
      'description' => t('A pseudo field to display the Trustami product review block'),
      'weight' => 0,
      'visible' => TRUE,
    ];

    // Define stars field for displaying rating by stars and link to comment section.
    $stars_field['commerce_product'][$bundle->id()]['display']['stars_field'] = [
      'label' => t('Product stars'),
      'description' => t('This is pseudo field for showing stars rating'),
      'visible' => FALSE,
    ];

    // Define statistic widget for rating.
    $stars_field['commerce_product'][$bundle->id()]['display']['stars_widget'] = [
      'label' => t('Stars widget'),
      'description' => t('Stars widget with statistic by marks'),
      'visible' => FALSE,
    ];
  }

  return $stars_field;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 *
 * Add stars field & widget to product view.
 */
function belmil_product_rating_commerce_product_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($display->getComponent('trustamiproductreview')) {
    $block = Block::load('trustamiproductreview');
    if ($block) {
      $build['trustamiproductreview'] = $block->getPlugin()->build();
    }
  }

  if ($display->getComponent('stars_field') ||
    $display->getComponent('stars_widget')
  ) {
    /** @var \Drupal\belmil_product_rating\BelmilProductRatingManager $product_rating_manager */
    $product_rating_manager = \Drupal::service('belmil_product_rating.belmil_product_rating_manager');

    $productRating = 0;
    $numOfComments = 0;
    $productsWithSameTagWithComments = [];
    $ratings = [];

    // Get product with same tag which contain comments for default product type.
    if ($entity->bundle() === "default") {
      $tagId = (int) $entity->get('field_tag')->target_id;
      $productsWithSameTagWithComments = $product_rating_manager
        ->getProductsWithSameTagWithComments($tagId);
    }
    // Get comments of single product for universal product type.
    elseif ($entity->bundle() === "universal") {
      $productsWithSameTagWithComments = [$entity->id()];
    }

    // Call get rating function.
    $product_rating_manager->getRating($productsWithSameTagWithComments, $productRating, $numOfComments, $ratings);
    // Prepare stars data - num of stars is fixed to 5.
    $starsData = $product_rating_manager->prepareStarsData(5, $productRating);
  }

  // Render product stars.
  if ($display->getComponent('stars_field')) {
    $build['stars_field'] = [
      '#markup' => \Drupal::theme()->render('belmil_product_rating', [
        'rating' => $productRating,
        'stars' => 5,
        'vote_type' => "fivestar-widget-static-vote",
        'num_of_comments' => $numOfComments,
        'widget' => ['name' => 'fivestar-basic'],
        'stars_data' => $starsData,
        'product_id' => $entity->id(),
      ]),
    ];
  }

  // Render stars statistics widget.
  if ($display->getComponent('stars_widget')) {
    // Render only if there is any comment.
    if (!empty($ratings)) {
      $totalRating = ($productRating / 20 );
      $statistics = $product_rating_manager->getStatisticsRatingData($ratings);
      // Get percentage of each mark.
      foreach ($statistics as $key => $rating) {
        $statistics[$key] = $rating / count($ratings) * 100;
      }

      $build['stars_widget'] = [
        '#markup' => \Drupal::theme()->render('belmil_product_rating_statistics_widget', [
          'ratings' => $statistics,
          'total_rating' => $totalRating,
          'rating' => $productRating,
          'stars' => 5,
          'vote_type' => "fivestar-widget-static-vote",
          'num_of_comments' => $numOfComments,
          'widget' => ['name' => 'fivestar-basic'],
          'stars_data' => $starsData,
          'product_id' => $entity->id(),
        ]),
      ];
    }
  }
}

/**
 * Implements hook_page_attachments().
 */
function belmil_product_rating_page_attachments(array &$page) {
  // Get request and entity.
  $request = \Drupal::request();
  $path = $request->attributes->get('_route_object')->getPath();
  /** @var \Drupal\commerce_product\Entity\ProductInterface $entity */
  $entity = $request->attributes->get('_entity');

  // Check if we are on product view page.
  if (!empty($entity) && $path == "/product/{commerce_product}") {
    // Attach google schema style script.
    /** @var \Drupal\belmil_product_rating\BelmilProductRatingManager $product_rating_manager */
    $product_rating_manager = \Drupal::service('belmil_product_rating.belmil_product_rating_manager');

    $product_rating_manager->attachGoogleSchemaStyleScript($entity, $page);

    // Attach Trustami Comment Widget.
    $referrerMeta = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'referrer',
        'content' => 'strict-origin-when-cross-origin',
      ],
    ];
    $page['#attached']['html_head'][] = [$referrerMeta, 'referrerMeta'];
    // attachTrustamiCommentsWidgetScript($entity, $page);
  }
}

/**
 * Trustami product widget script.
 *
 * @param \Drupal\commerce_product\Entity\ProductInterface $entity
 *   The product entity.
 * @param array $page
 *   The page array.
 */
function attachTrustamiCommentsWidgetScript(ProductInterface $entity, array &$page) {
  $variations = $entity->getVariations();
  $variation = reset($variations);

  if ($variation) {
    $trustamiProductWidgetScript = [
      '#tag' => 'script',
      '#attributes' => [
        'type' => 'text/javascript',
        'id' => 'trustami-product-widget',
        'src' => 'https://cdn.trustami.com/widgetapi/productWidget/trustami-product-widget.js',
        'data-uid' => '601e2fffcc96c5152b8b46de',
        'data-gtin' => $variation->getSku(),
        'data-asin' => $variation->get('field_asin')->value,
        'data-modes' => "[4]",
      ],
      '#value' => '',
    ];

    // Add script to head.
    $page['#attached']['html_head'][] = [
      $trustamiProductWidgetScript,
      'trustamiProductWidgetScript'
    ];
  }
}
<?php

declare(strict_types = 1);

namespace Drupal\enmon_core\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * @SearchApiProcessor(
 *   id = "only_special_offer",
 *   label = @Translation("Only special offer"),
 *   description = @Translation("Calculates whether the only special offer is true on all variation"),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 * )
 */
class OnlySpecialOffer extends ProcessorPluginBase {

  /**
   * {@inheritdoc}
   */
  public static function supportsIndex(IndexInterface $index) {
    $supported_entity_types = ['commerce_product'];
    foreach ($index->getDatasources() as $datasource) {
      if (in_array($datasource->getEntityTypeId(), $supported_entity_types)) {
        return TRUE;
      }
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = [];

    if (!$datasource) {
      $definition = [
        'label' => $this->t('Only special offers'),
        'description' => $this->t('Whether the product all variation marked with only special offer'),
        'type' => 'boolean',
        'is_list' => TRUE,
        'processor_id' => $this->getPluginId(),
      ];
      $properties['only_special_offers'] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $fields = $item->getFields();

    $only_special_offer_fields = $this->getFieldsHelper()
      ->filterForPropertyPath($fields, NULL, 'only_special_offers');

    /** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entity_adapter */
    $entity_adapter = $item->getOriginalObject();

    /** @var \Drupal\commerce_product\Entity\Product $product */
    $product = $entity_adapter->getEntity();

    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $product_variation */
    foreach ($product->getVariations() as $product_variation) {
      $is_only_special_offer = $product_variation->get('field_only_special_offer')->value;

      foreach ($only_special_offer_fields as $only_special_offer_field) {
        $only_special_offer_field->addValue($is_only_special_offer);
      }
    }
  }

}
/**
 * Implements hook_views_pre_view().
 */
function enmon_core_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() === 'special_offers') {
    $format_values = \Drupal::entityTypeManager()
      ->getStorage('commerce_product_attribute_value')
      ->getQuery()
      ->condition('attribute', 'master_format')
      ->execute();
    $color_values = \Drupal::entityTypeManager()
      ->getStorage('commerce_product_attribute_value')
      ->getQuery()
      ->condition('attribute', 'master_color')
      ->execute();
    $filters = $view->display_handler->getOption('filters');
    if (array_key_exists('attribute_master_format_target_id_1', $filters)) {
      foreach ($format_values as $format_key => $format_value) {
        $filters['attribute_master_format_target_id_1']['value'][$format_key] = $format_value;
      }
    }
    if (array_key_exists('attribute_master_color_target_id_1', $filters)) {
      foreach ($color_values as $color_key => $color_value) {
        $filters['attribute_master_color_target_id_1']['value'][$color_key] = $color_value;
      }
    }
    $view->display_handler->overrideOption('filters', $filters);
  }
}
TRUNCATE cache_config;
TRUNCATE cache_container;
TRUNCATE cache_data;
TRUNCATE cache_default;
TRUNCATE cache_discovery;
TRUNCATE cache_dynamic_page_cache;
TRUNCATE cache_entity;
TRUNCATE cache_menu;
TRUNCATE cache_render;
TRUNCATE cache_toolbar;
select w2.id,w2.value, w.name from workflowstepfieldexecution w2
         inner join workflowstepfield w on w2.workflowstepfield_id = w.id
         where w.name like '%%' AND
        workflowstepexecution_id in
        (select id from workflowstepexecution where workflowdefinitionexecution_id in  (select id from workflowdefinitionexecution
         where workflowexecution_id = (select id from workflowexecution where ordernumber like '%002619%' limit 1)));
select registrationnum,idcpicregistration from professionaldata where id =
(select  professionaldata_id from account where id =
(select senderaccount_id from workflowexecution where ordernumber like '%010598%' limit 1));
select w2.id,w2.value from workflowstepfieldexecution w2
         inner join workflowstepfield w on w2.workflowstepfield_id = w.id
         where w.name like '%MATRICULA%' AND
        workflowstepexecution_id in
        (select id from workflowstepexecution where workflowdefinitionexecution_id in  (select id from workflowdefinitionexecution
         where workflowexecution_id = (select id from workflowexecution where ordernumber like '%010598%' limit 1)));
CREATE DATABASE databasename;
CREATE DATABASE databasename;
(function (Drupal) {

  const handleExpand = (element) => {
    const expandElement = element.target.parentElement.querySelector('.to-expand');
    if (expandElement.style.display === "inline") {
      expandElement.style.display = "none";
      element.target.innerHTML = Drupal.t('Read more');
    } else {
      expandElement.style.display = "inline";
      element.target.innerHTML = Drupal.t('Collapse');
    }
  };

  document.querySelectorAll('.expand-link').forEach((element) => {
    element.addEventListener('click', handleExpand);
  });
}) (Drupal);
read_more:
  version: 1.x
  js:
    js/read_more.js: {}
  dependencies:
    - core/drupal
<?php

namespace Drupal\halo_widget_altering\Element;

use Drupal\Core\Render\Element\RenderElement;

/**
 * Provides a render element to display read more text.
 *
 * Properties:
 * - #text: Text to be printed.
 * - #limit_chars: Number of characters to limit.
 *
 * Usage Example:
 * @code
 * $build['read_more'] = [
 *   '#type' => 'correction_value_viewer',
 *   '#entity' => EntityInterface,
 * ];
 * @endcode
 * @RenderElement("read_more")
 */
class ReadMore extends RenderElement {

  /**
   * {@inheritDoc}
   */
  public function getInfo() {
    return [
      '#pre_render' => [
        [get_class($this), 'printText'],
      ],
      '#text' => NULL,
      '#limit_chars' => 250,
    ];
  }



  /**
   * @return
   */
  public static function printText(array $element) {
    $text = $element['#text'];
    $limit_characters = $element['#limit_chars'];

    if (empty($text)) {
      return [];
    }

    if (strlen($text) <= $limit_characters) {
      return [
        'text' => [
          '#type' => 'inline_template',
          '#template' => '{{ value|nl2br }}',
          '#context' => ['value' => $text],
        ],
      ];
    }
    $first_half_text = substr($text, 0, $limit_characters);
    $second_half_text = substr($text, $limit_characters);

    $element['text'] = [
      'text' => [
        '#type' => 'inline_template',
        '#template' => '{{ value1|nl2br }}<span class="to-expand" style="display: none">{{ value2|nl2br }}</span><a class="expand-link">{{ read_more_text }}</a>',
        '#context' => [
          'value1' => $first_half_text,
          'value2' => $second_half_text,
          'read_more_text' => t('Read more'),
        ],
      ],
    ];
    $element['#attached']['library'][] = 'halo_widget_altering/read_more';
    return $element;
  }

}
      $entity_row[] = [
        '#type' => 'read_more',
        '#text' => $entity->get('description')->value,
//        '#limit_chars' => 10,
      ];
    }
<?php
/**
* Implements hook_token_info().
*/
function mycustomtokenmodule_token_info() {
   $type = [
       'name' => t('Custom Token'),
       'description' => t('Tokens for custom things.'),
   ];
   $node['title'] = [
       'name' => t("Node Title"),
       'description' => t('The node\'s title'),
   ];
   $node['dateformat'] = [
       'name' => t("Custom Date Format"),
       'dynamic' => TRUE,
       'description' => t('Show a custom format for the current date'),
   ];
   return [
       'types' => ['customtoken' => $type],
       'tokens' => ['customtoken' => $node],
   ];
}
/**
* Implements hook_tokens().
*/
function mycustomtokenmodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
   $replacements = [];
   
   if ($type == 'customtoken' && !empty($data['node'])) {
       foreach ($tokens as $name => $original) {
           switch ($name) {
               case 'title':
                   $replacements[$original] = $data['node']->getTitle();
               break;
           }
       }
       if ($dateTokens = \Drupal::token()->findWithPrefix($tokens, 'dateformat')) {
           // var_dump($dateTokens)
           // retult: array(1) { ["Y-m-d"]=> string(30) "[customtoken:dateformat:Y-m-d]" }
           foreach ($dateTokens as $format => $original) {
               $replacements[$original] = date($format);
           }
       }
   }
   return $replacements;
}
function change_maintenance_date() {
  //Change the date so the Report date is 2024. 07. 15.
  $cfp = \Drupal::entityTypeManager()->getStorage('cfp')->load(190);
  $cfp->set('maintenance_period', '2021-07-15')->save(); // Ovaj datum je 
}
SELECT entity_id, COUNT(variations_target_id)
FROM `commerce_product__variations`
GROUP BY entity_id
HAVING COUNT(variations_target_id) > 1;
SELECT gender, day, sum(score_points) over (partition by gender order by day) as total FROM Scores 
ORDER BY gender, day
/* AQUI CREARE LA TABLA */
CREATE DATABASE fejesus;

CREATE TABLE leccion (
    id_leccion INT NOT NULL AUTO_INCREMENT, 
    titulo VARCHAR(30),
    instructor VARCHAR(50),
    no_leccion INT,

    PRIMARY KEY(id_leccion),
    INDEX(no_leccion)
    
) ENGINE=INNODB;

DESCRIBE leccion;

CREATE TABLE preguntas (
    id_pregunta INT NOT NULL AUTO_INCREMENT,
    pregunta VARCHAR(200),
    verso VARCHAR(40),
    id_leccion INT NOT NULL,
    id_seccion INT NOT NULL,

    PRIMARY KEY (id_pregunta),
    INDEX(id_leccion),
    INDEX(id_seccion),

    FOREIGN KEY (id_leccion)
        REFERENCES leccion(id_leccion)
        ON UPDATE CASCADE ON DELETE RESTRICT
    
) ENGINE=INNODB;

DESCRIBE preguntas;

CREATE TABLE seccion ( 
    id_seccion INT NOT NULL AUTO_INCREMENT, 
    leccion_id INT NOT NULL, 
    titulo VARCHAR(100), 

    PRIMARY KEY(id_seccion), 
    INDEX (leccion_id), 
        
    FOREIGN KEY (leccion_id) 
        REFERENCES leccion(id_leccion) ON UPDATE CASCADE ON DELETE RESTRICT

) ENGINE=INNODB;

DESCRIBE seccion;
select id from workflowexecution where subject like '%FOZG-069338%';

update workflowexecution set state = 4, cancellationDate=CURRENT_TIMESTAMP where id = 34470;

update workflowdefinitionexecution set state = 4 , cancellationDate=CURRENT_TIMESTAMP where workflowexecution_id = (select id from workflowexecution where id = 34470);

update workflowstepexecution set state = 4 where workflowdefinitionexecution_id in (select id from workflowdefinitionexecution where workflowexecution_id = (select id from workflowexecution where id = 34470));
$data = array(
  	'nazov' => $name,
  	'poznamka' => $poznamka,
  	'user_id' => $user_id,            
  	'date_modify' => date('Y-m-d H:i:s')
);

$this->db->where('ponuka_id',$ponuka_id);
$this->db->update('tsv_ponuky_h',$data);
$select = "SELECT * FROM tsv_sablonah WHERE sablona_id = '".(int)$sablona."'";
        
if($this->db->query($select)->num_rows() > 0 ){
  	return $this->db->query($select)->row();
} else {
  	return '';
}
$data = array(
  'nazov' => $name,
  'poznamka' => $poznamka,
  'user_id' => $user_id,
  'date_added' => date('Y-m-d H:i:s')
);
$this->db->insert('tsv_ponuky_h',$data);

$new_id = $this->db->insert_id();
CREATE TABLE drivers (
 emp_id INT PRIMARY KEY,
  first_name VARCHAR(40),
  last_name VARCHAR(40),
  Age INT,
  sex VARCHAR(1),
  Salary  INT,
  boss_id INT,
  team_id INT
);


CREATE TABLE employee (
  emp_id INT PRIMARY KEY,
  first_name VARCHAR(40),
  last_name VARCHAR(40),
  birth_day DATE,
  sex VARCHAR(1),
  salary INT,
  super_id INT,
  branch_id INT
);

CREATE TABLE team (
  team_id INT PRIMARY KEY,
  team_name VARCHAR(40),
  boss_id INT,
  boss_name VARCHAR(20),
  FOREIGN KEY(boss_id) REFERENCES drivers(driver_id) ON DELETE SET NULL
);


CREATE TABLE team (
  team_id INT PRIMARY KEY,
  team_name VARCHAR(40),
  boss_id INT,
  boss_name VARCHAR(20),
  FOREIGN KEY(boss_id) REFERENCES drivers(driver_id) ON DELETE SET NULL
);








ALTER TABLE drivers33
ADD FOREIGN KEY(team_id)
REFERENCES team(team_id)
ON DELETE SET NULL;

ALTER TABLE drivers33
ADD FOREIGN KEY(boss_id)
REFERENCES drivers(emp_id)
ON DELETE SET NULL;














CREATE TABLE client (
  client_id INT PRIMARY KEY,
  client_name VARCHAR(40),
  branch_id INT,
  FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ON DELETE SET NULL
);

CREATE TABLE works_with (
  emp_id INT,
  client_id INT,
  total_sales INT,
  PRIMARY KEY(emp_id, client_id),
  FOREIGN KEY(emp_id) REFERENCES employee(emp_id) ON DELETE CASCADE,
  FOREIGN KEY(client_id) REFERENCES client(client_id) ON DELETE CASCADE
);

CREATE TABLE branch_supplier (
  branch_id INT,
  supplier_name VARCHAR(40),
  supply_type VARCHAR(40),
  PRIMARY KEY(branch_id, supplier_name),
  FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ON DELETE CASCADE
);


-- -----------------------------------------------------------------------------

-- Corporate
INSERT INTO employee VALUES(100, 'David', 'Wallace', '1967-11-17', 'M', 250000, NULL, NULL);

INSERT INTO branch VALUES(1, 'Corporate', 100, '2006-02-09');

UPDATE employee
SET branch_id = 1
WHERE emp_id = 100;

INSERT INTO employee VALUES(101, 'Jan', 'Levinson', '1961-05-11', 'F', 110000, 100, 1);

-- Scranton
INSERT INTO employee VALUES(102, 'Michael', 'Scott', '1964-03-15', 'M', 75000, 100, NULL);

INSERT INTO branch VALUES(2, 'Scranton', 102, '1992-04-06');

UPDATE employee
SET branch_id = 2
WHERE emp_id = 102;

INSERT INTO employee VALUES(103, 'Angela', 'Martin', '1971-06-25', 'F', 63000, 102, 2);
INSERT INTO employee VALUES(104, 'Kelly', 'Kapoor', '1980-02-05', 'F', 55000, 102, 2);
INSERT INTO employee VALUES(105, 'Stanley', 'Hudson', '1958-02-19', 'M', 69000, 102, 2);

-- Stamford
INSERT INTO employee VALUES(106, 'Josh', 'Porter', '1969-09-05', 'M', 78000, 100, NULL);

INSERT INTO branch VALUES(3, 'Stamford', 106, '1998-02-13');

UPDATE employee
SET branch_id = 3
WHERE emp_id = 106;

INSERT INTO employee VALUES(107, 'Andy', 'Bernard', '1973-07-22', 'M', 65000, 106, 3);
INSERT INTO employee VALUES(108, 'Jim', 'Halpert', '1978-10-01', 'M', 71000, 106, 3);


-- BRANCH SUPPLIER
INSERT INTO branch_supplier VALUES(2, 'Hammer Mill', 'Paper');
INSERT INTO branch_supplier VALUES(2, 'Uni-ball', 'Writing Utensils');
INSERT INTO branch_supplier VALUES(3, 'Patriot Paper', 'Paper');
INSERT INTO branch_supplier VALUES(2, 'J.T. Forms & Labels', 'Custom Forms');
INSERT INTO branch_supplier VALUES(3, 'Uni-ball', 'Writing Utensils');
INSERT INTO branch_supplier VALUES(3, 'Hammer Mill', 'Paper');
INSERT INTO branch_supplier VALUES(3, 'Stamford Lables', 'Custom Forms');

-- CLIENT
INSERT INTO client VALUES(400, 'Dunmore Highschool', 2);
INSERT INTO client VALUES(401, 'Lackawana Country', 2);
INSERT INTO client VALUES(402, 'FedEx', 3);
INSERT INTO client VALUES(403, 'John Daly Law, LLC', 3);
INSERT INTO client VALUES(404, 'Scranton Whitepages', 2);
INSERT INTO client VALUES(405, 'Times Newspaper', 3);
INSERT INTO client VALUES(406, 'FedEx', 2);

-- WORKS_WITH
INSERT INTO works_with VALUES(105, 400, 55000);
INSERT INTO works_with VALUES(102, 401, 267000);
INSERT INTO works_with VALUES(108, 402, 22500);
INSERT INTO works_with VALUES(107, 403, 5000);
INSERT INTO works_with VALUES(108, 403, 12000);
INSERT INTO works_with VALUES(105, 404, 33000);
INSERT INTO works_with VALUES(107, 405, 26000);
INSERT INTO works_with VALUES(102, 406, 15000);
INSERT INTO works_with VALUES(105, 406, 130000);
SELECT table_name ,
  round(((data_length + index_length) / 1024 / 1024), 2) as SIZE_MB
FROM information_schema.TABLES
WHERE table_schema = DATABASE() ORDER BY SIZE_MB DESC;
UPDATE wp_options SET option_value = replace(option_value, 'http://www.oldurl', 'http://www.newurl') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://www.oldurl','http://www.newurl');

UPDATE wp_posts SET post_content = replace(post_content, 'http://www.oldurl', 'http://www.newurl');

UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.oldurl','http://www.newurl');
mysqldump -u root -p -h host_name_or_ip -P port_number --databases db_name --tables tbl_1 tbl_2 > db_name.sql
CREATE DATABASE mydatabase CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
UPDATE wp_options SET option_value = replace(option_value, 'oldurl.com', 'newurl.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'oldurl.com','newurl.com');
UPDATE wp_posts SET post_content = replace(post_content, 'oldurl.com', 'newurl.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'oldurl.com','newurl.com');
    mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    mysql> exit;
    if year < 2020 and not (year == 2019 and quarter == 4):
        query_churn = "SELECT sum(eur) FROM salesforce_summaries WHERE (\"Type of Business\" = 'Churn' AND \"Import from Weekly KPI Excel\" = 'True') AND time >= '{quarter_start}' AND time <= '{quarter_end}'".format(
            quarter_start=quarter_start, quarter_end=quarter_end)
CREATE DEFINER=`rdsadmin`@`localhost` PROCEDURE `rds_set_configuration`(IN name VARCHAR(30), IN value INT)
    READS SQL DATA
    DETERMINISTIC
BEGIN
   DECLARE sql_logging BOOLEAN;

   IF name = 'binlog retention hours' AND value NOT BETWEEN 1 AND 168 THEN
       SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'For binlog retention hours the value must be between 1 and 168 inclusive or be NULL';
   END IF;

   SELECT @@sql_log_bin INTO sql_logging;
   SET @@sql_log_bin = OFF;   
   UPDATE mysql.rds_configuration
   SET mysql.rds_configuration.value = value
   WHERE BINARY mysql.rds_configuration.name = BINARY name;
   SET @@sql_log_bin = sql_logging;
END
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
</dependency>
mysqldump --opt --no-tablespaces --compress -u <username> -p [-h <hostname>] -r <file> <database>


# mysqldump [--no-tablespaces] --default-character-set=utf8 -e -u $USER -p $DBNAME > /path/to/file.sql
SELECT 
  GROUP_CONCAT(lv SEPARATOR ',')
  #lv
FROM 
  (
    SELECT 
      @pv :=(
        SELECT 
          GROUP_CONCAT(cid SEPARATOR ',') 
        FROM 
          categories 
        WHERE 
          FIND_IN_SET(parent, @pv)
      ) AS lv 
    FROM 
      categories 
      JOIN (
        SELECT 
          @pv := 5
      ) tmp
  ) tmp2
// Custom query that will return the ancestors of a given id, it will
        // return a hierarchical data of parents and children in one query
        // For detailed explanation of the query, please see link below
        // https://explainextended.com/2009/07/20/hierarchical-data-in-mysql-parents-and-children-in-one-query/
        $sql = "
            SELECT t2.id, t2.sender_id, t2.invitee_id, t2.deal_admin_id, t2.agent_structure_id, t3.level, t3.sub_level, t3.position_type
            FROM (
                SELECT
                    @r AS _invitee_id,
                    (SELECT @r := sender_id FROM " . $agentInvitationTable . " WHERE invitee_id = _invitee_id AND status = :status LIMIT 1) AS sender_id,
                    @l := @l + 1 AS lvl
                FROM (SELECT @r := :userId, @l := 0) vars, " . $agentInvitationTable . " t
                WHERE @r <> 0
            ) t1
            JOIN " . $agentInvitationTable . " t2 ON t1._invitee_id = t2.invitee_id
            LEFT JOIN  " . $agentStructureTable . " t3 ON t2.agent_structure_id = t3.id
            WHERE t2.status = :status
            ORDER BY t1.lvl DESC;
        ";
sudo docker build . -t vitesse
from ai_jobs.models import CandidateJobJourney
from ai_api.services import Utils
job_jns = CandidateJobJourney.objects.filter(company_id=1038, journey_id=8747)
#job_jns = CandidateJobJourney.objects.filter(company_id=4318, journey_id=11941)
for jj in job_jns:

    jj_stage_settings = Utils.safe_jsonloads(jj.stage_settings)
    for k, v in jj_stage_settings.items():
        if v.get("interviewers"):
            v.update(interviewers='["r_5"]')
            jj_stage_settings[k] = v
    jj.stage_settings = Utils.safe_json_dumps(jj_stage_settings)
    jj.save()
from ai_jobs.models import Job
from ai_jobs.services import HiringTeamService
from ai_jobs.services.job_management import JobManagementService
from ai_jobs.constants.constants import JobRoleType
for job in jobs:
    try:
        hiring_manage_job_perms = HiringTeamService.get_hiring_manage_job_perms(job)
        hiring_manage_user_job_perms = hiring_manage_job_perms.get(JobRoleType.USER_ID, {})
        hiring_manage_user_job_perms.update({uid: True for uid in user_ids})
        hiring_manage_job_perms.update({JobRoleType.USER_ID: hiring_manage_user_job_perms})
        JobManagementService.update_hiring_team(
            job, users=hiring_manage_user_job_perms.keys(), hiring_manage_job_perms=hiring_manage_job_perms
        )

                             
for job in company_jobs:
    hiring_manage_job_perms = HiringTeamService.get_hiring_manage_job_perms(job)
    hiring_manage_role_job_perms = hiring_manage_job_perms.get(JobRoleType.ROLE_ID, {})
    hiring_manage_role_job_perms.update({uid: True for uid in user_ids})
    hiring_manage_job_perms.update({JobRoleType.ROLE_ID: hiring_manage_role_job_perms})
    JobManagementService.update_hiring_team(
        job, roles=hiring_manage_role_job_perms.keys(), hiring_manage_job_perms=hiring_manage_job_perms
    )
UPDATE `qm_aktuelle_liste` SET params = JSON_INSERT(params, '$.ohneMangel', 'x') WHERE id <300
CREATE TABLE test ( 
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(100) NOT NULL,
  PRIMARY KEY (id)
);
# If your logged in to mysql (mysql -u root -p) you can create the database
#CREATE DATABASE database_name;
CREATE DATABASE <database> CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_unicode_ci';

# The user can be created with
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'user_password';

# This user also needs access to the database
GRANT ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';

# To make the new access rights available you have to reload them
FLUSH PRIVILEGES;

# In file /etc/my.cnf or /etc/mysql/my.cnf (depending on your operating system), change
# "sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES" or add following

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION

# This should take care of the problem. Another way  to change sql_mode directly would be

mysql -u root -p -e „SET GLOBAL sql_mode = ‚NO_ENGINE_SUBSTITUTION‘;“

# But the later option only seems to set the mode temporarely, so I would advise going
# for the my.cnf file.
# /etc/my.cnf
# Raise max size to 4GB
SET GLOBAL tmp_table_size = 1024 * 1024 * 1024 * 4;
SET GLOBAL max_heap_table_size = 1024 * 1024 * 1024 * 4;
# If you are checking the above variables with
SELECT @@max_heap_table_size;
# Or
SHOW VARIABLES LIKE 'max_heap_table_size"

# If already a memory table, the alter will not change anything.
# Only apply the new max size.
ALTER TABLE table_name ENGINE=MEMORY;
select * from externalactivity ea 
join crmcache cc on cc.personid = ea.RecipientPersonID
join person p on p.personid = ea.RecipientPersonID
where ea.successdate is null and externalid = 13342
SELECT ea.externalresponse, ea.recipientpersonid, ea.externalid, ea.customfield01, cc.crmid, concat (cc.firstname, ' ', cc.lastname) FROM externalactivity ea join crmcache cc on cc.crmid = ea.RecipientPersonID WHERE SuccessDate IS NULL
IFNULL(tppp.preferredname, 'WA') AS 'SOR'
FROM person p
JOIN student_program sp ON sp.personid=p.personid AND sp.statusid=1 AND sp.is_deleted=0
JOIN enrollment e ON e.personid=p.personid
JOIN enrollmenttostudentdebit esd USING (enrollmentid)
JOIN studentdebit sd USING (studentdebitid)
LEFT JOIN studentdebit asd ON asd.adjustsdebitid=sd.studentdebitid AND asd.obsolete=0
LEFT JOIN thirdpartypayerengagement tppe ON tppe.tppengagementid=sd.tppengagementid
LEFT JOIN thirdpartypayer tpp ON tpp.tppayerid=tppe.tppayerid
LEFT JOIN person tppp ON tppp.personid=tpp.tppayerpersonid
DELIMITER $$
DROP PROCEDURE IF EXISTS sp_no_math_la$$
CREATE PROCEDURE sp_no_math_la()

BEGIN

...


END $$
DELIMITER ;

CALL sp_no_math_la();
-- these scripts will delete the tables if it's already there

DROP TABLE IF EXISTS StudentEnrollments;
DROP TABLE IF EXISTS Students;
DROP TABLE IF EXISTS Classrooms;


-- create and populate the students table
CREATE TABLE Students
(
	StudentId INTEGER PRIMARY KEY,
	FirstName VARCHAR(200) NOT NULL,
	LastName VARCHAR(200) NOT NULL,
	Nationality VARCHAR(100) NOT NULL,
	DateOfBirth DATETIME NULL
);


INSERT INTO Students
	(StudentId, FirstName, LastName, Nationality, DateOfBirth)
VALUES
	('1','Mickey', 'Mouse', 'American', '1991-05-02'),
	('2','Donald', 'Duck', 'Japanese', '1992-11-12'),
	('3','Goofy', 'Goof', 'American', '1980-04-15'),
	('4','Daisy', 'Duck', 'French', '1985-02-16'),
	('5','Huey', 'Duck', 'French', '1986-05-19'),
	('6','Scrooge', 'McDuck', 'Japanese', '1983-11-11'),
	('7','Minnie', 'Mouse', 'Canadian', '1983-11-30'),
	('8','Louie', 'Duck', 'French', '1985-09-09');

-- create and populate the classroom table
CREATE TABLE Classrooms
(
	ClassroomId INTEGER PRIMARY KEY,
	ClassName VARCHAR(200) NOT NULL,
	Weight DECIMAL NOT NULL
);

INSERT INTO Classrooms
	(ClassroomId, ClassName, Weight)
VALUES
	(1, 'Public Interaction', 0.10),
	(2, 'Pranks', 0.15),
	(3, 'Running', 0.15),
	(4, 'Acting', 0.30),
	(5, 'Making Jokes', 0.30);

-- create and populate the student enrollment table
CREATE TABLE StudentEnrollments
(
	StudentEnrollmentId INTEGER PRIMARY KEY,
	StudentId INTEGER NOT NULL,
	ClassroomId INTEGER NOT NULL,
	Grade DECIMAL NOT NULL,
	FOREIGN KEY(StudentId) REFERENCES Students(StudentId),
	FOREIGN KEY(ClassroomId) REFERENCES Classrooms(ClassroomId)
);

INSERT INTO StudentEnrollments
	(StudentEnrollmentId, StudentId, ClassroomId, Grade)
VALUES
	(1, 1, 1, 91),
	(2, 1, 2, 68),
	(3, 1, 3, 89),
	(4, 1, 4, 60),
	(5, 1, 5, 65),
	(6, 2, 1, 79),
	(7, 2, 2, 85),
	(8, 2, 3, 68),
	(9, 2, 4, 89),
	(10, 2, 5, 80),
	(11, 3, 1, 96),
	(12, 3, 2, 62),
	(13, 3, 3, 78),
	(14, 3, 4, 100),
	(15, 3, 5, 64),
	(16, 4, 1, 81),
	(17, 4, 2, 90),
	(18, 4, 3, 85),
	(19, 4, 4, 95),
	(20, 4, 5, 64),
	(21, 5, 1, 81),
	(22, 5, 2, 73),
	(23, 5, 3, 60),
	(24, 5, 4, 99),
	(25, 5, 5, 70),
	(26, 6, 1, 75),
	(27, 6, 2, 74),
	(28, 6, 3, 69),
	(29, 6, 4, 79),
	(30, 6, 5, 88),
	(31, 7, 1, 60),
	(32, 7, 2, 75),
	(33, 7, 3, 82),
	(34, 7, 4, 66),
	(35, 7, 5, 65),
	(36, 8, 1, 69),
	(37, 8, 2, 81),
	(38, 8, 3, 100),
	(39, 8, 4, 63),
	(40, 8, 5, 62);
CONCAT(',', section_id, ',') REGEXP ',(val1|val2|val3),'"
UPDATE deltadb.transactions_temp
SET ticker =(CASE CEIL(RAND()*2)
              WHEN 1 THEN '3CN:SP'
              WHEN 2 THEN 'AGV:SP'
          END);
SELECT ticker,`datetime`
FROM (
  SELECT ticker, MAX(`datetime`) `datetime`
  FROM Bloomberg_hist_data
  GROUP BY ticker
) t ORDER BY `datetime`
CURRENT_TIMESTAMP	ON UPDATE CURRENT_TIMESTAMP
CREATE TABLE firends (
	id INTEGER,
  	firstname VARCHAR(64)
);
Db::getInstance()->executeS("DELETE FROM product_images WHERE id_product NOT IN (" . join($allProductIds,',') . ")")
SELECT id, account_id, amount, created_at, null as type
 	FROM subscription_invoice
UNION ALL
SELECT id, account_id, amount, created_at, 
	`type` as type
FROM subscription_payment
ORDER BY created_at DESC
ALTER DATABASE database CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
sudo killall mysqld
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start
[root@jiaoyou mysql]# pwd
/var/lib/mysql
[root@jiaoyou mysql]# ls -ls
338256 -rw-rw---- 1 mysql mysql 346030080 2010-04-22 08:08 ibdata1
626812 -rw-rw---- 1 mysql mysql 641222072 2010-01-26 07:17 mysql-bin.000008
316892 -rw-rw---- 1 mysql mysql 324173772 2010-03-25 12:51 mysql-bin.000009
52724 -rw-rw---- 1 mysql mysql  53931666 2010-04-12 12:13 mysql-bin.000010
10136 -rw-rw---- 1 mysql mysql  10359639 2010-04-22 08:32 mysql-bin.000011

mysql> SHOW BINARY LOGS; 
+------------------+-----------+
| Log_name         | File_size |
+------------------+-----------+
| mysql-bin.000008 | 641222072 | 
| mysql-bin.000009 | 324173772 | 
| mysql-bin.000010 |  53931666 | 
| mysql-bin.000011 |  10360680 | 
+------------------+-----------+


Solution

PURGE BINARY LOGS TO 'mysql-bin.010';
star

Fri Sep 16 2022 11:17:18 GMT+0000 (UTC)

#drupal #mysql
star

Wed Sep 14 2022 14:16:13 GMT+0000 (UTC)

#mysql
star

Wed Sep 14 2022 13:34:16 GMT+0000 (UTC) https://phpdelusions.net/pdo

#mysql #bd #pdo #php
star

Tue Sep 13 2022 08:46:33 GMT+0000 (UTC)

#drupal #mysql
star

Mon Sep 12 2022 17:18:06 GMT+0000 (UTC)

#drupal #mysql
star

Mon Sep 12 2022 17:17:17 GMT+0000 (UTC)

#drupal #mysql
star

Thu Sep 08 2022 09:32:40 GMT+0000 (UTC) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:30:39 GMT+0000 (UTC) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:24:44 GMT+0000 (UTC) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:22:09 GMT+0000 (UTC) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:17:16 GMT+0000 (UTC) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:13:05 GMT+0000 (UTC) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Wed Sep 07 2022 08:10:48 GMT+0000 (UTC) https://gist.github.com/nextab/6a9b33919ab15e1f59828b4798682dd4

#mysql #sql
star

Wed Aug 17 2022 05:42:53 GMT+0000 (UTC)

#bash #mysql #slack
star

Tue Aug 16 2022 15:21:47 GMT+0000 (UTC)

#bash #mysql
star

Tue Aug 16 2022 15:21:46 GMT+0000 (UTC)

#bash #mysql
star

Wed Aug 10 2022 10:55:35 GMT+0000 (UTC)

#drupal #mysql
star

Wed Aug 10 2022 10:55:10 GMT+0000 (UTC)

#drupal #mysql
star

Fri Aug 05 2022 03:15:02 GMT+0000 (UTC) https://www.aidication.com/adminer/?username

#mysql #sql
star

Wed Aug 03 2022 10:14:47 GMT+0000 (UTC)

#drupal #mysql
star

Wed Aug 03 2022 10:14:27 GMT+0000 (UTC)

#drupal #mysql
star

Tue Aug 02 2022 10:18:11 GMT+0000 (UTC)

#drupal #mysql
star

Tue Jul 26 2022 12:41:49 GMT+0000 (UTC)

#drupal #mysql
star

Mon Jul 25 2022 20:01:19 GMT+0000 (UTC)

#drupal #mysql
star

Mon Jul 11 2022 15:04:49 GMT+0000 (UTC)

#drupal #mysql
star

Mon Jul 04 2022 20:25:04 GMT+0000 (UTC)

#sql #mysql
star

Mon Jul 04 2022 18:56:51 GMT+0000 (UTC)

#sql #mysql
star

Mon Jun 20 2022 14:19:04 GMT+0000 (UTC)

#mysql
star

Mon Jun 20 2022 14:18:47 GMT+0000 (UTC)

#mysql
star

Mon Jun 13 2022 20:07:08 GMT+0000 (UTC)

#drupal #mysql
star

Mon Jun 13 2022 20:06:44 GMT+0000 (UTC)

#drupal #mysql
star

Mon Jun 13 2022 19:47:28 GMT+0000 (UTC)

#drupal #mysql
star

Mon Jun 13 2022 19:46:54 GMT+0000 (UTC)

#drupal #mysql
star

Thu May 26 2022 14:07:36 GMT+0000 (UTC)

#drupal #mysql
star

Mon May 09 2022 19:58:09 GMT+0000 (UTC)

#mysql
star

Mon Apr 25 2022 18:35:28 GMT+0000 (UTC)

#sql #mysql
star

Fri Apr 22 2022 18:52:53 GMT+0000 (UTC)

#ci #mysql #portal
star

Fri Apr 22 2022 18:51:59 GMT+0000 (UTC)

#ci #mysql #portal
star

Fri Apr 22 2022 18:50:28 GMT+0000 (UTC)

#ci #mysql #portal
star

Sat Apr 16 2022 22:53:29 GMT+0000 (UTC)

#mysql
star

Fri Feb 25 2022 12:24:42 GMT+0000 (UTC) https://stackoverflow.com/questions/136782/convert-from-mysql-datetime-to-another-format-with-php

#php #date #mysql
star

Sat Feb 12 2022 23:13:25 GMT+0000 (UTC) https://stackoverflow.com/questions/9620198/how-to-get-the-sizes-of-the-tables-of-a-mysql-database

#mysql
star

Thu Jan 27 2022 08:33:32 GMT+0000 (UTC)

#mysql #mysqldump #remote
star

Wed Dec 22 2021 16:17:30 GMT+0000 (UTC) https://dba.stackexchange.com/questions/76788/create-a-mysql-database-with-charset-utf-8

#sql #mysql #mysql5.7
star

Thu Dec 09 2021 11:10:27 GMT+0000 (UTC)

#mysql #wordpress
star

Mon Dec 06 2021 17:34:36 GMT+0000 (UTC) https://stackoverflow.com/questions/23921117/disable-only-full-group-by

#mysql
star

Thu Nov 25 2021 14:40:12 GMT+0000 (UTC) https://gitlab.hornetsecurity.com/search?group_id

#python #mysql
star

Fri Nov 19 2021 08:45:09 GMT+0000 (UTC) https://www.reddit.com/r/aws/comments/gj1i1u/permanently_setting_binlog_retention_period_on/

#mysql #binlog
star

Tue Oct 19 2021 23:21:22 GMT+0000 (UTC) https://stackoverflow.com/questions/33123985/cannot-load-driver-class-com-mysql-jdbc-driver-spring/33124093

#mysql
star

Mon Oct 04 2021 14:33:05 GMT+0000 (UTC)

#mysql
star

Tue Sep 14 2021 06:05:48 GMT+0000 (UTC)

#mysql
star

Tue Aug 24 2021 06:36:11 GMT+0000 (UTC) https://explainextended.com/2009/07/20/hierarchical-data-in-mysql-parents-and-children-in-one-query/

#mysql
star

Tue Aug 17 2021 13:18:20 GMT+0000 (UTC)

#shell #mysql
star

Fri Jul 30 2021 13:35:57 GMT+0000 (UTC)

#shell #mysql
star

Fri Jul 30 2021 11:22:00 GMT+0000 (UTC)

#shell #mysql
star

Wed Jul 07 2021 14:11:01 GMT+0000 (UTC)

#mysql #json #update
star

Sun Jun 13 2021 04:34:51 GMT+0000 (UTC)

#sql #mysql
star

Sun Jun 13 2021 04:23:51 GMT+0000 (UTC)

#sql #mysql
star

Fri Jun 11 2021 14:23:59 GMT+0000 (UTC)

#database #mysql
star

Mon Jun 07 2021 20:53:33 GMT+0000 (UTC) https://www.neovision.ch/wie-sie-den-strict-modus-von-mysql-deaktivieren-konnen/

#mysql #strict #no-default-value
star

Thu May 27 2021 02:07:15 GMT+0000 (UTC)

#mysql
star

Wed May 26 2021 14:47:11 GMT+0000 (UTC)

#mysql
star

Thu May 20 2021 18:48:25 GMT+0000 (UTC)

#mysql
star

Thu May 13 2021 15:59:59 GMT+0000 (UTC)

#mysql
star

Sun May 02 2021 09:41:55 GMT+0000 (UTC) https://static.skillshare.com/uploads/attachment/1192226128/8c1374ad/Create%20the%20Initial%20Tables%20Script.txt

#sql #mysql
star

Fri Apr 23 2021 03:00:36 GMT+0000 (UTC)

#mysql
star

Wed Apr 07 2021 13:17:21 GMT+0000 (UTC)

#mysql
star

Fri Apr 02 2021 14:04:01 GMT+0000 (UTC)

#mysql
star

Wed Mar 31 2021 04:36:51 GMT+0000 (UTC)

#mysql
star

Wed Mar 31 2021 04:36:19 GMT+0000 (UTC)

#mysql
star

Wed Mar 24 2021 11:01:54 GMT+0000 (UTC)

#mysql
star

Fri Dec 11 2020 11:39:30 GMT+0000 (UTC)

#sql #mysql
star

Tue Oct 27 2020 17:03:36 GMT+0000 (UTC)

#sql #mysql
star

Thu Sep 17 2020 09:02:02 GMT+0000 (UTC) https://stackoverflow.com/questions/21267064/mysql-database-wont-start-in-xampp-manager-osx

#mysql
star

Mon Aug 10 2020 07:06:36 GMT+0000 (UTC) https://serverfault.com/questions/134840/what-are-these-files-can-i-delete-them-manually

#mysql

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension