问:
Advanced product filtering based on user's values
I already built a simple product configurator using HTML/CSS and JS (jQuery), but my project needs advanced filtering based on user's values.

Short project description - a special strollers configurator where You can select a product, put some accessories and order it.

What do I need?
Advanced filtering based on user's measurements (height, weight up to 10 unique values) which will show only compatibile products. Every stroller has a value range (Stroller1 has a height range from 100 to 130 cm). How to add this kind of form to my already existing project?

Code snippet:

jQuery(document).ready(function($) {
  function ProductBuilder(element) {
    this.element = element;
    this.stepsWrapper = this.element.children('.cd-builder-steps');
    this.steps = this.element.find('.builder-step');
    this.models = this.element.find('[data-selection="models"]');
    this.summary;
    this.optionsLists = this.element.find('.options-list');
    //podsumowanie
    this.fixedSummary = this.element.find('.cd-builder-footer');
    this.modelPreview = this.element.find('.selected-product').find('img');
    this.totPriceWrapper = this.element.find('.tot-price').find('b');
    //nawigacja
    this.mainNavigation = this.element.find('.cd-builder-main-nav');
    this.secondaryNavigation = this.element.find('.cd-builder-secondary-nav');
    //sprawdza, czy wszystko sie poprawnie zaladowalo
    this.loaded = true;

    this.bindEvents();
  }

  ProductBuilder.prototype.bindEvents = function() {
    var self = this;

    //wykrywa klikniecie na nawigacje z lewej strony
    this.mainNavigation.on('click', 'li:not(.active)', function(event) {
      event.preventDefault();
      self.loaded && self.newContentSelected($(this).index());
    });

    //wykrywa klikniecie na dole
    this.secondaryNavigation.on('click', '.nav-item li:not(.buy)', function(event) {
      event.preventDefault();
      var stepNumber = ($(this).parents('.next').length > 0) ? $(this).index() + 1 : $(this).index() - 1;
      self.loaded && self.newContentSelected(stepNumber);
    });
    //wykrywa klik na liscie u gory (podsumowanie, kolory itd)
    this.optionsLists.on('click', '.js-option', function(event) {
      self.updateListOptions($(this));
    });
    //wykrywa klik podczas "ubierania" sprzetu
    this.stepsWrapper.on('click', '.cd-product-customizer a', function(event) {
      event.preventDefault();
      self.customizeModel($(this));
    });
  };

  ProductBuilder.prototype.newContentSelected = function(nextStep) {
    //sprawdza, czy produkt zostal wybrany
    if (this.fixedSummary.hasClass('disabled')) {
      //jesli nie - pokazuje alert
      this.fixedSummary.addClass('show-alert');
    } else {
      //jezeli zostal wybrany, przechodzi dalej
      //sprawdza, czy kolor zostal wybrany
      if (this.steps.filter('.active').is('[data-selection="colors"]')) {
        //jezeli kolor zostal zmieniony, zaktualizuj zdjecie
        var imageSelected = this.steps.filter('.active').find('.cd-product-previews').children('.selected').children('img').attr('src');
        this.modelPreview.attr('src', imageSelected);
      }
      //zaktualizuj podglad produktu na dole
      if (nextStep + 1 >= this.steps.length) {
        this.createSummary();
      }

      this.showNewContent(nextStep);
      this.updatePrimaryNav(nextStep);
      this.updateSecondaryNav(nextStep);
    }
  }

  ProductBuilder.prototype.showNewContent = function(nextStep) {
    var actualStep = this.steps.filter('.active').index() + 1;
    if (actualStep < nextStep + 1) {
      //nawiguj do nastepnej sekcji
      this.steps.eq(actualStep - 1).removeClass('active back').addClass('move-left');
      this.steps.eq(nextStep).addClass('active').removeClass('move-left back');
    } else {
      //powroc do poprzedniej sekcji
      this.steps.eq(actualStep - 1).removeClass('active back move-left');
      this.steps.eq(nextStep).addClass('active back').removeClass('move-left');
    }
  }

  ProductBuilder.prototype.updatePrimaryNav = function(nextStep) {
    this.mainNavigation.find('li').eq(nextStep).addClass('active').siblings('.active').removeClass('active');
  }

  ProductBuilder.prototype.updateSecondaryNav = function(nextStep) {
    (nextStep == 0) ? this.fixedSummary.addClass('step-1'): this.fixedSummary.removeClass('step-1');

    this.secondaryNavigation.find('.nav-item.next').find('li').eq(nextStep).addClass('visible').removeClass('visited').prevAll().removeClass('visited').addClass('visited').end().nextAll().removeClass('visible visited');
    this.secondaryNavigation.find('.nav-item.prev').find('li').eq(nextStep).addClass('visible').removeClass('visited').prevAll().removeClass('visited').addClass('visited').end().nextAll().removeClass('visible visited');
  }

  ProductBuilder.prototype.createSummary = function() {
    var self = this;
    this.steps.each(function() {
      var step = $(this);
      if ($(this).data('selection') == 'colors') {
        //podsumowanie - kolor
        var colorSelected = $(this).find('.cd-product-customizer').find('.selected'),
          color = colorSelected.children('a').data('color'),
          colorName = colorSelected.data('content'),
          imageSelected = $(this).find('.cd-product-previews').find('.selected img').attr('src');

        self.summary.find('.summary-color').find('.color-label').text(colorName).siblings('.color-swatch').attr('data-color', color);
        self.summary.find('.product-preview').attr('src', imageSelected);
      } else if ($(this).data('selection') == 'accessories') {
        var selectedOptions = $(this).find('.js-option.selected'),
          optionsContent = '';

        if (selectedOptions.length == 0) {
          optionsContent = '

Nie wybrano żadnych akcesoriów;

';
        } else {
          selectedOptions.each(function() {
            optionsContent += '

' + $(this).find('p').text() + '

';
          });
        }

        self.summary.find('.summary-accessories').children('li').remove().end().append($(optionsContent));
      }
    });
  }

  ProductBuilder.prototype.updateListOptions = function(listItem) {
    var self = this;

    if (listItem.hasClass('js-radio')) {
      //pozwala na wybranie tylko jednej opcji w produktach
      var alreadySelectedOption = listItem.siblings('.selected'),
        price = (alreadySelectedOption.length > 0) ? -Number(alreadySelectedOption.data('price')) : 0;

      //odznaczenie opcji
      (listItem.hasClass('selected')) ?
      price = -Number(listItem.data('price')): price = Number(listItem.data('price')) + price;

      //odznacz wszystkie opcje
      alreadySelectedOption.removeClass('selected');
      //przelacz opcje
      listItem.toggleClass('selected');
      //zaktualizuj totalPrice
      (listItem.parents('[data-selection="models"]').length == 0) && self.updatePrice(price);
    } else {
      //mozna wybrac jedna niz wiecej opcji
      var price = (listItem.hasClass('selected')) ? -Number(listItem.data('price')) : Number(listItem.data('price'));
      //przelacz opcje
      listItem.toggleClass('selected');
      //zaktualizuj totalPrice
      self.updatePrice(price);
    }

    if (listItem.parents('[data-selection="models"]').length > 0) {
      self.updateModelContent(listItem);
    }
  };

  ProductBuilder.prototype.updateModelContent = function(model) {
    var self = this;
    if (model.hasClass('selected')) {
      var modelType = model.data('model'),
        modelImage = model.find('img').attr('src');

      this.modelPreview.attr('src', modelImage);

      //usun tresc odnoszaca sie do innego modelu
      this.models.siblings('li').remove();
      //zaladuj nowa tresc
      $.ajax({
        type: "GET",
        dataType: "html",
        url: modelType + ".html",
        beforeSend: function() {
          self.loaded = false;
          model.siblings().removeClass('loaded');
        },
        success: function(data) {
          self.models.after(data);
          self.loaded = true;
          model.addClass('loaded');
          //aktywuj nawigacje
          self.fixedSummary.add(self.mainNavigation).removeClass('disabled show-alert');
          //zaktualizuj dane obiektu
          self.steps = self.element.find('.builder-step');
          self.summary = self.element.find('[data-selection="summary"]');
          //wykrywa klik na liscie opcji
          self.optionsLists.off('click', '.js-option');
          self.optionsLists = self.element.find('.options-list');
          self.optionsLists.on('click', '.js-option', function(event) {
            self.updateListOptions($(this));
          });

          //nie wczytuj animacji przy pierwszym wczytaniu nowej zawartosci
          self.element.find('.first-load').removeClass('first-load');
        },
        error: function(jqXHR, textStatus, errorThrown) {}
      });

      //zaktualizuj cene
      this.totPriceWrapper.text(model.data('price'));
    } else {
      //nie wybrano produktu
      this.fixedSummary.add(this.mainNavigation).addClass('disabled');
      //zaktualizuj cene
      this.totPriceWrapper.text('0');

      this.models.find('.loaded').removeClass('loaded');
    }
  };

  ProductBuilder.prototype.customizeModel = function(target) {
    var parent = target.parent('li')
    index = parent.index();

    //zaktualizuj podsumowanie
    var price = (parent.hasClass('selected')) ?
      0 :
      Number(parent.data('price')) - parent.siblings('.selected').data('price');

    this.updatePrice(price);
    target.parent('li').addClass('selected').siblings().removeClass('selected').parents('.cd-product-customizer').siblings('.cd-product-previews').children('.selected').removeClass('selected').end().children('li').eq(index).addClass('selected');
  };

  ProductBuilder.prototype.updatePrice = function(price) {
    var actualPrice = Number(this.totPriceWrapper.text()) + price;
    this.totPriceWrapper.text(actualPrice);
  };

  if ($('.cd-product-builder').length > 0) {
    $('.cd-product-builder').each(function() {
      new ProductBuilder($(this));
    });
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div class="cd-product-builder">
  <header class="main-header">
    <h1>Wybierz odpowiedni produkt</h1>
    <nav class="cd-builder-main-nav disabled">
      <ul>
        <li class="active">Produkt</li>
        <li>Kolorystyka</li>
        <li>Akcesoria</li>
        <li>Podsumowanie</li>
      </ul>
    </nav>
  </header>
  <div class="cd-builder-steps">
    <ul>
      <li data-selection="models" class="active builder-step">
        <section class="cd-step-content">
          <header>
            <h1>Wybierz produkt</h1>
            <span class="steps-indicator">Step <b>1</b> of 4</span>
          </header>
          <!-- ponizej sa wszystkie 4 produkty -->
          <ul class="models-list options-list cd-col-2">
            <li class="js-option js-radio" data-price="2499" data-model="product-01">
              <span class="name">Tatalu</span>
              <img src="img/tat01.jpg" alt="wzrost100">
              <span class="price">Idealny dla dzieci do 100 cm wzrostu. <br>Dostępny już od 2499 zł</span>
              <div class="radio"></div>
            </li>

            <li class="js-option js-radio" data-price="3549" data-model="product-02">
              <span class="name">Mamalu</span>
              <img src="img/mam01.jpg" alt="wzrost130">
              <span class="price">Idealny dla dzieci do 130 cm wzrostu. <br>Dostępny już od 3549 zł</span>
              <div class="radio"></div>
            </li>
            <li class="js-option js-radio" data-price="4499" data-model="product-03">
              <span class="name">Ulises</span>
              <img src="img/ule01.jpg" alt="wzrost150">
              <span class="price">Idealny dla dzieci do 150 cm wzrostu. <br>Dostępny już od 4499 zł</span>
              <div class="radio"></div>
            </li>
            <li class="js-option js-radio" data-price="5999" data-model="product-04">
              <span class="name">Ursus</span>
              <img src="img/ursus02.jpg" alt="wzrost180">
              <span class="price">Idealny dla dorosłych do 180 cm wzrostu. <br>Dostępny już od 5999 zł</span>
              <div class="radio"></div>
            </li>
          </ul>
        </section>
      </li>
    </ul>
  </div>
  <footer class="cd-builder-footer disabled step-1">
    <div class="selected-product">
      <img src="img/tat01.jpg" alt="Product preview">
      <div class="tot-price">
        <span>Podsumowanie</span>
        <span class="total"><b>0</b> zł</span>
      </div>
    </div>
    <nav class="cd-builder-secondary-nav">
      <ul>
        <li class="next nav-item">
          <ul>
            <li class="visible">Kolorystyka</li>
            <li>Akcesoria</li>
            <li>Podsumowanie</li>
            <li class="buy">Kup teraz</li>
          </ul>
        </li>
        <li class="prev nav-item">
          <ul>
            <li class="visible">Produkt</li>
            <li>Produkt</li>
            <li>Kolorystyka</li>
            <li>Akcesoria</li>
          </ul>
        </li>
      </ul>
    </nav>
    <span class="alert">Aby kontynuować, wybierz produkt</span>
  </footer>
</div></code>```

What do I need? Advanced filtering based on user's measurements (height, weight up to 10 unique values) which will show only compatibile products. Every stroller has a value range (Stroller1 has a height range from 100 to 130 cm). How to add this kind of form to my already existing project?

Body:
I already built a simple product configurator using HTML/CSS and JS (jQuery), but my project needs advanced filtering based on user's values.

Short project description - a special strollers configurator where You can select a product, put some accessories and order it.

What do I need?
Advanced filtering based on user's measurements (height, weight up to 10 unique values) which will show only compatibile products. Every stroller has a value range (Stroller1 has a height range from 100 to 130 cm). How to add this kind of form to my already existing project?

Code snippet:

jQuery(document).ready(function($) {
  function ProductBuilder(element) {
    this.element = element;
    this.stepsWrapper = this.element.children('.cd-builder-steps');
    this.steps = this.element.find('.builder-step');
    this.models = this.element.find('[data-selection="models"]');
    this.summary;
    this.optionsLists = this.element.find('.options-list');
    //podsumowanie
    this.fixedSummary = this.element.find('.cd-builder-footer');
    this.modelPreview = this.element.find('.selected-product').find('img');
    this.totPriceWrapper = this.element.find('.tot-price').find('b');
    //nawigacja
    this.mainNavigation = this.element.find('.cd-builder-main-nav');
    this.secondaryNavigation = this.element.find('.cd-builder-secondary-nav');
    //sprawdza, czy wszystko sie poprawnie zaladowalo
    this.loaded = true;

    this.bindEvents();
  }

  ProductBuilder.prototype.bindEvents = function() {
    var self = this;

    //wykrywa klikniecie na nawigacje z lewej strony
    this.mainNavigation.on('click', 'li:not(.active)', function(event) {
      event.preventDefault();
      self.loaded && self.newContentSelected($(this).index());
    });

    //wykrywa klikniecie na dole
    this.secondaryNavigation.on('click', '.nav-item li:not(.buy)', function(event) {
      event.preventDefault();
      var stepNumber = ($(this).parents('.next').length > 0) ? $(this).index() + 1 : $(this).index() - 1;
      self.loaded && self.newContentSelected(stepNumber);
    });
    //wykrywa klik na liscie u gory (podsumowanie, kolory itd)
    this.optionsLists.on('click', '.js-option', function(event) {
      self.updateListOptions($(this));
    });
    //wykrywa klik podczas "ubierania" sprzetu
    this.stepsWrapper.on('click', '.cd-product-customizer a', function(event) {
      event.preventDefault();
      self.customizeModel($(this));
    });
  };

  ProductBuilder.prototype.newContentSelected = function(nextStep) {
    //sprawdza, czy produkt zostal wybrany
    if (this.fixedSummary.hasClass('disabled')) {
      //jesli nie - pokazuje alert
      this.fixedSummary.addClass('show-alert');
    } else {
      //jezeli zostal wybrany, przechodzi dalej
      //sprawdza, czy kolor zostal wybrany
      if (this.steps.filter('.active').is('[data-selection="colors"]')) {
        //jezeli kolor zostal zmieniony, zaktualizuj zdjecie
        var imageSelected = this.steps.filter('.active').find('.cd-product-previews').children('.selected').children('img').attr('src');
        this.modelPreview.attr('src', imageSelected);
      }
      //zaktualizuj podglad produktu na dole
      if (nextStep + 1 >= this.steps.length) {
        this.createSummary();
      }

      this.showNewContent(nextStep);
      this.updatePrimaryNav(nextStep);
      this.updateSecondaryNav(nextStep);
    }
  }

  ProductBuilder.prototype.showNewContent = function(nextStep) {
    var actualStep = this.steps.filter('.active').index() + 1;
    if (actualStep < nextStep + 1) {
      //nawiguj do nastepnej sekcji
      this.steps.eq(actualStep - 1).removeClass('active back').addClass('move-left');
      this.steps.eq(nextStep).addClass('active').removeClass('move-left back');
    } else {
      //powroc do poprzedniej sekcji
      this.steps.eq(actualStep - 1).removeClass('active back move-left');
      this.steps.eq(nextStep).addClass('active back').removeClass('move-left');
    }
  }

  ProductBuilder.prototype.updatePrimaryNav = function(nextStep) {
    this.mainNavigation.find('li').eq(nextStep).addClass('active').siblings('.active').removeClass('active');
  }

  ProductBuilder.prototype.updateSecondaryNav = function(nextStep) {
    (nextStep == 0) ? this.fixedSummary.addClass('step-1'): this.fixedSummary.removeClass('step-1');

    this.secondaryNavigation.find('.nav-item.next').find('li').eq(nextStep).addClass('visible').removeClass('visited').prevAll().removeClass('visited').addClass('visited').end().nextAll().removeClass('visible visited');
    this.secondaryNavigation.find('.nav-item.prev').find('li').eq(nextStep).addClass('visible').removeClass('visited').prevAll().removeClass('visited').addClass('visited').end().nextAll().removeClass('visible visited');
  }

  ProductBuilder.prototype.createSummary = function() {
    var self = this;
    this.steps.each(function() {
      var step = $(this);
      if ($(this).data('selection') == 'colors') {
        //podsumowanie - kolor
        var colorSelected = $(this).find('.cd-product-customizer').find('.selected'),
          color = colorSelected.children('a').data('color'),
          colorName = colorSelected.data('content'),
          imageSelected = $(this).find('.cd-product-previews').find('.selected img').attr('src');

        self.summary.find('.summary-color').find('.color-label').text(colorName).siblings('.color-swatch').attr('data-color', color);
        self.summary.find('.product-preview').attr('src', imageSelected);
      } else if ($(this).data('selection') == 'accessories') {
        var selectedOptions = $(this).find('.js-option.selected'),
          optionsContent = '';

        if (selectedOptions.length == 0) {
          optionsContent = '

Nie wybrano żadnych akcesoriów;

';
        } else {
          selectedOptions.each(function() {
            optionsContent += '

' + $(this).find('p').text() + '

';
          });
        }

        self.summary.find('.summary-accessories').children('li').remove().end().append($(optionsContent));
      }
    });
  }

  ProductBuilder.prototype.updateListOptions = function(listItem) {
    var self = this;

    if (listItem.hasClass('js-radio')) {
      //pozwala na wybranie tylko jednej opcji w produktach
      var alreadySelectedOption = listItem.siblings('.selected'),
        price = (alreadySelectedOption.length > 0) ? -Number(alreadySelectedOption.data('price')) : 0;

      //odznaczenie opcji
      (listItem.hasClass('selected')) ?
      price = -Number(listItem.data('price')): price = Number(listItem.data('price')) + price;

      //odznacz wszystkie opcje
      alreadySelectedOption.removeClass('selected');
      //przelacz opcje
      listItem.toggleClass('selected');
      //zaktualizuj totalPrice
      (listItem.parents('[data-selection="models"]').length == 0) && self.updatePrice(price);
    } else {
      //mozna wybrac jedna niz wiecej opcji
      var price = (listItem.hasClass('selected')) ? -Number(listItem.data('price')) : Number(listItem.data('price'));
      //przelacz opcje
      listItem.toggleClass('selected');
      //zaktualizuj totalPrice
      self.updatePrice(price);
    }

    if (listItem.parents('[data-selection="models"]').length > 0) {
      self.updateModelContent(listItem);
    }
  };

  ProductBuilder.prototype.updateModelContent = function(model) {
    var self = this;
    if (model.hasClass('selected')) {
      var modelType = model.data('model'),
        modelImage = model.find('img').attr('src');

      this.modelPreview.attr('src', modelImage);

      //usun tresc odnoszaca sie do innego modelu
      this.models.siblings('li').remove();
      //zaladuj nowa tresc
      $.ajax({
        type: "GET",
        dataType: "html",
        url: modelType + ".html",
        beforeSend: function() {
          self.loaded = false;
          model.siblings().removeClass('loaded');
        },
        success: function(data) {
          self.models.after(data);
          self.loaded = true;
          model.addClass('loaded');
          //aktywuj nawigacje
          self.fixedSummary.add(self.mainNavigation).removeClass('disabled show-alert');
          //zaktualizuj dane obiektu
          self.steps = self.element.find('.builder-step');
          self.summary = self.element.find('[data-selection="summary"]');
          //wykrywa klik na liscie opcji
          self.optionsLists.off('click', '.js-option');
          self.optionsLists = self.element.find('.options-list');
          self.optionsLists.on('click', '.js-option', function(event) {
            self.updateListOptions($(this));
          });

          //nie wczytuj animacji przy pierwszym wczytaniu nowej zawartosci
          self.element.find('.first-load').removeClass('first-load');
        },
        error: function(jqXHR, textStatus, errorThrown) {}
      });

      //zaktualizuj cene
      this.totPriceWrapper.text(model.data('price'));
    } else {
      //nie wybrano produktu
      this.fixedSummary.add(this.mainNavigation).addClass('disabled');
      //zaktualizuj cene
      this.totPriceWrapper.text('0');

      this.models.find('.loaded').removeClass('loaded');
    }
  };

  ProductBuilder.prototype.customizeModel = function(target) {
    var parent = target.parent('li')
    index = parent.index();

    //zaktualizuj podsumowanie
    var price = (parent.hasClass('selected')) ?
      0 :
      Number(parent.data('price')) - parent.siblings('.selected').data('price');

    this.updatePrice(price);
    target.parent('li').addClass('selected').siblings().removeClass('selected').parents('.cd-product-customizer').siblings('.cd-product-previews').children('.selected').removeClass('selected').end().children('li').eq(index).addClass('selected');
  };

  ProductBuilder.prototype.updatePrice = function(price) {
    var actualPrice = Number(this.totPriceWrapper.text()) + price;
    this.totPriceWrapper.text(actualPrice);
  };

  if ($('.cd-product-builder').length > 0) {
    $('.cd-product-builder').each(function() {
      new ProductBuilder($(this));
    });
  }
});

Wybierz odpowiedni produkt

Produkt

Kolorystyka

Akcesoria

Podsumowanie

Wybierz produkt

            Step 1 of 4

              Tatalu

              Idealny dla dzieci do 100 cm wzrostu.
Dostępny już od 2499 zł

              Mamalu

              Idealny dla dzieci do 130 cm wzrostu.
Dostępny już od 3549 zł

              Ulises

              Idealny dla dzieci do 150 cm wzrostu.
Dostępny już od 4499 zł

              Ursus

              Idealny dla dorosłych do 180 cm wzrostu.
Dostępny już od 5999 zł

        Podsumowanie
        0 zł

Kolorystyka

Akcesoria

Podsumowanie

Kup teraz

Produkt

Produkt

Kolorystyka

Akcesoria

    Aby kontynuować, wybierz produkt

What do I need? Advanced filtering based on user's measurements (height, weight up to 10 unique values) which will show only compatibile products. Every stroller has a value range (Stroller1 has a height range from 100 to 130 cm). How to add this kind of form to my already existing project?


来源: stackexchange

问:
Errors when using Connect-SDK
I am trying to build a POC using Connect-SDK-Android. I followed the step mentioned here
https://github.com/ConnectSDK/Connect-SDK-Android-API-Sampler

After cloning I am able to run the project 'Connect-SDK-Android' in Android Studio without any error. Also I could not connect phone to wifi using this
enter image description here
when i try to run test project it fails with below error

```<code>FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':testDebugUnitTest'.
> Could not resolve all task dependencies for configuration ':debugUnitTestRuntimeClasspath'.
   > Could not resolve project :Connect-SDK-Android.
     Required by:
         project :
      > Unable to find a matching configuration of project :Connect-SDK-Android:
          - None of the consumable configurations have attributes.
* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Exception is:
org.gradle.api.internal.tasks.TaskDependencyResolveException: Could not determine the dependencies of task ':testDebugUnitTest'.
    at org.gradle.api.internal.tasks.CachingTaskDependencyResolveContext.getDependencies(CachingTaskDependencyResolveContext.java:69)
    at org.gradle.execution.plan.TaskDependencyResolver.resolveDependenciesFor(TaskDependencyResolver.java:46)
    at org.gradle.execution.plan.LocalTaskNode.getDependencies(LocalTaskNode.java:161)
    at org.gradle.execution.plan.LocalTaskNode.resolveDependencies(LocalTaskNode.java:129)

    ------------------- some content removed  to reduce line -------------------org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:63)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:52)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)

</code>```

Any insights on this would be helpful.

As per suggestions received online i tried using below variations in build.gradle

```<code>//implementation project(':Connect-SDK-Android')
OR
//implementation 'com.github.ConnectSDK:Connect-SDK-Android:master-SNAPSHOT'
</code>```

ContentLicense: CC BY-SA 4.0

Title: Errors when using Connect-SDK

Body:
I am trying to build a POC using Connect-SDK-Android. I followed the step mentioned here
https://github.com/ConnectSDK/Connect-SDK-Android-API-Sampler

After cloning I am able to run the project 'Connect-SDK-Android' in Android Studio without any error. Also I could not connect phone to wifi using this
enter image description here
when i try to run test project it fails with below error

FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':testDebugUnitTest'.
> Could not resolve all task dependencies for configuration ':debugUnitTestRuntimeClasspath'.
   > Could not resolve project :Connect-SDK-Android.
     Required by:
         project :
      > Unable to find a matching configuration of project :Connect-SDK-Android:
          - None of the consumable configurations have attributes.
* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Exception is:
org.gradle.api.internal.tasks.TaskDependencyResolveException: Could not determine the dependencies of task ':testDebugUnitTest'.
    at org.gradle.api.internal.tasks.CachingTaskDependencyResolveContext.getDependencies(CachingTaskDependencyResolveContext.java:69)
    at org.gradle.execution.plan.TaskDependencyResolver.resolveDependenciesFor(TaskDependencyResolver.java:46)
    at org.gradle.execution.plan.LocalTaskNode.getDependencies(LocalTaskNode.java:161)
    at org.gradle.execution.plan.LocalTaskNode.resolveDependencies(LocalTaskNode.java:129)

    ------------------- some content removed  to reduce line -------------------org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:63)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:52)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)

Any insights on this would be helpful.

As per suggestions received online i tried using below variations in build.gradle

//implementation project(':Connect-SDK-Android')
OR
//implementation 'com.github.ConnectSDK:Connect-SDK-Android:master-SNAPSHOT'


问:
SQL Server Always Encrypted w/ Secure Enclave - Key Management Strategy
I am looking into ways to build a data warehouse that would house confidential data for 1+ clients. The requirement is that our organization can never obtain access to the decrypted data. There would be a web application clients utilize to write data and query data (basic select statements including ranges).

I've been learning about SQL Server Always Encrypted w/ Secure Enclaves (and Azure SQL Always Encrypted w/ Secure Enclaves) and am wondering about key management strategies.

Based on what I've read here: https://learn.microsoft.com/en-us/sql/relational-databases/security/encryption/always-encrypted-enclaves?view=sql-server-ver16 and even here https://aws.amazon.com/blogs/modernizing-with-aws/sql-server-always-encrypted-with-secure-enclaves/ , it seems like at the end of the day, someone in an organization utilizing this, is going to maintain access of the actual keys that could be used to decrypt the data.

Microsoft suggests role separation such that a DBA may have access to the database, but not access to the keys used for encryption and a Security Admin has access to the keys but not the actual database.

But, hypothetically, if the DBA and Security Admin wanted to be malicious together, they could technically obtain access to the data together. Are there strategies that can be employed to help mitigate this potential risk?

I'm wondering if the key management could be placed onto the client(s) instead of one of our own Security Admins - that way, technically, it would be completely impossible for our organization to ever have access to the data in a decrypted form. This would mean that for each client, there would be a column master key that they would store/manage and pass to us (encrypted). We'd use this to programmatically retrieve the column encryption key(s) relevant to their querying.

I've never worked around architectures involving confidential computing and am curious if the direction I am headed seems reasonable and/or if folks have any thoughts, advice, or could point me to any documentation involving key management strategies where clients house their own keys to access their data hosted by some other service.


问:
Outline onItemClick works only once
In the React-pdf library, the onitemclick props of the Outline component only works once, while the same props but of the Document component always work.
I send the piece of code, where you can see that the Outline component is wrapped in a MUI Drawer component, so that the outline is rendered in a sidebar.</p>
```<code> const [page, setPage] = useState(1);

 const clickTOC = ({ pageNumber: itemPageNumber }) => {
        setPage(itemPageNumber)
    }

<Grid xl={6}>
   <Box sx={{ my: 4 }}>
      <Document file={file} onLoadSuccess={onDocumentLoadSuccess} options={options} onItemClick={clickTOC}>
      <Page key={`page_${page}`} pageNumber={page} onRenderSuccess={onPageRenderSuccess} customTextRenderer={textRenderer} renderTextLayer="true" />
      <Drawer variant="persistent" anchor="left" open={state}>
          <DrawerHeader>
              <Typography variant="body3" display="block" color='black' gutterBottom>
                 INDICE
              </Typography>
              <IconButton onClick={TOCClose}>
                 <ChevronLeftIcon />
              </IconButton>
          </DrawerHeader>
          <Divider />
          <Box sx={{ width: drawerWidth }} role="presentation">
            <Outline onItemClick={clickTOC} onLoadSuccess={(outline) => toc(outline)} />
          </Box>
      </Drawer>
    </Document>
    <Pagination page={page} count={numPages} color="primary" onChange={(e, page) => setPage(page)} />
   </Box>
</Grid>
</code>```

Title: Outline onItemClick works only once

Body:
In the React-pdf library, the onitemclick props of the Outline component only works once, while the same props but of the Document component always work.
I send the piece of code, where you can see that the Outline component is wrapped in a MUI Drawer component, so that the outline is rendered in a sidebar.

 const [page, setPage] = useState(1);

 const clickTOC = ({ pageNumber: itemPageNumber }) => {
        setPage(itemPageNumber)
    }

<Grid xl={6}>
   <Box sx={{ my: 4 }}>
      <Document file={file} onLoadSuccess={onDocumentLoadSuccess} options={options} onItemClick={clickTOC}>
      <Page key={`page_${page}`} pageNumber={page} onRenderSuccess={onPageRenderSuccess} customTextRenderer={textRenderer} renderTextLayer="true" />
      <Drawer variant="persistent" anchor="left" open={state}>
          <DrawerHeader>
              <Typography variant="body3" display="block" color='black' gutterBottom>
                 INDICE
              </Typography>
              <IconButton onClick={TOCClose}>
                 <ChevronLeftIcon />
              </IconButton>
          </DrawerHeader>
          <Divider />
          <Box sx={{ width: drawerWidth }} role="presentation">
            <Outline onItemClick={clickTOC} onLoadSuccess={(outline) => toc(outline)} />
          </Box>
      </Drawer>
    </Document>
    <Pagination page={page} count={numPages} color="primary" onChange={(e, page) => setPage(page)} />
   </Box>
</Grid>


问:
mongoose and mongoDB nodejs in query
This is my user schema

```<code>const userSchema = new mongoose.Schema(
  {
......
    groups: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Group",
      },
    ],
}
</code>```

I want if the user is teacher to view just the students that related to him (that mean that the students has one of his groups)

for example if the theacher has 2 groups "group1", "group2" I want all the students that has or group1 or group2 or both

This is my current code but I didnt get any user

```<code>//getting the groups that related to the teacher
 const {groups} = await User.findOne({ username }).select("groups").lean().exec();
    const usersQuery = {
      active: true,
      groups: { $in: groups },

    };
</code>```

Title: mongoose and mongoDB nodejs in query

Body:
This is my user schema

const userSchema = new mongoose.Schema(
  {
......
    groups: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Group",
      },
    ],
}

I want if the user is teacher to view just the students that related to him (that mean that the students has one of his groups)

for example if the theacher has 2 groups "group1", "group2" I want all the students that has or group1 or group2 or both

This is my current code but I didnt get any user

//getting the groups that related to the teacher
 const {groups} = await User.findOne({ username }).select("groups").lean().exec();
    const usersQuery = {
      active: true,
      groups: { $in: groups },

    };


问:
Find the RIP instruction pointer in x64 MSVC?
Trying to find the runtime memory address of this instruction in the code below

```<code>int here = 42;
</code>```

Is this a correct approach and are there other methods?

In the x64 version of the Microsoft Visual C++ (MSVC) compiler, the RIP register (also known as the "instruction pointer register") is a 64-bit register that holds the memory address of the next instruction to be executed.

https://godbolt.org/z/f8WzGMqsE

I think godbolt uses a debug build as int here = 42; has not been optimized out.

```<code>#include <stdio.h>

void* RIP = NULL;

__declspec(noinline) void GetRIP(void)
{
    // RIP is the instruction pointer register on a 64-bit platform.
    RIP = _ReturnAddress();
}

int main(void)
{
    GetRIP();

    // Find the runtime memory address of this instruction.
    int here = 42;

    printf("RIP = %p\n", RIP);

    return 0;
}
</code>```

In MASM x64, the RIP is found using this technique

```<code>option casemap:none

extrn printf:proc

.data
     szRIP db 'RIP = %p',0ah,0

.code

main proc
     call    _here
_here:
     pop     rax
     ; rax now holds the RIP.
     mov     rdx,rax
     mov     rcx,offset szRIP
     sub     rsp,20h
     call    printf
     add     rsp,20h

     ret
main endp

end
</code>```

Body:
Trying to find the runtime memory address of this instruction in the code below

int here = 42;

Is this a correct approach and are there other methods?

In the x64 version of the Microsoft Visual C++ (MSVC) compiler, the RIP register (also known as the "instruction pointer register") is a 64-bit register that holds the memory address of the next instruction to be executed.

https://godbolt.org/z/f8WzGMqsE

I think godbolt uses a debug build as int here = 42; has not been optimized out.

#include <stdio.h>

void* RIP = NULL;

__declspec(noinline) void GetRIP(void)
{
    // RIP is the instruction pointer register on a 64-bit platform.
    RIP = _ReturnAddress();
}

int main(void)
{
    GetRIP();

    // Find the runtime memory address of this instruction.
    int here = 42;

    printf("RIP = %p\n", RIP);

    return 0;
}

In MASM x64, the RIP is found using this technique

option casemap:none

extrn printf:proc

.data
     szRIP db 'RIP = %p',0ah,0

.code

main proc
     call    _here
_here:
     pop     rax
     ; rax now holds the RIP.
     mov     rdx,rax
     mov     rcx,offset szRIP
     sub     rsp,20h
     call    printf
     add     rsp,20h

     ret
main endp

end


问:
is there a way to make events on google calendar into accounts signed with OAuthv2.0 on a CMS laravel website
sorry if this question is not sraightforward. I searched a lot and didn't find the result I want.

I have a CMS website which a specific role of user can link their account on the website to a google account by OAuth. I want to create event in user's calendar from by a form in my website. Now I have set the Oauth and I've created a form that creates events in my developer account.

All i found is creating events on developer account. I found one exactly like I want but in electron not laravel


问:
Expo React-Native Web Browser Back Button
I'm looking at using React-Native and Expo to build a web app. The only real issue I'm running into is allowing the use of the browser back button. I'm currently using @react-navigation/native to navigate between screens.

Unfortunately, when changing screens, the browser doesn't seem to register this as a change of page and so the browser back button never works. I could certainly use the standard back button used within the app to navigate back but I'd like people to be able to use the browser back button as that's more intuitive. I'm using the following in my App.js:

```<code>import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

const Stack = createNativeStackNavigator();

const App = () => {
...
return (
<NavigationContainer>
  <Stack.Navigator>
    <Stack.Screen
      name="Home"
      component={HomeScreen}
      options={{ headerShown: false }}
    />
    <Stack.Screen
      name="Settings"
      component={SettingsScreen}
      options={{ headerShown: false }}
    />
  </Stack.Navigator>
</NavigationContainer>
)
};

export default () => {
  return (
    <App />
  );
};
</code>```

So, is it possible using Expo and React-Native to allow the use of the browser back button for apps built for the web?

Body:
I'm looking at using React-Native and Expo to build a web app. The only real issue I'm running into is allowing the use of the browser back button. I'm currently using @react-navigation/native to navigate between screens.

Unfortunately, when changing screens, the browser doesn't seem to register this as a change of page and so the browser back button never works. I could certainly use the standard back button used within the app to navigate back but I'd like people to be able to use the browser back button as that's more intuitive. I'm using the following in my App.js:

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

const Stack = createNativeStackNavigator();

const App = () => {
...
return (
<NavigationContainer>
  <Stack.Navigator>
    <Stack.Screen
      name="Home"
      component={HomeScreen}
      options={{ headerShown: false }}
    />
    <Stack.Screen
      name="Settings"
      component={SettingsScreen}
      options={{ headerShown: false }}
    />
  </Stack.Navigator>
</NavigationContainer>
)
};

export default () => {
  return (
    <App />
  );
};

So, is it possible using Expo and React-Native to allow the use of the browser back button for apps built for the web?


问:
System Bottom Navigation Bar overlapping my views
I went into a problem, when using Samsung phones (android 12), system Nav bar is overlapping my views as follows
overlapping Nav bar

Here is my style.xml file

```<code><resources>

    <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar.Bridge">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@android:color/transparent</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="windowNoTitle">true</item>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowTranslucentNavigation">false</item>
        <item name="android:windowDrawsSystemBarBackgrounds">false</item>

        <item name="android:windowBackground">@drawable/shape_splash</item>
    </style>
</code>```

I also tried fitsSystemWindows property to set to true, but it did't work also.
Even tried layout_marginBottom parameter in the activity_main.xml file but still doesn't help.

What is the correct way to resolve this?

Body:
I went into a problem, when using Samsung phones (android 12), system Nav bar is overlapping my views as follows
overlapping Nav bar

Here is my style.xml file

<resources>

I also tried fitsSystemWindows property to set to true, but it did't work also.
Even tried layout_marginBottom parameter in the activity_main.xml file but still doesn't help.

What is the correct way to resolve this?


问:
Getting session counts, by source, from GA4 and BiqQuery
I've got GA4 pushing to BQ and I wanted to test some ideas, so I started with making sure my BiqQuery queries could duplicate (or at least get close to) what I see in the GA4 UI.

In GA4, I looked at the Traffic acquisition: Session source report and just looked at traffic with a source of 'google' for a specific date range. This is what I see:

So just under 16k sessions for google during this timeframe.

I then ran this query to get session counts by source and just had it show me the results for Google:

```<code>WITH prep AS (
SELECT
    user_pseudo_id,
    (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS session_id,
    MAX((SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'source')) AS source,
  FROM `disco-retina-319219.analytics_312878766.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20221112' AND '20221209'
group by
    user_pseudo_id,
    session_id)

SELECT
    COALESCE(source,'(direct)') AS source,
    COUNT(DISTINCT CONCAT(user_pseudo_id,session_id)) AS sessions
FROM
    prep
WHERE source='google'
GROUP BY
    source
ORDER BY
    sessions desc
</code>```

But it only shows 4,200 sessions.

I expected the results might be slightly off, but my BQ query is showing just over 4k sessions. Clearly I am doing something wrong, but I don't understand what. I'm getting a distinct list of the concatenated session ID and pseudo user ID; from what I've read this is the proper way to get a list of distinct sessions. I've verified that I am using the same date ranges in both (11/12/2022 - 12/9/2022) and that I hitting the proper table in BQ.

Body:
I've got GA4 pushing to BQ and I wanted to test some ideas, so I started with making sure my BiqQuery queries could duplicate (or at least get close to) what I see in the GA4 UI.

In GA4, I looked at the Traffic acquisition: Session source report and just looked at traffic with a source of 'google' for a specific date range. This is what I see:

So just under 16k sessions for google during this timeframe.

I then ran this query to get session counts by source and just had it show me the results for Google:

WITH prep AS (
SELECT
    user_pseudo_id,
    (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS session_id,
    MAX((SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'source')) AS source,
  FROM `disco-retina-319219.analytics_312878766.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20221112' AND '20221209'
group by
    user_pseudo_id,
    session_id)

SELECT
    COALESCE(source,'(direct)') AS source,
    COUNT(DISTINCT CONCAT(user_pseudo_id,session_id)) AS sessions
FROM
    prep
WHERE source='google'
GROUP BY
    source
ORDER BY
    sessions desc

But it only shows 4,200 sessions.

I expected the results might be slightly off, but my BQ query is showing just over 4k sessions. Clearly I am doing something wrong, but I don't understand what. I'm getting a distinct list of the concatenated session ID and pseudo user ID; from what I've read this is the proper way to get a list of distinct sessions. I've verified that I am using the same date ranges in both (11/12/2022 - 12/9/2022) and that I hitting the proper table in BQ.


问:
Discord Modal Form Body Issue?
```<code>Traceback (most recent call last):
  File "C:\Users\pacif\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\modal.py", line 186, in _scheduled_task
    await self.on_submit(interaction)
  File "c:\Users\pacif\OneDrive\Desktop\Essence Discord\Cogs\arcane.py", line 128, in on_submit
    await interaction.response.send_modal(Editor())
  File "C:\Users\pacif\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 852, in send_modal
    await adapter.create_interaction_response(
  File "C:\Users\pacif\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 221, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In type: Value must be one of {4, 5, 6, 7, 10}.
</code>```

A modal, after taking an input sends a new modal which is having issues.

I wanted it to send the new modal and allow you to send new inputs. Nada

Code: https://pastebin.com/cPuXJVCK

Title: Discord Modal Form Body Issue?

Body:
Traceback (most recent call last):
  File "C:\Users\pacif\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\modal.py", line 186, in _scheduled_task
    await self.on_submit(interaction)
  File "c:\Users\pacif\OneDrive\Desktop\Essence Discord\Cogs\arcane.py", line 128, in on_submit
    await interaction.response.send_modal(Editor())
  File "C:\Users\pacif\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 852, in send_modal
    await adapter.create_interaction_response(
  File "C:\Users\pacif\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 221, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In type: Value must be one of {4, 5, 6, 7, 10}.

A modal, after taking an input sends a new modal which is having issues.

I wanted it to send the new modal and allow you to send new inputs. Nada

Code: https://pastebin.com/cPuXJVCK


问:
Flutter Socket.IO cannot connect to server, but browser works fine
Was going to use Socket.IO for authorizing in a flutter application, but it wont work on anything other than localhost:

```<code>String serverURL = "https://example.awsapprunner.com";
IO.Socket socket = IO.io('$serverURL/client', <String, dynamic>{'transports': ['websocket']});

checkUserExists(String phoneNum, context) {
  socket.connect();
  socket.emit('login', phoneNum);

  socket.on('login_error', (res)=> {
    log("new user"),
  });

  socket.on('session-started',(sid)=>{
    log("old user!"),
  });
}
</code>```

The app won't even connect to the socket so anything after socket.connent() never runs.

Here's what I have tried

'autoConnect': true

replacing 'https' with 'wss' or 'ws'

removing 'https://' altogether

Different Cloud Services (AWS, GC, Azure)

local server (works and connects perfectly fine)

connecting to the server via browser (also works perfectly fine)

Body:
Was going to use Socket.IO for authorizing in a flutter application, but it wont work on anything other than localhost:

String serverURL = "https://example.awsapprunner.com";
IO.Socket socket = IO.io('$serverURL/client', <String, dynamic>{'transports': ['websocket']});

checkUserExists(String phoneNum, context) {
  socket.connect();
  socket.emit('login', phoneNum);

  socket.on('login_error', (res)=> {
    log("new user"),
  });

  socket.on('session-started',(sid)=>{
    log("old user!"),
  });
}

The app won't even connect to the socket so anything after socket.connent() never runs.

Here's what I have tried

'autoConnect': true

replacing 'https' with 'wss' or 'ws'

removing 'https://' altogether

Different Cloud Services (AWS, GC, Azure)

local server (works and connects perfectly fine)

connecting to the server via browser (also works perfectly fine)


问:
gem5 - linking to external library's header/binaries
We are trying to build gem5 with an external library (redis server). We tried passing the library's binary file paths as LINKFLAGS to the build. But the build is failing and the error states that the redis library is not found.

Does any one have any experience linking external libraries with gem5?
We are trying to use the redis library to send messages from the gem5's cache access function to another external process (a python function).


问:
Huffman Encoder, trying to pass a string from a txt file with no luck. <3 lines needed
I have a file named "EE.txt" that contains the string: "E R R O R". As you can see in the compiler notes I have posted, I'm trying to call Huffman Tree and pass EE.txt along with it, for the filename. Anyone have any suggestions?

HuffmanNode.java

```<code>public class HuffmanNode implements Comparable
{
    public String letter;
    public Double frequency;
    public HuffmanNode left, right;

    // - add constructors to initialize letter and frequency, etc.
    public HuffmanNode(String letter, Double frequency)
    {
        this.letter = letter;
        this.frequency = frequency;
    }

    public HuffmanNode(String letter, Double frequency)
    {
        Double freq = Double.parseDouble( frequency );
        this.letter = letter;
        this.frequency = freq;
    }

    public HuffmanNode(HuffmanNode left, HuffmanNode right)
    {
        this.left = left;
        this.right = right;
        this.letter = left.letter + right.letter;
        this.frequency = left.frequency + right.frequency;
    }

    public String toString()
    {
        return "<" + this.letter + ", " + this.frequency + ">";
    }

    public int compareTo(Object o)
    {
        HuffmanNode huff = (HuffmanNode) o;
        return this.frequency.compareTo( huff.frequency );
    }
}
</code>```

HuffmanTree

```<code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class HuffmanTree {

    HuffmanNode root;

    // - add a constructor to init the Tree from a HuffmanNode
    public HuffmanTree(HuffmanNode huff)
    {
        this.root = huff;
    }

    // print legend
    public void printLegend()
    {
        this.printLegend(this.root, "");
    }

    private void printLegend(HuffmanNode t, String s)
    {
        if( t.letter.length() > 1 )
        {
            this.printLegend( t.left, s + "0");
            this.printLegend( t.right, s + "1" );
        }
        else
        {
            System.out.print( t.letter + "=" + s );
        }
    }

    // takes a String for the file name containing our input (letter & frequency data).
    // The letters and frequencies are all in the first line of the file, with spaces as separators.
    // (You may assume each separator is a single space).
    public static BinaryHeap fileToHeap(String filename)
    {
        try {
            BufferedReader br = new BufferedReader(new FileReader( filename ));

            String line = br.readLine();
            br.close();

            String[] key = line.split(" ");
            HuffmanNode[] huffs = new HuffmanNode[ key.length / 2];
            int i = 0;
            int j = 0;
            while( i < key.length )
            {
                huffs[ j ] = new HuffmanNode( key[i], key[i + 1]);
//          System.out.println( key[i] + " " + key[i + 1 ] );

                i = i + 2;
                j++;
            }

            BinaryHeap heap = new BinaryHeap( huffs );
            return heap;

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static HuffmanTree createFromHeap(BinaryHeap b)
    {
        try {
            while( b.getSize() > 1 )
            {
                HuffmanNode huff1 = (HuffmanNode) b.deleteMin();
                HuffmanNode huff2 = (HuffmanNode) b.deleteMin();
                HuffmanNode huff = new HuffmanNode( huff1, huff2 );
                b.insert( huff );
            }
            HuffmanTree tree = new HuffmanTree( (HuffmanNode) b.deleteMin() );
            return tree;
        } catch (Underflow e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    // - the main method will go here, as well as code to take
    //   a command-line argument for the input file name
    /**
     * @param args
     */
    public static void main(String[] args) {
        **// TODO Auto-generated method stub
        BinaryHeap bheap = HuffmanTree.fileToHeap( "EE.txt");

        bheap.printHeap();
        HuffmanTree htree = HuffmanTree.createFromHeap( bheap );
        htree.printLegend();
    }**

}
</code>```

I believe it is the main method that is causing all of the problems. I just am not quite sure how to edit it.

Compiler:

```<code>HuffmanEncoder % java HuffmanTree EE.txt
Exception in thread "main" java.lang.NumberFormatException: For input string: "R"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.base/java.lang.Double.parseDouble(Double.java:735)
    at HuffmanNode.<init>(HuffmanNode.java:16)
    at HuffmanTree.fileToHeap(HuffmanTree.java:53)
    at HuffmanTree.main(HuffmanTree.java:99)

</code>```

Body:
I have a file named "EE.txt" that contains the string: "E R R O R". As you can see in the compiler notes I have posted, I'm trying to call Huffman Tree and pass EE.txt along with it, for the filename. Anyone have any suggestions?

HuffmanNode.java

public class HuffmanNode implements Comparable
{
    public String letter;
    public Double frequency;
    public HuffmanNode left, right;

    // - add constructors to initialize letter and frequency, etc.
    public HuffmanNode(String letter, Double frequency)
    {
        this.letter = letter;
        this.frequency = frequency;
    }

    public HuffmanNode(String letter, Double frequency)
    {
        Double freq = Double.parseDouble( frequency );
        this.letter = letter;
        this.frequency = freq;
    }

    public HuffmanNode(HuffmanNode left, HuffmanNode right)
    {
        this.left = left;
        this.right = right;
        this.letter = left.letter + right.letter;
        this.frequency = left.frequency + right.frequency;
    }

    public String toString()
    {
        return "<" + this.letter + ", " + this.frequency + ">";
    }

    public int compareTo(Object o)
    {
        HuffmanNode huff = (HuffmanNode) o;
        return this.frequency.compareTo( huff.frequency );
    }
}

HuffmanTree

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class HuffmanTree {

    HuffmanNode root;

    // - add a constructor to init the Tree from a HuffmanNode
    public HuffmanTree(HuffmanNode huff)
    {
        this.root = huff;
    }

    // print legend
    public void printLegend()
    {
        this.printLegend(this.root, "");
    }

    private void printLegend(HuffmanNode t, String s)
    {
        if( t.letter.length() > 1 )
        {
            this.printLegend( t.left, s + "0");
            this.printLegend( t.right, s + "1" );
        }
        else
        {
            System.out.print( t.letter + "=" + s );
        }
    }

    // takes a String for the file name containing our input (letter & frequency data).
    // The letters and frequencies are all in the first line of the file, with spaces as separators.
    // (You may assume each separator is a single space).
    public static BinaryHeap fileToHeap(String filename)
    {
        try {
            BufferedReader br = new BufferedReader(new FileReader( filename ));

            String line = br.readLine();
            br.close();

            String[] key = line.split(" ");
            HuffmanNode[] huffs = new HuffmanNode[ key.length / 2];
            int i = 0;
            int j = 0;
            while( i < key.length )
            {
                huffs[ j ] = new HuffmanNode( key[i], key[i + 1]);
//          System.out.println( key[i] + " " + key[i + 1 ] );

                i = i + 2;
                j++;
            }

            BinaryHeap heap = new BinaryHeap( huffs );
            return heap;

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static HuffmanTree createFromHeap(BinaryHeap b)
    {
        try {
            while( b.getSize() > 1 )
            {
                HuffmanNode huff1 = (HuffmanNode) b.deleteMin();
                HuffmanNode huff2 = (HuffmanNode) b.deleteMin();
                HuffmanNode huff = new HuffmanNode( huff1, huff2 );
                b.insert( huff );
            }
            HuffmanTree tree = new HuffmanTree( (HuffmanNode) b.deleteMin() );
            return tree;
        } catch (Underflow e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    // - the main method will go here, as well as code to take
    //   a command-line argument for the input file name
    /**
     * @param args
     */
    public static void main(String[] args) {
        **// TODO Auto-generated method stub
        BinaryHeap bheap = HuffmanTree.fileToHeap( "EE.txt");

        bheap.printHeap();
        HuffmanTree htree = HuffmanTree.createFromHeap( bheap );
        htree.printLegend();
    }**

}

I believe it is the main method that is causing all of the problems. I just am not quite sure how to edit it.

Compiler:

HuffmanEncoder % java HuffmanTree EE.txt
Exception in thread "main" java.lang.NumberFormatException: For input string: "R"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.base/java.lang.Double.parseDouble(Double.java:735)
    at HuffmanNode.<init>(HuffmanNode.java:16)
    at HuffmanTree.fileToHeap(HuffmanTree.java:53)
    at HuffmanTree.main(HuffmanTree.java:99)


问:
Display progress during save() in R?
Suppose the data objects are quite large and the saving takes a while, is there someway to display the progress of the save() function in R? How about showing that in the UI in Shiny?</p>

Title: Display progress during save() in R?


问:
Adding field in theresult of aggregate in mongoose
Hello I am trying to add a field to my aggregation result that contains an array of distinctively selected brands(field of my model)

My data look like

```<code>{
      "name": "64gb Blue",
      "price": 200,
      "salePrice": 190,
      "saleStartingDate": null,
      "saleEndingDate": null,
      "productImages": [
        {
          "imageId": "636675a83553963e30161f9b",
          "path": "iphone13.jpg",
          "alt": "iPhone 13 picture",
          "description": "iPhone 13 is the new phone",
          "_id": "6366778942f0826bda3300ac"
        }
      ],
      "_id": "6366769942f0826bda3300a4",
      "brand": "Apple",
      "ItemName": "iPhone 13",
      "slug": "iPhone-13",
      "status": "In-Stock",
      "category": "phones",
      "date_created": "2022-11-05T14:43:37.955Z",
      "fullName": "iPhone 13 64gb Blue",
      "queryName": "phones Apple iPhone 13 64gb Blue"
    },
    {
      "name": "64gb Red",
      "price": 250,
      "salePrice": 200,
      "saleStartingDate": null,
      "saleEndingDate": null,
      "productImages": [
        {
          "imageId": "636675a83553963e30161f9b",
          "path": "iphone13.jpg",
          "alt": "iPhone 13 picture",
          "description": "iPhone 13 is the new phone",
          "_id": "636677a442f0826bda3300b2"
        }
      ],
      "_id": "6366769942f0826bda3300a4",
      "brand": "Apple",
      "ItemName": "iPhone 13",
      "slug": "iPhone-13",
      "status": "In-Stock",
      "category": "phones",
      "date_created": "2022-11-05T14:43:37.955Z",
      "fullName": "iPhone 13 64gb Red",
      "queryName": "phones Apple iPhone 13 64gb Red"
    }
</code>```

This result comes from this aggregate

```<code>[
            {
                $unwind: "$variants"
            },{
            $addFields: {
                "variants._id": "$_id",
                "variants.brand": "$brand",
                "variants.ItemName": "$name",
                "variants.slug": "$slug",
                "variants.status": "$status",
                "variants.category":"$category.name",
                "variants.date_created": "$date_created",
                "variants.fullName":{$concat:["$name"," ","$variants.name"]},
                "variants.queryName":{$concat:["$category.name"," ","$brand"," ","$name"," ","$variants.name"]}
            }
        },
         {
            $replaceRoot: {
                newRoot: "$variants"
            }
        }]
</code>```

I want to add a field that contains all the brands ( distinct select) and the returned data should be like

```<code>{
    products:[ **result of aggregate I had before**]
    brands:[**list of distinctively selected brands**]
}
</code>```

I have seen examples with $facet but I didn't manage to get it working.

Body:
Hello I am trying to add a field to my aggregation result that contains an array of distinctively selected brands(field of my model)

My data look like

{
      "name": "64gb Blue",
      "price": 200,
      "salePrice": 190,
      "saleStartingDate": null,
      "saleEndingDate": null,
      "productImages": [
        {
          "imageId": "636675a83553963e30161f9b",
          "path": "iphone13.jpg",
          "alt": "iPhone 13 picture",
          "description": "iPhone 13 is the new phone",
          "_id": "6366778942f0826bda3300ac"
        }
      ],
      "_id": "6366769942f0826bda3300a4",
      "brand": "Apple",
      "ItemName": "iPhone 13",
      "slug": "iPhone-13",
      "status": "In-Stock",
      "category": "phones",
      "date_created": "2022-11-05T14:43:37.955Z",
      "fullName": "iPhone 13 64gb Blue",
      "queryName": "phones Apple iPhone 13 64gb Blue"
    },
    {
      "name": "64gb Red",
      "price": 250,
      "salePrice": 200,
      "saleStartingDate": null,
      "saleEndingDate": null,
      "productImages": [
        {
          "imageId": "636675a83553963e30161f9b",
          "path": "iphone13.jpg",
          "alt": "iPhone 13 picture",
          "description": "iPhone 13 is the new phone",
          "_id": "636677a442f0826bda3300b2"
        }
      ],
      "_id": "6366769942f0826bda3300a4",
      "brand": "Apple",
      "ItemName": "iPhone 13",
      "slug": "iPhone-13",
      "status": "In-Stock",
      "category": "phones",
      "date_created": "2022-11-05T14:43:37.955Z",
      "fullName": "iPhone 13 64gb Red",
      "queryName": "phones Apple iPhone 13 64gb Red"
    }

This result comes from this aggregate

[
            {
                $unwind: "$variants"
            },{
            $addFields: {
                "variants._id": "$_id",
                "variants.brand": "$brand",
                "variants.ItemName": "$name",
                "variants.slug": "$slug",
                "variants.status": "$status",
                "variants.category":"$category.name",
                "variants.date_created": "$date_created",
                "variants.fullName":{$concat:["$name"," ","$variants.name"]},
                "variants.queryName":{$concat:["$category.name"," ","$brand"," ","$name"," ","$variants.name"]}
            }
        },
         {
            $replaceRoot: {
                newRoot: "$variants"
            }
        }]

I want to add a field that contains all the brands ( distinct select) and the returned data should be like

{
    products:[ **result of aggregate I had before**]
    brands:[**list of distinctively selected brands**]
}

I have seen examples with $facet but I didn't manage to get it working.


问:
Having problems to add SSL to nuxt-axios web app on DOCKER
Well after many tests and brain burns trying with nginx, caddy and other resources to apply SSL I resort to this medium.

all the services are running on docker container.

I can't fully apply the certificates, rather I can't get my site to work with SSL, I can get to the login with https but then I can't get past that barrier:

to formalize:
https://example.com:3000/login (basic web domain)
https://example.com:3001/api (all my resources)

for https i have to change the axios BASEurl form: (recomendations from caddy forum)
this: http://example.com:3001/api
to this: https://example.com/api

to stop having the error of ERR_SSL_PROTOCOL_ERROR

I share my settings from my last failed attempt with caddy.
The truth is that at this point I don't know if it is a bad configuration problem on the caddy side or on the node-nuxt-axios side.

caddyfile:

```<code>{
 debug
}

example.com {

    handle_path /api/* {
        reverse_proxy /api/* node:3001
    }

    handle {
        reverse_proxy node:3000
    }
}

emqx.example.com {
    reverse_proxy emqx:18083
}
ws.example.com {
    reverse_proxy emqx:8083
}
wss.example.com {
    reverse_proxy emqx:8084
}

portainer.example.com {

   reverse_proxy portainer:9000

}
</code>```

here it goes nuxt.config.js

```<code>  axios: {
    baseURL: process.env.AXIOS_BASE_URL
  },
  env: {
    mqtt_prefix: process.env.MQTT_PREFIX,
    mqtt_host: process.env.MQTT_HOST,
    mqtt_port: process.env.MQTT_PORT
  },

  server: {
    https: true,
    port: 3000,
    host: '0.0.0.0',
  },

  serverMiddleware: {
    https: true,
    '/api': '~/api'
  },
</code>```

here is the index.js for api

```<code>const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const cors = require("cors");
const colors = require("colors");
const app = express();
require("dotenv").config();

//express config
app.use(morgan("tiny"));
app.use(express.json());
app.use(express.urlencoded({
  extended: true,
})
);

app.use(cors());

app.use("/api", require("./routes/devices.js"));
app.use("/api", require("./routes/users.js"));
app.use("/api", require("./routes/templates.js"));
app.use("/api", require("./routes/datas.js"));
app.use("/api", require("./routes/webhooks.js"));
app.use("/api", require("./routes/emqxapi.js"));
app.use("/api", require("./routes/alarms.js"));
app.use("/api", require("./routes/controls.js")); // nueva funcion
app.use("/api", require("./routes/dataprovider.js"));

module.exports = app;

//listener
app.listen(process.env.API_PORT, () => {
  console.log("API server listening on port " + process.env.API_PORT);
}); //api port 3001
</code>```

for the record all services works like a charm on http, but having problems with secure comunication.

Body:
Well after many tests and brain burns trying with nginx, caddy and other resources to apply SSL I resort to this medium.

all the services are running on docker container.

I can't fully apply the certificates, rather I can't get my site to work with SSL, I can get to the login with https but then I can't get past that barrier:

to formalize:
https://example.com:3000/login (basic web domain)
https://example.com:3001/api (all my resources)

for https i have to change the axios BASEurl form: (recomendations from caddy forum)
this: http://example.com:3001/api
to this: https://example.com/api

to stop having the error of ERR_SSL_PROTOCOL_ERROR

I share my settings from my last failed attempt with caddy.
The truth is that at this point I don't know if it is a bad configuration problem on the caddy side or on the node-nuxt-axios side.

caddyfile:

{
 debug
}

example.com {

    handle_path /api/* {
        reverse_proxy /api/* node:3001
    }

    handle {
        reverse_proxy node:3000
    }
}

emqx.example.com {
    reverse_proxy emqx:18083
}
ws.example.com {
    reverse_proxy emqx:8083
}
wss.example.com {
    reverse_proxy emqx:8084
}

portainer.example.com {

   reverse_proxy portainer:9000

}

here it goes nuxt.config.js

  axios: {
    baseURL: process.env.AXIOS_BASE_URL
  },
  env: {
    mqtt_prefix: process.env.MQTT_PREFIX,
    mqtt_host: process.env.MQTT_HOST,
    mqtt_port: process.env.MQTT_PORT
  },

  server: {
    https: true,
    port: 3000,
    host: '0.0.0.0',
  },

  serverMiddleware: {
    https: true,
    '/api': '~/api'
  },

here is the index.js for api

const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const cors = require("cors");
const colors = require("colors");
const app = express();
require("dotenv").config();

//express config
app.use(morgan("tiny"));
app.use(express.json());
app.use(express.urlencoded({
  extended: true,
})
);

app.use(cors());

app.use("/api", require("./routes/devices.js"));
app.use("/api", require("./routes/users.js"));
app.use("/api", require("./routes/templates.js"));
app.use("/api", require("./routes/datas.js"));
app.use("/api", require("./routes/webhooks.js"));
app.use("/api", require("./routes/emqxapi.js"));
app.use("/api", require("./routes/alarms.js"));
app.use("/api", require("./routes/controls.js")); // nueva funcion
app.use("/api", require("./routes/dataprovider.js"));

module.exports = app;

//listener
app.listen(process.env.API_PORT, () => {
  console.log("API server listening on port " + process.env.API_PORT);
}); //api port 3001

for the record all services works like a charm on http, but having problems with secure comunication.


问:
How to extract video data from video tag?
Hey folks I'm trying to save video from a video tag.

This is part of a scraping exercise on Tiktok and I cannot use the url directly to save the video, either in the browser or server.

I also cannot use canvases as I'm getting a tainted canvas error.

What would be the best way to save the video data?

```<code>// Example code
let video = document.querySelector('video');
let src = video.src;

// Do something with the el or the source??
</code>```

Body:
Hey folks I'm trying to save video from a video tag.

This is part of a scraping exercise on Tiktok and I cannot use the url directly to save the video, either in the browser or server.

I also cannot use canvases as I'm getting a tainted canvas error.

What would be the best way to save the video data?

// Example code
let video = document.querySelector('video');
let src = video.src;

// Do something with the el or the source??


问:
Cannot resolve fields declared in my Model in my view. Using thymleaf+Springboot+IntelliJ
So I am working on a small project (I'm a newbie) and I have been unable to access my fields declared in my model class from my view in Thymeleaf. I checked the documentation and I am certain I am doing everything as it should be but for some reason, IntelliJ gives me a "cannot resolve field" error. I checked here and there online and saw that It used to be an issue with IntelliJ which was supposedly fixed in their 2017.X version but I still get a similar error(I am using IntelliJ 2022.2.4). Can anyone please help?

This is my view page and I get an error at the level of th:field="*{loginDate}"

```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8">
    <title>ADD NEW RECORD</title>
    <link rel="stylesheet" type="text/css" th:href = "@{/webjars/bootstrap/css/bootstrap.min.css}"/>
</head>
<body>
<div class="container-fluid text-center">
    <div><h2>ADD NEW RECORD</h2></div>

    <form th:action="@{students/save}" th:object="${newStudent}" method="post" >
        <div class ="border">
            <div class="form-group row">
                <label class="col-sm-4 col-form-label">Date</label>
                <div class="col-sm-8">
                    <input type="date" **th:field="*{loginDate}"** class="form-control">

                </div>

            </div>

        </div>

    </form>

</div>

</body>
</html>
</code>```

Here is my controller:

```<code>package com.sfsb.studentsSFSB.students.controller;

import com.sfsb.studentsSFSB.students.model.Students;
import com.sfsb.studentsSFSB.students.service.StudentsServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class StudentController {
    private StudentsServiceImpl service;

    public StudentController(StudentsServiceImpl service) {
        this.service = service;
    }

    @GetMapping("")
    public String showHomePage(){
        return "index";
    }

    @GetMapping("/students/new")
    public String showForm(Model model){
        model.addAttribute("newStudent", new Students());
        return "student_form";

    }

    @GetMapping("/students")
    public String showStudentsList(Model model){
        List<Students> listStudents =  service.findAll();
        model.addAttribute("listStudents", listStudents);

        return "students";
    }

}

</code>```

And here is my model class

```<code>package com.sfsb.studentsSFSB.students.model;

import jakarta.persistence.*;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Entity
@Table(name = "students")
public class Students {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "FirstName")
    private String firstName;

    @Column(name = "LastName")
    private String lastName;

    @Column(name = "Date")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate loginDate;

    @Column(name = "LoginTime")
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime loginTime;

    @Column(name = "BreakPeriod")
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime breakPeriod;

    @Column(name = "LogoutTime")
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime logoutTime;

    @Column(name = "HoursWorkedPerDay")
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime workHoursPerDay;

    @Column(name = "Task")
    private String task;

    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime workHoursPerWeek;

    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime totalHoursForCurrentContract;

    //@DateTimeFormat(iso = DateTimeFormat.ISO.TIME) if above does not work
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime hoursLeftOnCurrentContract;

    //Method to calculate work hours per day based on login,break and logout values
    public LocalTime calculateWorkHoursPerDay(){
        //DateTimeFormatter Formatter = DateTimeFormatter.ofPattern("H:mm");
        Duration breakDuration = Duration.between(LocalTime.MIDNIGHT, breakPeriod);
        Duration workDuration = Duration.between(loginTime,logoutTime).minus(breakDuration);
        String workHoursInString = LocalTime.MIDNIGHT.plus(workDuration).toString();
        workHoursPerDay = LocalTime.parse(workHoursInString);
        return workHoursPerDay;

    }

}

</code>```

Body:
So I am working on a small project (I'm a newbie) and I have been unable to access my fields declared in my model class from my view in Thymeleaf. I checked the documentation and I am certain I am doing everything as it should be but for some reason, IntelliJ gives me a "cannot resolve field" error. I checked here and there online and saw that It used to be an issue with IntelliJ which was supposedly fixed in their 2017.X version but I still get a similar error(I am using IntelliJ 2022.2.4). Can anyone please help?

This is my view page and I get an error at the level of th:field="*{loginDate}"

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>ADD NEW RECORD</title>
    <link rel="stylesheet" type="text/css" th:href = "@{/webjars/bootstrap/css/bootstrap.min.css}"/>

ADD NEW RECORD

    <form th:action="@{students/save}" th:object="${newStudent}" method="post" >

                Date

                    <input type="date" **th:field="*{loginDate}"** class="form-control">

    </form>

Here is my controller:

package com.sfsb.studentsSFSB.students.controller;

import com.sfsb.studentsSFSB.students.model.Students;
import com.sfsb.studentsSFSB.students.service.StudentsServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class StudentController {
    private StudentsServiceImpl service;

    public StudentController(StudentsServiceImpl service) {
        this.service = service;
    }

    @GetMapping("")
    public String showHomePage(){
        return "index";
    }

    @GetMapping("/students/new")
    public String showForm(Model model){
        model.addAttribute("newStudent", new Students());
        return "student_form";

    }

    @GetMapping("/students")
    public String showStudentsList(Model model){
        List<Students> listStudents =  service.findAll();
        model.addAttribute("listStudents", listStudents);

        return "students";
    }

}

And here is my model class

package com.sfsb.studentsSFSB.students.model;

import jakarta.persistence.*;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Entity
@Table(name = "students")
public class Students {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "FirstName")
    private String firstName;

    @Column(name = "LastName")
    private String lastName;

    @Column(name = "Date")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate loginDate;

    @Column(name = "LoginTime")
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime loginTime;

    @Column(name = "BreakPeriod")
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime breakPeriod;

    @Column(name = "LogoutTime")
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime logoutTime;

    @Column(name = "HoursWorkedPerDay")
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime workHoursPerDay;

    @Column(name = "Task")
    private String task;

    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime workHoursPerWeek;

    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime totalHoursForCurrentContract;

    //@DateTimeFormat(iso = DateTimeFormat.ISO.TIME) if above does not work
    @DateTimeFormat(pattern = "HH:mm")
    private LocalTime hoursLeftOnCurrentContract;

    //Method to calculate work hours per day based on login,break and logout values
    public LocalTime calculateWorkHoursPerDay(){
        //DateTimeFormatter Formatter = DateTimeFormatter.ofPattern("H:mm");
        Duration breakDuration = Duration.between(LocalTime.MIDNIGHT, breakPeriod);
        Duration workDuration = Duration.between(loginTime,logoutTime).minus(breakDuration);
        String workHoursInString = LocalTime.MIDNIGHT.plus(workDuration).toString();
        workHoursPerDay = LocalTime.parse(workHoursInString);
        return workHoursPerDay;

    }

}


问:
AttributeError: module 'face_recognition' has no attribute 'load_image_file'
 I have succefully installed a library to perform face recognition; I have tried to use this on a program but I get an attribute error.

# Import the face_recognition library
import face_recognition
import face_recognition_models

# Load a sample image
image = face_recognition.load_image_file(r'C:\Users\WAJIH\Desktop\code\face')

# Detect faces in the image
face_locations = face_recognition.face_locations(image, model="cnn")

# Print the number of faces detected
print(f"{len(face_locations)} faces detected")
```
<p>out:</p>
```Traceback (most recent call last):
```

File "c:\Users\WAJIH\Desktop\Face-recognition-python-project-main\ss.py", line 1, in
import face_recognition
File "C:\Users\WAJIH\AppData\Local\Programs\Python\Python39\lib\site-packages\face_recognition_init_.py", line 7, in
from .api import load_image_file, face_locations, batch_face_locations, face_landmarks, face_encodings, compare_faces, face_distance
File "C:\Users\WAJIH\AppData\Local\Programs\Python\Python39\lib\site-packages\face_recognition\api.py", line 3, in
import PIL.Image
File "C:\Users\WAJIH\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL_init_.py", line 15, in
from . import _version
ValueError: source code string cannot contain null bytes

Body:
 I have succefully installed a library to perform face recognition; I have tried to use this on a program but I get an attribute error.

# Import the face_recognition library
import face_recognition
import face_recognition_models

# Load a sample image
image = face_recognition.load_image_file(r'C:\Users\WAJIH\Desktop\code\face')

# Detect faces in the image
face_locations = face_recognition.face_locations(image, model="cnn")

# Print the number of faces detected
print(f"{len(face_locations)} faces detected")

out:

Traceback (most recent call last):

File "c:\Users\WAJIH\Desktop\Face-recognition-python-project-main\ss.py", line 1, in
import face_recognition
File "C:\Users\WAJIH\AppData\Local\Programs\Python\Python39\lib\site-packages\face_recognition_init_.py", line 7, in
from .api import load_image_file, face_locations, batch_face_locations, face_landmarks, face_encodings, compare_faces, face_distance
File "C:\Users\WAJIH\AppData\Local\Programs\Python\Python39\lib\site-packages\face_recognition\api.py", line 3, in
import PIL.Image
File "C:\Users\WAJIH\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL_init_.py", line 15, in
from . import _version
ValueError: source code string cannot contain null bytes


问:
Loading indicator showLoading is not showing up
I am learning and trying to implement Sweetalert2 and at the same time, I am trying to mix it with Fetch API.

I have a html element like this:

```<code><a class="btn btn-sm btn-success" th:onClick="uploadMultipleUsingSwal()">Upload</a>
</code>```

and blend of Sweetalert2 and my JavaScript (Fetch API - POST) goes like this:

```<code>function uploadMultipleUsingSwal() {
    Swal.fire({
        title: 'Upload File(s)',
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('/uploadMultipleFiles', {
                method: 'POST',
                body: formData
            }).then((response) => {
                Swal.showLoading();  // This is NOT working
                response.json();
                Swal.fire(
                    'Uploaded!',
                    'All files uploaded successfully.',
                    'success'
                ).then(() => {
                    location.reload();
                });
            }).catch((error) => {
                Swal.fire(
                    'Upload Failed!',
                    error,
                    'error'
                )
            });
        } else if (result.isDenied) {
            Swal.fire('No file uploaded', 'Try again !', 'info')
        }
    })
}
</code>```

I am trying to show loading (Spinner) while waiting for the file upload to finish but somehow it doesn't show up and no errors in the console whatsoever.

What I am missing here? Or what I am doing wrong?

Update:

Following the link shared by Felix, I tried this:

```<code>function uploadMultipleUsingSwal() {
    let htmlstring = '<input type="file" id="file-selector" multiple>';

    Swal.fire({
        html: htmlstring,
        title: 'Do you want to get data from Github?',
        text: "You won't be able to revert this!",
        showDenyButton: true,
        denyButtonText: 'Cancel',
        showCloseButton: true,
        showConfirmButton: true,
        confirmButtonText: 'Upload',
        showLoaderOnConfirm: true,
        allowOutsideClick: () => !Swal.isLoading(),
        preConfirm: async function() {
            const fileselector = document.getElementById('file-selector');
            const fileselectorValid = Swal.getPopup().querySelector('#file-selector').value
            if (!fileselectorValid == "") {
                Swal.showValidationMessage(`Please select at least one or more file(s). !`)
            }
            var files = fileselector.files;
            var formData = new FormData();
            for (var index = 0; index < files.length; index++) {
                formData.append("files", files[index]);
            }
            return fetch('/uploadMultipleFiles', {
                method: 'POST',
                body: formData
            }).then((response) => {
                response.json();
                Swal.fire(
                    'Uploaded!',
                    'All files uploaded successfully.',
                    //'All files uploaded successfully. Response Code: ' + response.status,
                    'success'
                ).then(() => {
                    location.reload();
                });
            }).catch((error) => {
                Swal.fire(
                    'Upload Failed!',
                    error,
                    'error'
                )
            });
        }
    });
}
</code>```

But it broke the validation I had where I check for 0 files.

Body:
I am learning and trying to implement Sweetalert2 and at the same time, I am trying to mix it with Fetch API.

I have a html element like this:

Upload

and blend of Sweetalert2 and my JavaScript (Fetch API - POST) goes like this:

function uploadMultipleUsingSwal() {
    Swal.fire({
        title: 'Upload File(s)',
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('/uploadMultipleFiles', {
                method: 'POST',
                body: formData
            }).then((response) => {
                Swal.showLoading();  // This is NOT working
                response.json();
                Swal.fire(
                    'Uploaded!',
                    'All files uploaded successfully.',
                    'success'
                ).then(() => {
                    location.reload();
                });
            }).catch((error) => {
                Swal.fire(
                    'Upload Failed!',
                    error,
                    'error'
                )
            });
        } else if (result.isDenied) {
            Swal.fire('No file uploaded', 'Try again !', 'info')
        }
    })
}

I am trying to show loading (Spinner) while waiting for the file upload to finish but somehow it doesn't show up and no errors in the console whatsoever.

What I am missing here? Or what I am doing wrong?

Update:

Following the link shared by Felix, I tried this:

function uploadMultipleUsingSwal() {
    let htmlstring = '<input type="file" id="file-selector" multiple>';

    Swal.fire({
        html: htmlstring,
        title: 'Do you want to get data from Github?',
        text: "You won't be able to revert this!",
        showDenyButton: true,
        denyButtonText: 'Cancel',
        showCloseButton: true,
        showConfirmButton: true,
        confirmButtonText: 'Upload',
        showLoaderOnConfirm: true,
        allowOutsideClick: () => !Swal.isLoading(),
        preConfirm: async function() {
            const fileselector = document.getElementById('file-selector');
            const fileselectorValid = Swal.getPopup().querySelector('#file-selector').value
            if (!fileselectorValid == "") {
                Swal.showValidationMessage(`Please select at least one or more file(s). !`)
            }
            var files = fileselector.files;
            var formData = new FormData();
            for (var index = 0; index < files.length; index++) {
                formData.append("files", files[index]);
            }
            return fetch('/uploadMultipleFiles', {
                method: 'POST',
                body: formData
            }).then((response) => {
                response.json();
                Swal.fire(
                    'Uploaded!',
                    'All files uploaded successfully.',
                    //'All files uploaded successfully. Response Code: ' + response.status,
                    'success'
                ).then(() => {
                    location.reload();
                });
            }).catch((error) => {
                Swal.fire(
                    'Upload Failed!',
                    error,
                    'error'
                )
            });
        }
    });
}

But it broke the validation I had where I check for 0 files.


问:
discord.py how to remove documents in mongodb python
I'm trying to remove one and also able to remove all documents in a collection on mongodb and I'm not sure what to do.

```<code>@client.hybrid_command(name = "clearwarn", with_app_command=True, description="Delete a warn or all warns of a member", aliases=["clearwarns"])
@commands.guild_only()
@commands.is_owner()
@commands.has_permissions(moderate_members=True)
async def clearwarn(ctx, member: discord.Member = None, caseid = None):
    if member == None:
        await ctx.reply("A member is required")
    else:
        if caseid == None:
            check = list(warndb.warn_logs.find({ "user_id": member.id }))
            if check is None:
                await ctx.reply("This user doesn't have any warns to clear")
            else:
                warndb.warn_logs.delete_many(check)
                await ctx.reply(f"Removed all warnings from **{member.name}**")
                return
        else:
            try:
                check = list(warndb.warn_logs.find({"case_id": caseid}))
                warndb.warn_logs.delete_one(check)
                await ctx.reply(f"Removed 1 warning from **{member.name}**")
                return
            except:
                await ctx.reply("The case id you provided is invalid")
                return
</code>```

I'm trying to make it so if someone just does ;clearwarn @member it deletes all the warns/documents that member has but if they do ;clearwarn @member (caseid) then it'll delete only the warn/document that matches that case id.

```<code>randnum = random.randrange(1000, 999999)
        randnum2 = random.randrange(1000, 999999)
        warnid = f"{randnum}-{randnum2}"
        warndb.warn_logs.insert_one(
            {
                "guild_id": ctx.guild.id,
                "user_id": member.id,
                "moderator_id": ctx.author.id,
                "reason": str(reason),
                "case_id": warnid,
            }

        )
</code>```

This is how I sorted the db. If you know please help me I've been struggling on this for a while

Body:
I'm trying to remove one and also able to remove all documents in a collection on mongodb and I'm not sure what to do.

@client.hybrid_command(name = "clearwarn", with_app_command=True, description="Delete a warn or all warns of a member", aliases=["clearwarns"])
@commands.guild_only()
@commands.is_owner()
@commands.has_permissions(moderate_members=True)
async def clearwarn(ctx, member: discord.Member = None, caseid = None):
    if member == None:
        await ctx.reply("A member is required")
    else:
        if caseid == None:
            check = list(warndb.warn_logs.find({ "user_id": member.id }))
            if check is None:
                await ctx.reply("This user doesn't have any warns to clear")
            else:
                warndb.warn_logs.delete_many(check)
                await ctx.reply(f"Removed all warnings from **{member.name}**")
                return
        else:
            try:
                check = list(warndb.warn_logs.find({"case_id": caseid}))
                warndb.warn_logs.delete_one(check)
                await ctx.reply(f"Removed 1 warning from **{member.name}**")
                return
            except:
                await ctx.reply("The case id you provided is invalid")
                return

I'm trying to make it so if someone just does ;clearwarn @member it deletes all the warns/documents that member has but if they do ;clearwarn @member (caseid) then it'll delete only the warn/document that matches that case id.

randnum = random.randrange(1000, 999999)
        randnum2 = random.randrange(1000, 999999)
        warnid = f"{randnum}-{randnum2}"
        warndb.warn_logs.insert_one(
            {
                "guild_id": ctx.guild.id,
                "user_id": member.id,
                "moderator_id": ctx.author.id,
                "reason": str(reason),
                "case_id": warnid,
            }

        )

This is how I sorted the db. If you know please help me I've been struggling on this for a while


问:
App died on Heroku free and needs to be restarted
I had an app that worked perfectly under your free platform.  Heroku ended free in November and I am prepared to pay the monthly fee NP.  How do I get it running again?
Here is my link:
https://tmg-web-dev.herokuapp.com/users/sign_in</p>


问:
Why do I have blank page when serving VueJS 3 build with ExpressJS?
I have a web application, coded with VueJS 3, that runs well with npm run serve and npm run build; npx serve -s dist.

My problem is that, when serving the build files with ExpressJS and my NodeJS application, I can see in my browser that I successfuly downloaded all the required elements, but the only thing I get is a blank page, with no error.

I expect to see my application working, as it does with serve, or npm run serve. I launch my NodeJS application with npm run dev. Is it a problem?


问:
Why is there no output in this function/parameter?
```<code>def plus_ten(a):
    return a + 10

plus_ten(2)
</code>```

I thought that the plus_ten(2) would generate an output of 12, but when I run the code, it comes up with nothing.

Why is this?

This was lifted directly from: https://www.youtube.com/watch?v=lA9OuhldJd0&ab_channel=365DataScience

It shows in the video that there should be an output. However, in my VS studio, there is no output... please help!

Body:
def plus_ten(a):
    return a + 10

plus_ten(2)

I thought that the plus_ten(2) would generate an output of 12, but when I run the code, it comes up with nothing.

Why is this?

This was lifted directly from: https://www.youtube.com/watch?v=lA9OuhldJd0&ab_channel=365DataScience

It shows in the video that there should be an output. However, in my VS studio, there is no output... please help!