javascript – Erro ao chamar invocar Helper no handlebars

Criei um simples helper de switch no handlebars, aonde passo o value, operator e compare, o esperado é que o switch verifique o digitado e execute a função correspondente.
Na teoria acredito que deveria funcionar, contudo não sei se estou errando na forma de construir a função ou na invocação do helper.

// helpers

switch: function(value, operator, compare, options){
  switch (operator) {
    case '==':
        return (value == compare) ? options.fn(this) : options.inverse(this);
    case '===':
        return (value === compare) ? options.fn(this) : options.inverse(this);
    case '!=':
        return (value != compare) ? options.fn(this) : options.inverse(this);
    case '!==':
        return (value !== compare) ? options.fn(this) : options.inverse(this);
    case '<':
        return (value < compare) ? options.fn(this) : options.inverse(this);
    case '<=':
        return (value <= compare) ? options.fn(this) : options.inverse(this);
    case '>':
        return (value > compare) ? options.fn(this) : options.inverse(this);
    case '>=':
        return (value >= compare) ? options.fn(this) : options.inverse(this);
    case '&&':
        return (value && compare) ? options.fn(this) : options.inverse(this);
    case '||':
        return (value || compare) ? options.fn(this) : options.inverse(this);
    default:
        return options.inverse(this);
}

// index.hbs

{{#switch freeHours '<=' 0}}
  {{#case '<=' }} Teste {{/case}}
  {{#default '' }} erro {{/default}}
{{/switch}}

O único erro que recebo é Error: Missing helper: “case”

c# – Helper Class en Modelo

Hola tengo una clase modelo de un objeto que recibo de una api, pero tambien necesito aplicar algunos cambios a los valores segun el caso, originalmente estaba heredando a la clase las interfaces.

    public class MopDTO : INotifyPropertyChanged , IFormattable { 

   public string ToString(string format, IFormatProvider formatProvider)
        {
            switch (format)
            {
                //mi logica                 
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
 }

Pero mi jefe em esta pidiendo que mueva eso a una helper class, alguien sabe como puedo usar una Helper class en mi modelo de forma propia??

java – Reuse helper objects or recreate them on usage?

I would like to get some experienced advice about the handling of helper objects. Consider the following situation where we want to build a connector to a third party system. The connector shall translate business objects/entities of our domain into entities of that system and transfer them via HTTP:

abstract class BaseController {
    protected final HttpClient httpClient;
    // four more members like base URI and request timeout

    protected final Gson gson = new Gson();

    public BaseController(HttpClient httpClient /*and the other four members*/) {
        this.httpClient = httpClient;
        // assigning the other members
    }

    protected HttpResponse<String> sendRequest(HttpRequest httpRequest, String restPath) {
        // send the request, handle exceptions and return the response
    }

    protected <T> T deserializeJson(String json, Class<T> type) {
        // call this.gson.fromJson(json, type), handle the JsonSyntaxException and return the result
    }
}

class EntityAController extends BaseController {
    public EntityAController(/* members of BaseController */) {
        super(/* the five parameters */);
    }

    void createEntityA(EntityA entity) {
        // translate entity into a corresponding entity of another system
        // pack this external entity into an HttpRequest
        this.sendRequest(httpRequest, "/externalEntity1");
    }
}

class EntityBController extends BaseController {
    public EntityBController(/* members of BaseController */) {
        super(/* the five parameters */);
    }

    void createEntityB(EntityB entity) {
        // translate entity into a corresponding entity of another system
        // pack this external entity into an HttpRequest
        this.sendRequest(httpRequest, "/externalEntity2");

        for (EntityBPart part : entity.parts()) {
            // translate the parts
            this.sendRequest(httpRequest, "/externalEntity2/part");
        }
    }
}

class Connector {
    protected final EntityAController entityAController;
    protected final EntityBController entityBController;

    public Connector(Map<String, String> options) {
        // create HttpClient and the four other members of BaseController out of the options

        this.entityAController = new EntityAController(httpClient/* and the rest */);
        this.entityBController = new EntityBController(httpClient/* and the rest */);
    }

    void createEntityA(EntityA entity) {
        this.entityAController.createEntityA(entity);
    }

    void createEntityB(EntityB entity) {
        this.entityBController.createEntityB(entity);
    }
}

The main question we are currently talking about is: is it legit to keep the instances of Gson, EntityAController and EntityBController in memory or not?

One party states that the multiple storage of stateless objects is more expensive for the JVM and the garbage collection than creating new instances at short term, which can be released directly after their calls. It would also make the code harder to read and maintain, because you always have to think about why the object is stored and reused.

The other party states that the above code is perfectly valid, since it saves object creation time. Especially in the case of EntityB which requires multiple requests, and creating a new Gson object for each request would be a waste of CPU. Memory management is not an issue since the JVM and the GC are made to handle objects. Keeping them is an equal use case to create/use/toss. And Spring (which is used to build some web services) does pretty much the same with its @Autowired members and @Repositorys, @Services et cetera.
And readability is not affected since this is simple OOP stuff. Every developer should be able to understand the code.

What do you think? Is one or the other considered best practice or bad practice? Are both approaches equal/valid? Does it depend on the invocation frequency?

catalog – Magento 2 Unit Testing with Helper dependency

I have a Helper class and a Model class, which looks like

<?php
# File: app/code/MagePsycho/Catalog/Helper/Data.php

namespace MagePsychoCatalogHelper;

use MagentoFrameworkAppHelperAbstractHelper;
use MagentoFrameworkAppHelperContext;
use MagentoStoreModelStoreManagerInterface;

class Data extends AbstractHelper
{
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    public function __construct(
        Context $context,
        StoreManagerInterface $storeManager
    ) {
        $this->storeManager = $storeManager;

        parent::__construct($context);
    }

    public function getUrl($route, $params = ())
    {
        return $this->_getUrl($route, $params);
    }

    // Other helper methods...
}

and

<?php
# File: app/code/MagePsycho/Catalog/Model/UrlResolver.php

namespace MagePsychoCatalogModel;

use MagentoCatalogApiProductRepositoryInterface;
use MagentoCatalogHelperProduct as ProductHelper;
use MagePsychoCatalogHelperData as Helper;

class UrlResolver
{
    /**
     * @var Helper
     */
    private $helper;

    /**
     * @var ProductHelper
     */
    private $productHelper;

    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    public function __construct(
        Helper $helper,
        ProductHelper $productHelper,
        ProductRepositoryInterface $productRepository
    ) {
        $this->helper = $helper;
        $this->productHelper = $productHelper;
        $this->productRepository = $productRepository;
    }

    public function getDefaultUrl($keyword)
    {
        return $this->helper->getUrl('catalogsearch/result', ('_secure' => true)) . '?q=' . $keyword;
    }

    public function getUrlBySku($sku)
    {
        $product = $this->productRepository->get($sku);
        if (!$product || !$product->getId()) {
            return false;
        }

        if (!$this->productHelper->canShow($product)) {
            return false;
        }

        return $product->getProductUrl();
    }
}

Now I want to test the getDefaultUrl() and getUrlBySku() methods of UrlResolver.
And I tried to test getDefaultUrl() as

<?php
# File: app/code/MagePsycho/Catalog/Test/Unit/Model/UrlResolverTest.php

namespace MagePsychoCatalogTestUnitModel;

use MagentoCatalogApiProductRepositoryInterface;
use MagentoCatalogHelperProduct as ProductHelper;
use MagePsychoCatalogHelperData as Helper;
use MagePsychoCatalogModelUrlResolver;
use PHPUnitFrameworkTestCase;
use MagentoFrameworkTestFrameworkUnitHelperObjectManager as ObjectManagerHelper;

class UrlResolverTest extends TestCase
{
    /**
     * @var UrlResolver
     */
    protected $model;

    public function setUp(): void
    {
        $objectManager = new ObjectManagerHelper($this);
        $productRepository = $this->getMockBuilder(ProductRepositoryInterface::class)
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();
        $productHelper = $this->getMockBuilder(ProductHelper::class)
            ->disableOriginalConstructor()
            ->getMock();

        $arguments = $objectManager->getConstructArguments(Helper::class);
        $helper = $objectManager->getObject(Helper::class, $arguments);
        //$helper = $this->createMock(Helper::class);

        $this->model = $objectManager->getObject(
            UrlResolver::class,
            (
                'helper' => $helper,
                'productHelper' => $productHelper,
                'productRepository' => $productRepository,
            )
        );
    }

    /**
     * @dataProvider defaultUrlDataProvider
     */
    public function testGetDefaultUrl($sku, $url)
    {
        $this->assertStringContainsString($url, $this->model->getDefaultUrl($sku));
    }

    public function defaultUrlDataProvider(): array
    {
        return (
            ('sku1', 'catalogsearch/result?q=sku1'),
            ('sku2', 'catalogsearch/result?q=sku2'),
        );
    }
}

But $this->model->getDefaultUrl($sku) always results in ?q=$sku without the URL part.
I feel that Helper dependency injection is not working properly.

Can you please let me know how should I test getDefaultUrl() and getUrlBySku() methods of UrlResolver?

java – Can DTO have helper method that operates on DTO fields?

I wonder where to add method that reads my dto WindowDto.getPath().getPoints() and based on this collections returns some value (that value will be needed in some different srevices in my app):

public class WindowDto{

    @JsonProperty("valid_from")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate validFrom;

    @JsonProperty("valid_to")
    @FutureOrPresent
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate validTo;

    @JsonProperty("type")
    private String type;

    @JsonProperty("path")
    @Valid
    private PathDto path;

    @Data
    public static class PathDto {
        @JsonProperty("points")
        private Set<PointDto> points;
    }

//maybe here my helper method
public Long getStoreId(){
//iterate over points and make some operations on this collection...
}

Is it good practice to add such helper method in DTO? Or maybe create some other static class like WindowDtoHelper?

Is it reliable to hire a dissertation helper online?

Yes, it is safe and highly reliable to hire dissertation help online. There is a massive advantage when you opt for hiring a tutor or online help for dissertation service. You get a 24/7 customer service option that will be with you until you are satisfied with the work. The experts writing your dissertation will provide you with a thoroughly researched paper that will fetch you nothing less than an A+ grade.

magento2 – Magento 2 Model file Const get in Helper

Magento 2 Model file Const get in Helper.

I want to this type :-

File Path :- GetSomeMojoCategoryLandingPageModelEntityAttributeSource

<?php

namespace GetSomeMojoCategoryLandingPageModelEntityAttributeSource;

use MagentoFrameworkOptionArrayInterface;

class Landingpageproducts extends MagentoEavModelEntityAttributeSourceBoolean implements ArrayInterface
{

    const VALUE_NO = 'lpage_no';
    const VALUE_NEW = 'lpage_new';
    const VALUE_FEATURED = 'lpage_featured';
    const VALUE_SALE = 'lpage_sale';

    protected $_options;

    public function getAllOptions()
    {
        return (
            ('value' => self::VALUE_NO, 'label' => __('No')),
            ('value' => self::VALUE_NEW, 'label' => __('New Products')),
            ('value' => self::VALUE_FEATURED, 'label' => __('Featured Products')),
            ('value' => self::VALUE_SALE, 'label' => __('Sale Products'))
        );
    }
?>

Above const value get in Helper file.

So Please Help me how to get const in helper.

THANKS.

magento2 – Override a helper using Plugin

I have been trying to use plugin to override MagentoSalesHelperReorder.php but I am not sure how and have been stuck with this problem. Basically I am trying to override the function in this helper file. I have added a comment inside the code what I would like to change.

/**
     * Check is it possible to reorder
     *
     * @param int $orderId
     * @return bool
     */
    public function canReorder($orderId)
    {
        $order = $this->orderRepository->get($orderId);
        if (!$this->isAllowed($order->getStore())) {
            return false;
        }

        $currentOrder = $this->registry->registry('current_order');
        if ($this->customerSession->isLoggedIn() || isset($currentOrder)) {
            \WHAT I AM TRYING TO DO - canReorder() change to canReorderIgnoreSalable()
            return $order->canReorderIgnoreSalable();
        } else {
            return false;
        }
    }

How can I do this through plugin?

list manipulation – KenKen Puzzle Helper – Dropping order-less sequences

In the following example, I am generating all the variants of a $9 times 9$ KenKen puzzle that come in groups of three using addition that result in $18$.

  data = Select(Tuples(Range(9), 3), Plus @@ # == 18 &)

This generates

${{1,8,9},{1,9,8},{2,7,9},{2,8,8},{2,9,7},{3,6,9},{3,7,8},{3,8,7},{3,9,6},{4,5,9},{4,6,8},{4,7,7},{4,8,6},{4,9,5},{5,4,9},{5,5,8},{5,6,7},{5,7,6},{5,8,5},{5,9,4},{6,3,9},{6,4,8},{6,5,7},{6,6,6},{6,7,5},{6,8,4},{6,9,3},{7,2,9},{7,3,8},{7,4,7},{7,5,6},{7,6,5},{7,7,4},{7,8,3},{7,9,2},{8,1,9},{8,2,8},{8,3,7},{8,4,6},{8,5,5},{8,6,4},{8,7,3},{8,8,2},{8,9,1},{9,1,8},{9,2,7},{9,3,6},{9,4,5},{9,5,4},{9,6,3},{9,7,2},{9,8,1}}$

I can then do something to search for repeated cases without order

  Cases(data, {OrderlessPatternSequence(1, 8, 9)})

This generates (I want to delete all those after $198$ from data, but to do it for each unique set of three digits).

$${{1,8,9},{1,9,8},{8,1,9},{8,9,1},{9,1,8},{9,8,1}}$$

This approach has two drawbacks, I had to know the sequence to test for, then I can use that to drop all the repeats from data. I would have to repeat this for the next unique sequence.

Is there a simple way to create

 data2 = some_fancy_command(data)

It produces data2 (note – I don’t care about the commas either), which only has unique 3-digit numbers regardless of order

$${{189},{279},{288}},{369},{378}}… $$

What is the easiest way to do that?

Note that I am familiar with https://community.wolfram.com/groups/-/m/t/478684/, but only want a helper as opposed to a solver.

Aside: My goal is to have a tool that effectively duplicates https://homepages.bluffton.edu/~nesterd/apps/kenkenhelp.html as maybe a CDF of just an MMA Notebook where I enter all the cages, their type, the size of the puzzle and it provides hints on all the numbers that can go into the cage.

magento2 – Get userid of the admin logged in magento 2 helper

Below is a helper with a dependency and you can see within one of its function how the backend user id is read

<?php

namespace MbsBackendScreenHelper;

use MagentoFrameworkAppHelperAbstractHelper;
use MagentoFrameworkAppHelperContext;

class AdminUserReaderHelper extends AbstractHelper
{
    /**
     * @var MagentoBackendModelAuthSession
     */
    private $authSession;

    public function __construct(
        Context $context,
        MagentoBackendModelAuthSession $authSession
    ) {
        parent::__construct($context);
        $this->authSession = $authSession;
    }

    public function doSomethingWithMyAdminUserId()
    {
        ...

        $adminUserId = $this->authSession->getUser()->getId();
        
        ...
    }

}