Axios Post Method does not activate the Action in the BackEnd

I want to make an post request to my BackEnd ASP.NET Core Web API from my React JS FrontEnd but when using @axios@ it is not triggered.

I followed some instructions from the internet regarding making an axios get/post request but it seemed not to work

handleRegistration = (event) => {     event.preventDefault();      const user = {         email: this.state.email,         firstName: this.state.firstName,         lastName: this.state.lastName,         password: this.state.password     };      axios.post('http://localhost:{somenumbershere}/api/values/5', { user })         .then(res => {             console.log(res);             console.log(res.data);         }) } 

I am creating a user and want to send him as an object to my Action method to the BackEnd but it never hits the breakpoint. As you see the url I am sending my obj to, the @api/values/5@ is an example route for sending to the backend actiom method. I have decorated the Action with HttpPost, but still nothing.

Generating Biased Random Values (Walker’s Alias Method)

Am simply wondering if I made any egregious mistakes while implementing the Alias Method as an IEnumerator<TElement>; would also like to know if there are any sorts of general improvements that can be made to the design of the class.

Usage:

var rng = Pcg32XshRr.New(0, 1); var generator = ProbabilisticEnumerator     .New(         elementWeights: new Dictionary<string, int> {             { "A", 1 },             { "B", 2 },             { "C", 4 }         },         randomNumberGenerator: rng     )     .Take(100000); var summary = generator     .GroupBy(item => item)     .Select(item => new {         Element = item.Key,         Count = item.Count(),     })     .OrderBy(item => item.Element);  foreach (var item in summary) {     Console.WriteLine($  "{item.Element} | {item.Count}"); } 

Code:

Nuget Package

Source Repository

/// <summary> /// Represents an enumerator that yields elements in accordance with the rules descibed by a probability table; relies on Michael D Vose's implementation of <a href="https://en.wikipedia.org/wiki/Alias_method">Walker's Alias Method.</a> /// </summary> /// <typeparam name="TElement">The type of elements encapsulated by the enumerator.</typeparam> /// <remarks> /// Derived from https://github.com/BlueRaja/Weighted-Item-Randomizer-for-C-Sharp. /// </remarks> public class ProbabilisticEnumerator<TElement> : IEnumerable<TElement>, IEnumerator<TElement> {     private readonly struct ElementMetadata     {         public int ActualIndex { get; }         public int AliasedIndex { get; }         public int Threshold { get; }          public ElementMetadata(int actualIndex, int aliasedIndex, int biasAreaSize) {             ActualIndex = actualIndex;             AliasedIndex = aliasedIndex;             Threshold = biasAreaSize;         }     }      private readonly ElementMetadata[] m_elementMetadata;     private readonly TElement[] m_elements;     private readonly int m_heightPerRectangle;     private readonly IUniformlyDistributedRandomNumberGenerator m_randomNumberGenerator;      /// <summary>     /// Gets the next random element.     /// </summary>     public TElement Current {         get {             var elementMetadata = m_elementMetadata;             var elements = m_elements;             var heightPerRectangle = m_heightPerRectangle;             var randomNumberGenerator = m_randomNumberGenerator;             var randomHeight = randomNumberGenerator.NextInt32(0, heightPerRectangle);             var randomMetadata = elementMetadata[randomNumberGenerator.NextInt32(0, (elementMetadata.Length - 1))];              return ((randomHeight <= randomMetadata.Threshold) ? elements[randomMetadata.ActualIndex] : elements[randomMetadata.AliasedIndex]);         }     }     /// <summary>     /// Gets the next random element.     /// </summary>     object IEnumerator.Current => Current;      /// <summary>     /// Initializes a new instance of the <see cref="ProbabilisticEnumerator{TElement}"/> class.     /// </summary>     /// <param name="elementWeights">The collection of element-to-weight pairs that defines the rules for the table.</param>     /// <param name="randomNumberGenerator">The source of random numbers that will be used to perform extract elements from the table.</param>     private ProbabilisticEnumerator(IReadOnlyDictionary<TElement, int> elementWeights, IUniformlyDistributedRandomNumberGenerator randomNumberGenerator) {         if (elementWeights.IsNull()) {             throw new ArgumentNullException(paramName: nameof(elementWeights));         }          var count = unchecked((ulong)elementWeights.Count);         var elements = new TElement[count];         var index = 0;         var totalWeight = 0UL;          foreach (var kvp in elementWeights) {             var element = kvp.Key;             var weight = kvp.Value;              if (0 > weight) {                 throw new ArgumentOutOfRangeException(actualValue: weight, message: "weight must be a positive integer", paramName: nameof(weight));             }              elements[index++] = element;             totalWeight += unchecked((ulong)weight);         }          var gcd = BitwiseHelpers.GreatestCommonDivisor(count, totalWeight);         var heightPerRectangle = checked((int)(totalWeight / gcd));         var weightMultiplier = checked((int)(count / gcd));          m_elementMetadata = InitializeMetadata(elementWeights, weightMultiplier, heightPerRectangle);         m_elements = elements;         m_heightPerRectangle = heightPerRectangle;         m_randomNumberGenerator = randomNumberGenerator;     }      /// <summary>     /// Releases all resources used by this <see cref="ProbabilisticEnumerator{TElement}"/> instance.     /// </summary>     public void Dispose() { }     /// <summary>     /// Returns an enumerator that yields a random element from the table.     /// </summary>     public IEnumerator<TElement> GetEnumerator() => this;     /// <summary>     /// Returns an enumerator that yields a random element from the table.     /// </summary>     IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();     /// <summary>     /// Returns true.     /// </summary>     public bool MoveNext() => true;     /// <summary>     /// Throws <see cref="NotSupportedException"/>.     /// </summary>     public void Reset() => new NotSupportedException();      private static ElementMetadata[] InitializeMetadata(IReadOnlyDictionary<TElement, int> elementWeights, int weightMultiplier, int heightPerRectangle) {         var count = elementWeights.Count;         var elementMetadata = new ElementMetadata[count];         var index = 0;         var stackLarge = new Stack<KeyValuePair<int, int>>();         var stackSmall = new Stack<KeyValuePair<int, int>>();          foreach (var kvp in elementWeights) {             var newWeight = (kvp.Value * weightMultiplier);              if (newWeight > heightPerRectangle) {                 stackLarge.Push(new KeyValuePair<int, int>(index++, newWeight));             }             else {                 stackSmall.Push(new KeyValuePair<int, int>(index++, newWeight));             }         }          while (0 < stackLarge.Count) {             var largeItem = stackLarge.Pop();             var smallItem = stackSmall.Pop();              largeItem = new KeyValuePair<int, int>(largeItem.Key, (largeItem.Value - (heightPerRectangle - smallItem.Value)));              if (largeItem.Value > heightPerRectangle) {                 stackLarge.Push(largeItem);             }             else {                 stackSmall.Push(largeItem);             }              elementMetadata[--count] = new ElementMetadata(smallItem.Key, largeItem.Key, smallItem.Value);         }          while (0 < stackSmall.Count) {             var smallItem = stackSmall.Pop();              elementMetadata[--count] = new ElementMetadata(smallItem.Key, smallItem.Key, heightPerRectangle);         }          return elementMetadata;     }      /// <summary>     /// Initializes a new instance of the <see cref="ProbabilisticEnumerator{TElement}"/> class.     /// </summary>     /// <param name="elementWeights">The collection of element-to-weight pairs that defines the rules for the table.</param>     /// <param name="randomNumberGenerator">The source of random numbers that will be used to perform extract elements from the table.</param>     public static ProbabilisticEnumerator<TElement> New(IReadOnlyDictionary<TElement, int> elementWeights, IUniformlyDistributedRandomNumberGenerator randomNumberGenerator) => new ProbabilisticEnumerator<TElement>(elementWeights, randomNumberGenerator); }  /// <summary> /// A collection of methods that directly or indirectly augment the <see cref="ProbabilisticEnumerator{TElement}"/> class. /// </summary> public static class ProbabilisticEnumerator {     /// <summary>     /// Initializes a new instance of the <see cref="ProbabilisticEnumerator{TElement}"/> class.     /// </summary>     /// <param name="elementWeights">The collection of element-to-weight pairs that defines the rules for the table.</param>     /// <param name="randomNumberGenerator">The source of random numbers that will be used to perform extract elements from the table.</param>     public static ProbabilisticEnumerator<TElement> New<TElement>(IReadOnlyDictionary<TElement, int> elementWeights, IUniformlyDistributedRandomNumberGenerator randomNumberGenerator) => ProbabilisticEnumerator<TElement>.New(elementWeights, randomNumberGenerator); } 

Is there a way to inherit a method that points to a class’ own private variable?

I am trying to have a child class inherit a method from some parent class that points to parent’s own private variable. I want the inherited method of the child to use the child’s own private variable. Is this possible, without redefining the whole method in the child class?

The code works fine if using public or protected (single underscore) variables. But our instructor insists on using private (double underscore) variables. We are only a couple of days into object-oriented programming so I do not really know what is the term I am looking for (sorry for that!).

I suspect I should only be using protected ones, but I want to comply with the instructions as much as possible.

class ClassA:     def __init__(self): self.__var = 10      def method1(self):         self.__var += 1     #method1 is intended to work on ClassA's __var         return self.__var   #The method will also return the processed value of ClassA's __var  class ClassB(ClassA):     def __init__(self): self.__var = 20      #ClassA's method1 is inherited by ClassB.      #But I want this method1 to use ClassB's __var   ObjectA = ClassA() ObjectB = ClassB()  print(ObjectA.method1()) #Will output 11 print(ObjectB.method1()) #Will raise an AttributeError, still looks for __var of ClassA 

Above is just a demonstration of what I intend to achieve.

When using public or protected variables, I will have an output of 11 and 21.
When using private variables however, I will have an 11 and an error.

I want ClassB‘s method1 to use ClassB‘s __var (_ClassB__var).

I could get ClassB to have a variable named _ClassA__var and set it to 20, and it does work, but that is kind of messy IMO.

Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response

Boa noite Guy’s!

Estou enfrentando um problema quando tento fazer uma requisição do tipo PATCH para meu servidor escrito com o framework ExpressJS. As requisições usando GET, POST e DELETE funcionam normalmente. As requisições vem de uma aplicação escrita usando Angular.

Este é o erro que estou recebendo:

Access to XMLHttpRequest at 'http://localhost:3000/events/61' from origin 'http://localhost:4200' has been blocked by CORS policy: Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response. 

Ja tentei configurar os Headers usando o seguinte codigo:

app.use(function(req, res, next) {   req.header('Access-Control-Allow-Origin', '*');   req.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS,PATCH');   req.header('Access-Control-Allow-Headers', 'Content-Type');   next(); }); 

Ja tentei importando o modulo Cors:

const cors = require('cors');  

Nenhuma dessas tentativas resolveu meu problema. O que poderia ser?

Att. Jeiferson

Efficient method to load/get and assign multiple custom attributes from quote item?

Is there a more efficient way to load and assign quote item custom attributes?

This is code in my Observer:

public function MyFunction(Varien_Event_Observer $  observer) { $  QuoteObject = Mage::getSingleton('checkout/session')->getQuote();         foreach ($  QuoteObject->getAllVisibleItems() as $  item) {             $  custom_attr1 = $  item->getData('custom1');             $  custom_attr2 = $  item->getData('custom2');             $  custom_attr3 = $  item->getData('custom3');             $  custom_attr4 = $  item->getData('custom4');             $  custom_attr5 = $  item->getData('custom5');            //do other stuff here         }   //do some other stuff here } 

How can I solve $T(n) = 2T(\sqrt{n-1} + 2) + 1$ recurrence using tree method?

The recurrence I have is

$ T(n) = 2T(\sqrt{n-1} + 2) + 1$

I don’t know how to solve it. I didn’t find much on the internet with square roots in recurrences especially with constants inside of it. I’m supposed to find the height of the tree but I have no idea how.

I need to solve this recurrence only using trees. And I can’t find anything about solving recurrences with trees and square roots as parameters.

What is an efficient method to convert Windows MS Access database files, code, forms, etc. to Mac FileMaker Pro

As much as possible, I need to convert Windows Access forms (entry screens, reports), tables and code to FileMaker Pro. The databases need to be brought over to Mac from an older Windows computer and updated going forward.

Note: A similar question was asked many years back with most recent updates in 2014. As much time has passed, I am checking for possible new information. How to port an Access database to the Mac?

Unit testing extension method adding view location expander


Introduction

I’m writing unit tests for an extension method I wrote. Its only purpose it is to wrap startup logic which extends ViewLocationExpanders list by an instance implementating IViewLocationExpander. ViewLocationExpanders is a property of RazorViewEngineOptions, which can be configured in application startup in ConfigureServices() method. I’m using XUnit 2.4.1.

Usage

Instead of:

services.Configure<RazorViewEngineOptions>(options => {     options.ViewLocationExpanders.Add(new ViewLocationExpander()); }); 

I can use:

services.AddViewLocationExpander(new ViewLocationExpander()); 

ViewLocationExpander

public class ViewLocationExpander : IViewLocationExpander {     public IEnumerable<string> ExpandViewLocations(         ViewLocationExpanderContext context,          IEnumerable<string> viewLocations)     {         if (context == null)         {             throw new ArgumentNullException(nameof(context));         }          if (viewLocations == null)         {             throw new ArgumentNullException(nameof(viewLocations));         }          /*             * Note:             * {0} = action name             * {1} = controller name             * {2} = area name             */          var newViewLocations = new string[]         {             // Example: '/Views/Home/_Partials/FooBar.cshtml'             "/Views/{1}/_Partials/{0}.cshtml",         };          // Add new locations *AFTER* MVC default locations.         return viewLocations.Union(newViewLocations);     }      public void PopulateValues(ViewLocationExpanderContext context)     {         context.Values["customviewlocation"] = nameof(ViewLocationExpander);     } } 

Extension method

public static IServiceCollection AddViewLocationExpander(     this IServiceCollection services,      IViewLocationExpander viewLocationExpander) {     if (services == null)     {         throw new ArgumentNullException(nameof(services));     }      if (viewLocationExpander == null)     {         throw new ArgumentNullException(nameof(viewLocationExpander));     }      return services.Configure<RazorViewEngineOptions>(options =>     {         options.ViewLocationExpanders.Add(viewLocationExpander);     }); } 

Unit tests

[Fact] public void ExtensionMethodAddsNewViewLocationExpander() {     // Arrange     var services = new ServiceCollection();     services.AddMvc();      // These two are required to active the RazorViewEngineOptions.     services.AddSingleton<IHostingEnvironment, HostingEnvironment>();     services.AddSingleton<ILoggerFactory, LoggerFactory>();      // Act     var serviceProvider = services.BuildServiceProvider();     var oldOptions = serviceProvider.GetRequiredService<IOptions<RazorViewEngineOptions>>().Value;     services.AddViewLocationExpander(new ViewLocationExpander());     serviceProvider = services.BuildServiceProvider();     var newOptions = serviceProvider.GetRequiredService<IOptions<RazorViewEngineOptions>>().Value;      // Assert     Assert.True(newOptions.ViewLocationExpanders.Count > oldOptions.ViewLocationExpanders.Count); } 

Questions

  1. Am I going beyond the scope of what unit testing should include? I’m afraid that my code is actually testing the basic functions of generic collections and/or aspects of ASP.NET Core.
  2. If my concern above is true, that should I write unit tests to this at all? How should it work?

Is it possible to throw compiler error when attempting to use an unimplemented method?

The backstory is long but the general idea is that I’m beginning an iterative refactoring process to replace a poorly designed data access layer with a new one under constraints from above. We can’t fix everything at once but need to slowly phase in the new changes.

The old DAL contains several classes each containing several data access methods. The new DAL must preserve the method signatures and return types of the old DAL, and the old DAL code must be retained through the refactor. In a way you could say that we’re implementing a repository pattern after the fact but also hard coding the dependencies on a method by method basis instead of injecting them at runtime.

A nice way to go about the refactor is with VS Quick Actions. I can easily extract an interface from each of the old classes through the designer and then auto-implement them for the new classes. This creates a new class with the same method signatures of the old class; however the new methods are initially just stubs that throw a NotImplementedException until they are filled with an implementation.

The trouble is that the NotImplementedException is only thrown at runtime whereas I really need it at compile time. Is there a pattern that can be used to allow us to stub out the new DAL methods but raise a compiler error if we attempt to use them before they are in fact implemented?

Magento : REST API integration with paypal payment method

We are using REST API for mobile app from magento 2. We are try to place order using paypal express checkout method. But we get error. Check detail bellow.

API call.

Call Type : PUT

API URL : https://example.com/index.php/rest/V1/carts/302/order

Request Body

{     "paymentMethod": {           "method": "paypal_express",           "additional_data": {                  "paypal_express_payment_payload": {                        "create_time":"2019-04-15T23:13:52Z",                        "id":"PAY-6RV70583SB702805EKEYSZ6Y",                        "intent":"sale",                        "state":"approved"                  }           }     } } 

Response of API call :

{ “message”: “Internal Error. Details are available in Magento log file. Report ID: webapi-5cb8df18c6197” }

Magento Error log

    [2019-04-18 20:33:28] main.CRITICAL: Report ID: webapi-5cb8df18c6197; Message: Notice: Array to string conversion in /vendor/magento/framework/Reflection/TypeProcessor.php on line 473  {"exception":"[object] (Exception(code: 0): Report ID: webapi-5cb8df18c6197; Message: Notice: Array to string conversion in /vendor/magento/framework/Reflection/TypeProcessor.php on line 473  at /vendor/magento/framework/Webapi/ErrorProcessor.php:206, Exception(code: 0): Notice: Array to string conversion in /vendor/magento/framework/Reflection/TypeProcessor.php on line 473 at /vendor/magento/framework/App/ErrorHandler.php:61)"} []