texts:
I have a function that creates a css transform property string
based on some global variables. This string can be copied later by a user, so I would prefer to keep the output short.

This is my code:

var createTransformation = () => {
        var final_transformation = "";
        if (x)
            final_transformation += "rotateX(" + x + "deg)";
        if (y)
            final_transformation += " rotateY(" + y + "deg)";
        if (z)
            final_transformation += " rotateZ(" + z + "deg)";
        if (scalex !== 1 || scaley !== 1)
            final_transformation += " scale(" + scalex + "," + scaley + ")";
        if (translatex !== 0 || translatey !== 0 || translatez !== 0) {
            if (translatex !== 0 && translatey == 0 && translatez == 0)
                final_transformation += " translateX(" + translatex + "px)";
            else if (translatey !== 0 && translatex == 0 && translatez == 0)
                final_transformation += " translateY(" + translatey + "px)";
            else if (translatez !== 0 && translatex == 0 && translatey == 0)
                final_transformation += " translateZ(" + translatez + "px)";
            else if (translatex == 0)
                final_transformation += " translateY(" + translatey + "px) translateZ(" + translatez + "px)";
            else if (translatez == 0)
                final_transformation += " translateX(" + translatex + "px) translateY(" + translatey + "px)";
            else if (translatey == 0)
                final_transformation += " translateX(" + translatex + "px) translateZ(" + translatez + "px)";
            else
                final_transformation += " translateX(" + translatex + "px) translateY(" + translatey + "px) translateZ(" + translatez + "px)";
        }
        //if scalex != 1 || scaley != 1
        //If the skew's sliders have been changed e.g, moved from 0 to 1 or from 0 to 100 add skew property
        if (skewX || skewY)
            final_transformation += " skew(" + skewX + "deg," + skewY + "deg)";
        return final_transformation;
    };

As you can see there are a lot of if statements. I was wondering, is there anything I can do to improve this code?


texts: C++ class for aligning objects on the stack

texts:
I wrote a short class which allocates objects on the stack and aligns them to a specific memory address. Alignment makes sense for some objects (i.e. some SIMD intrinsics require aligned data). I wrote this mostly as an exercise. Tests are included. If someone has time to skim over this: thanks in advance, I'm looking forward to learn from your comments!

Also I'd be curious if you would add more functionality, i.e. operator== etc.

Usage

  // Allocates an int object aligned to 8 bytes, initializes it with 4
  aligned<8, int> i8(4);
  // Get a pointer to the actual value with operator&
  int *pi8 = &i8;
  // Get the actual value with operator*
  assert(*i8 == 4);

Header file

#include <cstdint>

template<size_t Align, typename T>
class aligned
{
  public:
    using value_type = T;
    using aligned_type = aligned<Align, T>;

    constexpr aligned() : ptr_(nullptr) {
    }

    aligned(const aligned_type &other) {
      *ptr_ = *other.ptr_;
    }

    aligned(const aligned_type &&other) {
      *ptr_ = std::move(*other.ptr_);
    }

    aligned_type &operator=(const aligned_type &other) {
      *ptr_ = *other.ptr_;
      return *this;
    }

    template<typename... Args>
    aligned(Args&&... args) {
      ptr_ = aligned_position();
      new (ptr_) T(std::forward<Args>(args)...);
    }

    ~aligned() {
      ptr_->~T();
    }

    T *get() const {
      return ptr_;
    }

    T *operator&() const {
      return get();
    }

    T operator*() const {
      return *ptr_;
    }

  private:
    T *aligned_position() {
      uint8_t *p = &storage_[0];
      while (reinterpret_cast<unsigned long>(p) % Align != 0)
        p++;
      return reinterpret_cast<T *>(p);
    }

    uint8_t storage_[Align - 1 + sizeof(T)];
    T *ptr_;
};

Tests

The main function has a few the tests. You can use operator& to get a pointer to the (aligned) object, or operator* to get a reference.

#include <cassert>
#include <utility>

int
main(int argc, const char *argv[])
{
  aligned<16, char> a;
  assert(&a == nullptr);

  aligned<8, int> i8(4);
  int *pi8 = &i8;
  assert(reinterpret_cast<unsigned long>(pi8) % 8 == 0);
  assert(*i8 == 4);

  aligned<7, double> d7(12.123);
  double *pd7 = &d7;
  assert(reinterpret_cast<unsigned long>(pd7) % 7 == 0);
  assert(*d7 == 12.123);

  using P = std::pair<int, int>;
  aligned<13, P> p13({1, 2}); // testing a more complex object
  P *pp13 = &p13;
  assert(reinterpret_cast<unsigned long>(pp13) % 13 == 0);
  assert(*p13 == std::make_pair(1, 2));
  return 0;
}

I use the GNU g++ compiler, version 5.4.0.


texts: Decoding indeterminate types using JSON Decoder

texts:
I'm working with a REST service that responds with indeterminate types. In particular, it can respond with a String, a correct payload (T: Decodable) or an error payload (PayloadError).
In order to cope with this type of requirement I've ended up with the following solution:
do {
    let decoder = JSONDecoder()
    let either = try decoder.decode(Either<T, PayloadError>.self, from: data)
    switch either {
        case .left(let value):
            completion(.success(value))
        case .right(let payloadError):
            completion(.failure(.generic)))
    }
} catch {
    if let value = String(data: data, encoding: .utf8) as? T {
        completion(.success(value))
    } else {
        completion(.failure(.generic))
    }
}

where Either is defined as:
enum Either<T, U> {
    case left(T)
    case right(U)
}

extension Either: Decodable where T: Decodable, U: Decodable {
    init(from decoder: Decoder) throws {
        if let value = try? T(from: decoder) {
            self = .left(value)
        } else if let value = try? U(from: decoder) {
            self = .right(value)
        } else {
            let context = DecodingError.Context(
                codingPath: decoder.codingPath,
                debugDescription: "Cannot decode \(T.self) or \(U.self)"
            )
            throw DecodingError.dataCorrupted(context)
        }
    }
}

Do you think the code looks good or should I use a more elegant solution?
Update 01.11.2020
These are the possible use cases along side with concrete responses.
Use Case 1
The client calls API method /authenticate. The server can responds with an authentication token of type String or a payload error of type PayloadError (if the server responds with unauthorized, for example). The JSON used to decode PayloadError is something like:
{
    code: 1,
    message: "Error message here"
}

PayloadError is defined as:
struct PayloadError: Decodable {
    let code: Int
    let message: String
}

Use Case 2
The client calls any other method. For example, it can call /user that gives back the info for the current user (the auth token is passed along). A struct User: Decodable is decoded from the returned JSON. If there is an error, the server replies with a PayloadError.
Based on the above use cases, the server can respond with:

String
T: Decodable (like User)
PayloadError

What I don't like is the code in catch since its intent is not clear.


texts: Implementation of Non-Generic Stack in Java

texts:
I'm starting out to work on DS in Java for the first time and thought that some inputs will get me going to more data structures. I implemented a stack which is non-generic. I followed some of the posts and realized that the top pointer should not be at -1. I know this is a very basic implementation (probably the worst). The LIFO part is working well. I am looking for suggestions on what are some ways to improve this code other than making this to be Generic Stack.

Code:

import java.util.*;

//******************************* Stack Demo Class **********//

class StackDemo{
  int stackarray[] , top;

  // Constructor

  StackDemo(int size){
    stackarray = new int[size+1];
    top = 0;
    System.out.println("The size of stack array is "+ (stackarray.length-1));
  }

  // *********************PUSH******************************//

  void push(int ele){
    if(top == stackarray.length - 1){
      System.out.println("Stack Overflow");
    }
    else{
      top++;
      stackarray[top] = ele;
    }
  } // Push Method

  // *********************POP******************************//

  int pop(){
    int lastElement = 0;
    if(top == 0){
      System.out.println("Stack is Underflow");
    }
    else{
      lastElement = stackarray[top];
      top--;
    }
    return lastElement;
  }  // Pop Method

  // *********************DISPLAY******************************//

  void display(){
    if(top == 0){
      System.out.println("Nothing to Display");
    }
    for (int i = 1; i<=top ; i++){
      System.out.print(stackarray[i] +"\t");
    }
    System.out.println("");
  } // Display Method

}

// *****************************Main Class*******************//

public class Stacks{
  public static void main(String args[]){
    StackDemo sd = new StackDemo(10);
    Scanner s = new Scanner(System.in);
    while(true){
      System.out.println("Enter your choice : \n 1.Push \n 2.Pop \n 3.Display \n 4.Exit");
      int choice = s.nextInt();
      switch(choice){
        case 1:
          System.out.println("Enter an Element to push");
          int pushElement = s.nextInt();
          sd.push(pushElement);
          break;
        case 2:
          int popElement = sd.pop();
          System.out.println("Popped Element is "+popElement);
          break;
        case 3:
          sd.display();
          break;
        case 4:
          System.exit(0);
          break;
        default:
          System.out.println("Enter valid choice");
      }  // Switch Closing
    } // While Closing
  } // Main method
} // Main class


texts:
I have written this big function to do some formatting in my python code. Would you be able to suggest anyways to make this smaller ?

def disfun(String1,String2,String3):
        if String3 == "A" or String3 == "B":
            if String3 == "A":
                pass
            elif String3 == "B":
                print "#"*54

            print "##"," "*48,"##"
            print "##",'{0:^48}'.format(String2),"##"
            print "##",'{0:^48}'.format(String1),"##"
            print "##"," "*48,"##"
            print "#"*54

        elif String3 == "C":
            print "-"*40
            print "--",'{0:^34}'.format(String2),"--"
            print "-"*40

        elif String3 == 'D':
            String2 = ' * '.join(String2)
            print "#"*54
            print "##",'{0:^48}'.format(String2),"##"
            print "##",'{0:^48}'.format(String1),"##"
            print "#"*54

        elif String3 == 'E':
            print "*"*54
            print "**",'{0:^48}'.format(String2),"**"
            print "**",'{0:^48}'.format(String1),"**"
            print "*"*54


texts: Max Increase to Keep City Skyline in Java

texts:
In a 2-dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.

In the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.

What is the maximum total sum that the height of the buildings can be increased?

Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
  [2, 4, 5, 7],
  [9, 2, 6, 3],
  [0, 3, 1, 0] ]

The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]

The grid after increasing the height of buildings without affecting skylines is:

gridNew = [ [8, 4, 8, 7],
            [7, 4, 7, 7],
            [9, 4, 8, 7],
            [3, 3, 3, 3] ]

Notes:

1 < grid.length = grid[0].length <= 50.
All heights grid[i][j] are in the range [0, 100].
All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x
   1 x grid[i][j] rectangular prism.

My approach:

class Solution {
    public int maxIncreaseKeepingSkyline(int[][] grid) {

        int nrows = grid.length;
        int ncols = grid[0].length;

        int [] leftRig = new int[nrows];
        int [] topBot = new int[ncols];

        //Filling topBot
        for( int i = 0; i < ncols; i++ )
        {
               int max = Integer.MIN_VALUE;

                for( int j = 0; j < nrows; j++ )
               {
                   if( max <= grid[j][i] )
                       max = grid[j][i];
               }
            topBot[i] = max;
        }

        //Filling leftRig
        for( int k = 0; k < nrows; k++ )
        {
               int max = Integer.MIN_VALUE;

                for( int l = 0; l < ncols; l++ )
               {
                   if( max <= grid[k][l] )
                       max = grid[k][l];
               }
            leftRig[k] = max;
        }

        int count = 0;
        int min = 0;

        //Enumerating the minimum height to be added
        for( int i = 0; i < nrows; i++ )
        {
          for( int j = 0; j < ncols; j++ )
            {
                  min = Math.min(leftRig[i],topBot[j]);
                  count += min - grid[i][j];
            }
        }

        return count;
    }
}

Time complexity: O(n^2)

Space complexity: O(n)

Time complexity: O(n) Space complexity: O(n)

I have the following questions regarding the above code snippets:

1) How can I improve the time and space complexity of my code?

2) Is there a better way(lesser lines of code, better data structures) that can be used to improve the code?

3) Is there any better approach to solve this question?

Reference


texts: AsyncTask for subscribing to current location

texts:
I made the below CurrentLocationTask as a way of reducing code duplication, as my application currently has 2 different Activitys which both use GoogleApiClient and OnLocationChanged.

The task basically connects a GoogleApiClient, then uses a LocationRequest to subscribe to RequestLocationUpdates.

In the OnLocationChanged method, CurrentLocation is updated, and the PropertyChanged event is fired.

Because the PropertyChangedEventHandler is public, it can be subscribed to from the required Activity. So the task can be called from an Activity on which we need to get the user's current location.

Usage

OnCreate

Create a new CurrentLocationTask and Execute, passing in the current activity as context. Then subscribe to the PropertyChanged event with OnCurrentLocationChanged:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);

    // Subscribe to current location
    _currentLocationTask = new CurrentLocationTask();
    _currentLocationTask.Execute(this);
    _currentLocationTask.PropertyChanged += OnCurrentLocationChanged;
}

OnCurrentLocationChanged

We can get CurrentLocation from the CurrentLocationTask:

private void OnCurrentLocationChanged(object sender, PropertyChangedEventArgs e)
{
    _currentLocation = _currentLocationTask.CurrentLocation;
}

OnStop

In OnStop, Disconnect the GoogleApiClient:

protected override void OnStop()
{
    base.OnStop();
    _currentLocationTask.Client.Disconnect();
}

The code for the AsyncTask is below. Any recommendations are much appreciated.

I'm not sure if using AsyncTask is the best way of doing this, especially since I don't think very much of the code here is actually being called in RunInBackground.

CurrentLocationTask

using System.Linq;
using System.ComponentModel;
using Android.OS;
using Android.Gms.Common.Apis;
using Android.Gms.Common;
using Android.Gms.Location;
using Android.Locations;
using Android.Content;

namespace WeatherApp.Droid
{
    class CurrentLocationTask :
        AsyncTask<Context, int, Java.Lang.Void>,
        GoogleApiClient.IConnectionCallbacks,
        GoogleApiClient.IOnConnectionFailedListener,
        Android.Gms.Location.ILocationListener,
        INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public Location CurrentLocation { get; set; }
        public GoogleApiClient Client;

        private LocationRequest _locationRequest;
        private Context _context;

        // AsyncTask
        protected override Java.Lang.Void RunInBackground(params
            Context[] context)
        {
            _context = context.First();
            // Build the client and connect
            Client =
                new GoogleApiClient.Builder(_context)
                .AddApi(LocationServices.API)
                .AddConnectionCallbacks(this)
                .Build();

            Client.Connect();

            return null;
        }

        // API connection
        public void OnConnected(Bundle connectionHint)
        {
            _locationRequest = LocationRequest.Create();
            _locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
            _locationRequest.SetInterval(1000);

            LocationServices.FusedLocationApi.RequestLocationUpdates(
                Client, _locationRequest, this);
        }
        public void OnConnectionFailed(ConnectionResult result)
        {
            MessageBox.Show(_context, "Connection Failed");
        }
        public void OnConnectionSuspended(int cause)
        {
            MessageBox.Show(_context, "Connection Suspended");
        }

        // Location changed
        public void OnLocationChanged(Location location)
        {
            CurrentLocation = location;

            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs("CurrentLocation"));
        }
    }
}


texts: Return a string based on Type, Color and Position

texts:
I recently wrote a really long one-liner, it was really just for fun, but I would like to know if it's bad practice or not. Can you tell me?

Here's my full class, but it's about the ToString() method.

namespace HGroupBadge.Classes
{
    public class BadgeDetail : BadgePart
    {
        public DetailType Type { get; set; }

        public BadgeDetail(DetailType type, BadgeColor color, BadgePosition position)
        {
            Type = type;
            Color = color;
            Position = position;
        }

        public override string ToString()
            => ((int)Type > 99 ? "t" : "s")
            + ((int)Type > 99 ? ((int)Type).ToString().Remove(0, 1) : ((int)Type < 10 ? "0" + (int)Type : "" + (int)Type))
            + ((int)Color < 10 ? "0" + (int)Color : "" + (int)Color)
            + (int)Position;
    }
}

It has to return a string similar to s01137, when Type or Color are lower than 10, a leading 0 has to be added because the final string always has to end in 5 digits.  When Type is bigger than 99, the first digit has to be cut off. In the end, Position has to simply be added to the string.

DetailType, BadgeColor and BadgePosition are enums.


texts: Code allowed to test mail invitations by users (from another post) on an instance of Visual studio debugging

texts:
I am currently working on an application in ASP.Net MVC, with a SQL Server 2016 database and Entity Framework 6.

The application can process specific data and generate forms (in DOC format), and in some cases it sends emails to targeted people.

My problem is with this piece of code (The code set is further down):

#region Fix proxy proxy locally on URL
Var currentHost = "localhost: 57061";
Var newhost = $ "{GetIPAddressV4 ()}: 90";
Url = url.Replace (currentHost, newhost);
#endregion

What I learned from the explanation I was given was:

  This code allowed to test mail invitations by users (from another
  post) on an instance of Visual studio debugging.

  The purpose of this step is to modify the URL sent in the email so
  that the new URL points to the instance of Debug VS. To use this
  trick, it uses iisexpress-proxy.

I have an opinion on this code but I would like an expert feedback on this.

My questions:

Is this code clean?
Is it dangerous (reliability, safety)?
Can we replace it?

The code set is here:

 public class SendMailMgr
    {
        #region MailInvit

        public static void SendMailInvit(BaseViewModels model, string userId, string htmlInvit)
        {
            var usr = PersonalInfoDbMgr.GetByUserId(userId);

            if (usr != null)
            {
                var url = string.Format("{0}://{1}{2}",
               model.Request.Url.Scheme,
               model.Request.Url.Authority,
               model.Url.Action("FirstStep", "Account", new { id = usr.AspNetUser.Id }));

                #region Fix prob de proxy en local sur l'URL

                var currentHost = "localhost:57061";
                var newhost = $"{GetIPAddressV4()}:90";
                url = url.Replace(currentHost, newhost);

                #endregion Fix prob de proxy en local sur l'URL

                var mailT = BuildMailMgr.MailInvit(new Business.Tools.Mail.ViewModels.MailInvit()
                {
                    UrlInvit = url,
                    FirstName = usr.FirstName,
                    LastName = usr.LastName,
                    Profile = usr.Profile,
                    HtmlMessage = htmlInvit,
                });

                mailT.To = usr.Email;
                MailMgr.SendMail(mailT);
            }
            else
            {
                model.Feedback.AddError("SendMailInvit User Not find ", " SendMailInvit User Not find => UserId : " + userId);
            }
        }

        #endregion MailInvit

        public static string GetIPAddressV4()
        {
            var res = "";
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());

            for (int i = 0; i < ipHostInfo.AddressList.Length; i++)
            {
                IPAddress ipAddress = ipHostInfo.AddressList[i];
                var ip = ipAddress.ToString();
                if (ip.Length <= 12)
                {
                    res = ip;
                }
            }
            return res;
        }
    }


texts:
I've been maintaining a Rbac helper for some time now. My goal is to provide an easy way to tell the following:

When does an user have a role
What can a user do (with those roles)
Which users have which role in which resources

And I'm pretty happy with my result so far, I can do the following:

var rbac = new RbacSession();
rbac.AddPermission("owner", "Delete");
rbac.UserIsInRoleIf("mantainer", u => u.Identity.Name == "Bob");
rbac.AddUserRoleForTypeIf<string>("Teacher", (user, resource) => resource == "Hello world");

I have been told to get rid of my fluent interface because all of it was wrong.

And my thought was, well yeah... But hey, wouldn't it be really cool if I could support properties to check if a user has a role? If I did I could also support easy binding to WPF Applications. Here follows the implementation

public class RbacPrincipal : IPrincipal, IIdentity
{
    [Browsable(false)]
    public class CanDoAction
    {
        private readonly RbacPrincipal _principal;
        public CanDoAction(RbacPrincipal principal)
        {
            _principal = principal;
        }

        public bool this[string action]
        {
            get
            {
                return _principal._session.Query.IsUserAbleTo(_principal, action);
            }
        }

        public bool this[string action, object resource]
        {
            get
            {
                return _principal._session.Query.IsUserAbleTo(_principal, action, resource);
            }
        }
    }

    [Browsable(false)]
    public class IsUserInRole
    {
        private readonly RbacPrincipal _principal;

        public IsUserInRole(RbacPrincipal principal)
        {
            _principal = principal;
        }

        public bool this[string role]
        {
            get
            {
                return _principal._session.Query.IsUserInRole(_principal, role);
            }
        }

        public bool this[string role, object resource]
        {
            get
            {
                return _principal._session.Query.IsUserInRole(_principal, role, resource);
            }
        }
    }

    private readonly IPrincipal _principal;
    private readonly IRbacSession _session;
    public RbacPrincipal(IPrincipal principal, IRbacSession session)
    {
        _principal = principal;
        _session = session;
        CanDo = new CanDoAction(this);
        Is = new IsUserInRole(this);
    }

    public bool IsInRole(string role)
    {
        //check role on the decorated principal se we avoid stackoverflow
        return _session.Query.IsUserInRole(_principal, role);
    }

    public CanDoAction CanDo { get; private set; }
    public IsUserInRole Is { get; private set; }

    IIdentity IPrincipal.Identity { get { return _principal.Identity; } }
    public string Name { get { return _principal.Identity.Name; } }
    public string AuthenticationType { get { return _principal.Identity.AuthenticationType; } }
    public bool IsAuthenticated { get { return _principal.Identity.IsAuthenticated; } }
}

And an example of the usage of it

var owner = new RbacPrincipal(new Principal
{
    Roles = { "owner", "member", "user" }
}, rbac);
Assert.IsTrue(owner.Is["owner"]);
Assert.IsTrue(owner.Is["member"]);
Assert.IsTrue(owner.CanDo["Delete"]);

I leave the link to full test class on repo here

Now I have one limitation if I use bindings with this. The resources cannot be anything but strings, but at least, and most important I can let you check a role of a user with a binding Is[owner].

Is this it? Did I finally reach the "yayness"?


texts: Fastest way to change the HSV value of all pixels in a bitmap

texts:
I want to change all the pixels in an image to have the same value, in terms of the HSV colour space.

At the moment I'm running the following code:

private Bitmap changeVForAllPixels(Bitmap bitmap, float newV)
{
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int[] rgbs = new int[width * height];

    bitmap.getPixels(rgbs, 0, width, 0, 0, width, height);

    for(int rgbi = 0; rgbi < rgbs.length; rgbi++)
    {
        float[] hsv = new float[3];
        Color.colorToHSV(rgbs[rgbi], hsv);
        hsv[2] = newV;
        rgbs[rgbi] = Color.HSVToColor(hsv);
    }

    return Bitmap.createBitmap(rgbs, width, height, Bitmap.Config.ARGB_8888);
}

I would like to know if there is a faster way, as this is taking in the range of 30 seconds to process a 1920 x 1080 pixels image on an LG D802 phone. I'd like to get it down to the 1 second range, or to know if that's not possible.


texts: Finding if value exists in any column recursively

texts:
Our company uses an old version of JAXB so it does not allow generics. Other than that, I am using recursive calls because Rows can have subrows and I want to find out if any of the rows for the given column id i has any values.

I am interested to know if I got the recursion right.

private static boolean anyCellHasValue(CommonRowType row, int i) {

    CustomCellType cell = (CustomCellType)row.getCustomRow().getCell().get(i);

    if(!CELL_EMPTY.equals(cell.getType())) {
        return true ;
    }

    if (row.getChildren() != null && row.getChildren().getRowData() != null &&
        !row.getChildren().getRowData().isEmpty()) {
        for (int k = 0; k < row.getChildren().getRowData().size(); k++) {
            if(anyCellHasValue((CommonRowType) row.getChildren().getRowData().get(k), i)) {
                return true;
            }
        }
    }

    return false;
}


texts: Given an input list of words and a string, output every different set of words that can make up that string

texts:
Problem:

  Given an input list of words and a string, output every different set of words that you can find in the string from the given words. For example, input: word_list = ['dog', 'cats', 'sand', 'cat', 'and'], string = "catsanddog" output: [ ['cat', 'sand', 'dog'], ['cats', 'and', 'dog'] ]

My pseudo code is:

Create an array current_matches.
Loop through each character in the string, keeping track of the sub-word up to that character, and the current character.
Add the current character to all the matches in current_matches so that they can keep track of successive matches.
See if the sub-word is in the array. If it is, add that word to the current_matches array.
After the loop is done, check if any of the matches add up to the original string.

Perhaps I'm missing a key concept that would make this easier? I read about Tries 2 weeks ago, and it sounds like that could be it, but I'm not familiar enough with them.

def string_legos(list_of_words, string)
  # Make hash out of the words so that lookup is faster
  # when we scan the list of words to see if one exists
  dictionary = {}
  list_of_words.each do |word|
    dictionary[word] = true
  end
  current_matches = []
  string.length.times do |i|
    character = string[i]
    word = string[0..i]
    current_matches.each do |match|
      match.track(character)
    end
    if dictionary[word]
      current_matches << Match.new(word, dictionary)
    end
  end

  current_matches.select do |match|
    match.equals?(string)
  end
  current_matches
end

class Match
  def initialize(word, dictionary)
    @dictionary = dictionary.clone
    @words = []
    @current_string = ''
    @words << word
  end

  def track(character)
    @current_string << character
    if word_unused?
      mark_word_as_used
      @words << @current_string
      @current_string = ''
    end
  end

  def word_unused?
    @dictionary[@current_string]
  end

  def mark_word_as_used
    @dictionary[@current_string] = false
  end

  def equals?(string)
    @words.join == string
  end
end

Are there any glaring issues / optimizations you can see with this?


texts:
This is a Leetcode problem -

  On an \$N\$ x \$N\$ board, the numbers from 1 to N * N are
  written boustrophedonically (starting from the bottom left of the
  board), and alternating direction each row.  For example, for a 6 x 6
  board, the numbers are written as follows -

  You start on square 1 of the board (which is always in the last row
  and first column).  Each move, starting from square x, consists of
  the following -

  You choose a destination square S with number x+1, x+2, x+3, x+4, x+5, or x+6, provided this number is <= N * N.

  (This choice simulates the result of a standard 6-sided die roll, ie., there are always at most 6 destinations, regardless of
  the size of the board.)

  If S has a snake or ladder, you move to the destination of that snake or ladder.  Otherwise, you move to S.

  A board square on row r and column c has a "snake or ladder" if
  board[r][c] != -1. The destination of that snake or ladder is
  board[r][c].

  Note that you only take a snake or ladder at most once per move; if
  the destination to a snake or ladder is the start of another snake or
  ladder, you do not continue moving. (For example, if the board is
  [[4,-1],[-1,3]], and on the first move your destination square is
  2, then you finish your first move at 3 because you do not
  continue moving to 4.)

  Return the least number of moves required to reach square N * N. If
  it is not possible, return -1.

  Note -

  2 <= board.length = board[0].length <= 20
  board[i][j] is between 1 and N * N or is equal to -1.
  The board square with number 1 has no snake or ladder.
  The board square with number N * N has no snake or ladder.

  Example 1 -

Input: [
[-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1],
[-1,35,-1,-1,13,-1],
[-1,-1,-1,-1,-1,-1],
[-1,15,-1,-1,-1,-1]]

Output: 4

"""
Explanation -

At the beginning, you start at square 1 [at row 5, column 0].

You decide to move to square 2, and must take the ladder to square 15.

You then decide to move to square 17 (row 3, column 5), and must take the snake to square 13.

You then decide to move to square 14, and must take the ladder to square 35.

You then decide to move to square 36, ending the game.

It can be shown that you need at least 4 moves to reach the N*N-th square, so the answer is 4.

"""

I would like to have a performance review of my solution and would also like to know whether I could make it more efficient.

Here is my solution to this challenge (in Python 3) -

# Uses Breadth First Search (BFS)

def snakes_and_ladders(board):

    """
    :type board: List[List[int]]
    :rtype: int
    """

    board_2 = [0]
    rows, cols = len(board), len(board[0])
    row = rows - 1

    while row >= 0:
        for col in range(cols):
            board_2.append(board[row][col])
        row -= 1
        if row >= 0:
            for col in range(cols - 1, -1, -1):
                board_2.append(board[row][col])
            row -= 1

    visited = [0 for i in range(len(board_2))]
    stack = collections.deque()
    stack.append([1,0])
    while stack:
        current_index, current_dist = stack.popleft()
        for i in range(1,7):
            next_index = min(rows * cols, current_index + i)
            if board_2[next_index] != -1:
                next_index = board_2[next_index]
            if next_index == rows * cols:
                return current_dist + 1
            if visited[next_index] == 0:
                visited[next_index] = 1
                stack.append([next_index, current_dist + 1])

    return -1


texts: Counting numbers that have an even number of digits

texts:
I solved this problem: given an array/vector of numbers, return how many of them contain an even number of digits.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 10^5

Please review the code:
impl Solution {
    pub fn find_numbers(nums: Vec<i32>) -> i32 {
        let mut count = 0;
        let mut len = 0;

        if nums.len() <= 500 {
            for num in nums {
                let digit: Vec<_> = num
                    .to_string()
                    .chars()
                    .map(|d| d.to_digit(10).unwrap())
                    .collect();

                len = digit.len();
                if num > 100000 {
                    panic!("Too much greater values are in vector");
                }
                if len % 2 == 0 {
                    count += 1;
                }
            }
        }
        count
    }
}

Are there better ways to apply the constraints and solve the problem?


texts:
Recently i wanted to test my Python knowledge so I'm taking some challenges. I came across a Rock Paper Scissor challenge and I wanted to make it with less code and reuse the same code over and over. The code below is what I have written so far and it works great. I just want to get your opinions: what can i do better?

rules = {
    'rock': {
        'scissor': 'smashes'
    },
    'paper': {
        'rock': 'packs'
    },
    'scissor': {
        'paper': 'cuts'
    }
}

player_one = input("P1 | Rock, Paper or Scissor: ").lower()
player_two = input("P2 | Rock, Paper or Scissor: ").lower()

def play(p1, p2):
    if p1 in rules:
        if p2 in rules[p1]:
            print("{} {} {}".format(p1, rules[p1][p2], p2))

    if p2 in rules:
        if p1 in rules[p2]:
            print("{} {} {}".format(p2, rules[p2][p1], p1))

    if p1 not in rules or p2 not in rules:
        print("Invalid input")

if __name__ == '__main__':
    play(player_one, player_two)


texts: Classes representing items in an RPG game

texts:
I wrote a little program in C# that contains classes representing Items in RPG game. I wanted to have access to all inherited classes parameters from list contains parent Item class instances, so this is my code:

using System;
using System.Collections.Generic;

public interface SpecialObject
{
    int GetIntParameter
    {
        get;
    }
}

public interface ElementalsObject
{
    int[] GetElementalsParameters
    {
        get;
    }
}

public class Item
{
    private string _name;
    private int _cost;

    public string name
    {
        get { return _name; }
    }

    public int cost
    {
        get { return _cost; }
    }

    public Item(string name, int cost)
    {
        _name = name;
        _cost = cost;
    }
}

public class Weapon : Item, SpecialObject, ElementalsObject
{
    private int dmgs;
    private int[] elementalsDmgs;

    public int GetIntParameter
    {
        get { return dmgs; }
    }

    public int[] GetElementalsParameters
    {
        get { return elementalsDmgs; }
    }

    public Weapon(string name, int cost, int dmgs, int[] elementalsDmgs = null) : base(name, cost)
    {
        if (elementalsDmgs != null)
            this.elementalsDmgs = elementalsDmgs;
        else
            this.elementalsDmgs = new int[] { 0, 0, 0, 0 };

        this.dmgs = dmgs;
    }
}

public class Armor : Item, SpecialObject, ElementalsObject
{
    private int armorPts;
    private int[] elementalsArmorPts;

    public int GetIntParameter
    {
        get { return armorPts; }
    }

    public int[] GetElementalsParameters
    {
        get { return elementalsArmorPts; }
    }

    public Armor(string name, int cost, int armorPts, int[] elementalsArmorPts = null) : base(name, cost)
    {
        if (elementalsArmorPts != null)
            this.elementalsArmorPts = elementalsArmorPts;
        else
            this.elementalsArmorPts = new int[] { 0, 0, 0, 0 };
        this.armorPts = armorPts;
    }
}

public class Food : Item, SpecialObject
{
    private int _hungryRestorePts;

    public int GetIntParameter
    {
        get { return _hungryRestorePts; }
    }

    public Food(string name, int cost, int hungryRestorePts) : base(name, cost)
    {
        _hungryRestorePts = hungryRestorePts;
    }
}

class Equipment
{
    public static void Test()
    {
        List<Item> items = new List<Item>();
        items.AddRange(new Item[] { new Item("Stone", 1),
                                    new Armor("Steel Helmet", 80, 10),
                                    new Weapon("Great Sword", 120, 80),
                                    new Armor("Storm Cuirass", 1000, 120, new int[4] {0, 0, 0, 60}),
                                    new Weapon("Fire Spear", 1400, 60, new int[4] {0, 80, 0, 0}),
                                    new Food("Apple", 5, 10) });

        string[] el = new string[4] { "Water", "Fire", "Earth", "Wind" };

        foreach(Item i in items)
        {
            Console.WriteLine("Name: " + i.name + ", Cost: " + i.cost);
            if(i is SpecialObject)
            {
                //SpecialObject so = i as SpecialObject;
                SpecialObject so = (SpecialObject)i;
                Console.WriteLine(" Damages/ArmorPts/HungryRestorePts: " + so.GetIntParameter);
            }

            if(i is ElementalsObject)
            {
                ElementalsObject eo = i as ElementalsObject;
                Console.WriteLine(" Elementals parameters: ");

                for (int e = 0; e < el.Length; e++)
                {
                    Console.WriteLine("  " + el[e] + ": " + eo.GetElementalsParameters[e] + ", ");
                }
            }
            Console.WriteLine();
        }
    }
}

What do you think about it? Is it good code? If no then how I can write it better? :)


texts: Performance is too low, online compiler wants a faster way to find all possible combinations of k numbers out of 1...n

texts:
I have to find a method (using backtracking) to list all possible combinations, in lexicographical order,of k numbers out of the interval [1,n].. duplicates are not allowed. i.e: input: 5 3output:1 2 31 2 41 2 5 1 3 41 3 51 4 5 2 3 42 3 52 4 53 4 5

I know using namespace std; is bad practice, but that's the way we've been taught to write code, we always use iostream library and sometimes cmath iomanip and string, so the point is that I don't have a lot of knowledge in C++.. All I would like is a faster method than the one that I implemented, and if you can, don't use advanced syntax.. I understand that "advanced" might mean different things for different people, but maybe the code bellow will give you an uderstanding of the level of C++ knowledge I have

#include <iostream>
using namespace std;
int sol[20], n , el_maxim;
void display()
{
    for (int i = 0; i < n; i++)
        cout << sol[i] << " ";
    cout << endl;
}
int okay()
{
    for (int i = 0; i < n - 1; i++)
        if (sol[i] >= sol[i + 1])
            return 0;
    return 1;
}
void bkt(int poz)
{
    if (poz == n)
    {
        okay();
        if (okay() == 1)
            display();
    }
    else
        for (int i = 1; i <= el_maxim; i++)
        {
            sol[poz] = i;
            bkt(poz + 1);
        }
}
int main()
{
    cin >> el_maxim >> n;
    bkt(0);
    return 0;
}


texts: Using common code inside a Higher Order Component

texts:
I have a common List in mind which looks something like this:

it has one remove button

one input in which user can enter the name of element and on clicking insert the element will be added in the list.

For this i have added HOC like this:

function ListHOC(Component, data, listName, placeholder) {
  return class extends React.Component {
    constructor() {
      super();
      this.state = { data, element: "" };
    }

    add = item => {
      const { data } = this.state;
      data.push(item);
      this.setState({ data });
    };

    remove = keyToRemove => {
      const { data } = this.state;
      const newData = data.filter(({ key }) => keyToRemove !== key);
      this.setState({ data: newData });
    };

    render() {
      const { data, element } = this.state;
      const updatedList = data.map(({ name, key }) => (

{name}

          <button onClick={() => this.remove(key)}>remove</button>

      ));
      return (
        <>

{listName}:

          <Component data={updatedList} {...this.props} />
          <input
            placeholder={placeholder}
            onChange={e => this.setState({ element: e.target.value })}
          />
          <button
            onClick={() => this.add({ name: element, key: data.length + 1 })}
          >
            insert
          </button>
        </>
      );
    }
  };
}

one thing i am not sure about is weather to use the input and button and listname inside HOC or not

link to codepen: https://codepen.io/saxenanihal95/pen/NWKVJOx?editors=1010


texts: Do-While loop in Python, with limit on the amount of 'do's

texts:
I'm in a location with poor Internet access. In order to ensure that a call to an external service succeeds, I am wrapping the call in a pseudo-do-while in Python. Additionally, I am limiting the call to running a maximum of three times:

def post_safe(url, params):

    done = 0
    max_tries = 3
    messages = []

    while done<max_tries:
        try:
            response = requests.post(url, data=params)
        except Exception as e:
            messages.append(e)
            time.sleep(1)
        else:
            done = max_tries+1
        done += 1

    if done==max_tries:
        output = "%s\n" % (datetime.now().strftime('%Y-%m-%d %H:%M'),)
        output+= "requests() failed 3 times:\n"
        for m in messages:
            output+= m+"\n"
        print(output)

        return False

    return True

I personally am not satisfied with the 'Pythoness' of this code. It looks inelegant, and I would have preferred to use the type bool for done but that would require a second variable to count the iterations.

Is there a cleaner way to achieve a do-while in Python while limiting the amount of iterations?


texts:
How can I make this matrix effect more like the matrix movie?

#include<stdlib.h>
#include<stdio.h>
int main()
{
srand((unsigned) time(0));
int i,j;
system("color 0a");

while(1)
{
    i = rand() % 2;
    j= rand() % 2;
    if(j)
    {
       printf("%d ", i);
    }
    else
    {
        printf(" %d", i);
    }

}
return 0;
}

Here is how it looks like:

Of course it is better if it was moving but that's all what I can show.

Also it takes a notable time to compile, is there anything wrong I'm doing?


texts:
I have the following program. I have 90 million domain names split between 87 files. I need to resolve the IP of all. Right now I feel like this is super slow.
import multiprocessing
import fileinput
import socket
from datetime import datetime

socket.setdefaulttimeout(2)

def worker(i):
    filename = (str(i).zfill(len(str(111))))
    buffer_array = []
    for line in fileinput.input(f"./data/{filename}"):
        domain = '.'.join( list( reversed( line.split('\t')[1].split('.') ) ) )
        try:
            ip_list = socket.gethostbyname(domain)
            buffer_array.append(ip_list)
            if(len(buffer_array) == 1000):
                with open(f"./parsed_data/{i}", "a+") as save_file:
                    save_file.write("\n".join(buffer_array))
                    buffer_array = []
                    print(f"{datetime.now()} -- WRITING: worker {i}")
                    save_file.close()

        except Exception as e:
            pass

    with open(f"./parsed_data/{i}", "a+") as save_file:
        save_file.write("\n".join(buffer_array))
        print(f"{datetime.now()} -- WRITING ***FINAL***: worker {i}")
        save_file.close()

if __name__ == '__main__':
    jobs = []
    for i in range(87):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

In node, I was able to do 1,000,000 on a 2017 macbook pro in about 12 hours without using workers. Right now this accomplished 39 million in 32 hours. My hope was I could make it do it's thing in 12 hours (1m per worker in in 12 hours) on a AWS T3aXL
Does anyone have a bit faster way of doing this?


texts: Saving a collection of WPF user control layout into an XPS document

texts:
I am making an application to save a layout of user control into an .xps document. But, the export doesn't seem completed if the data is too many. I've tried to encapsulate each part with DispatcherPriority.Loaded but it seems the data binding is horrifyingly take too long to be finished (I honestly don't know what is the problem to be exact).

How can I optimize the below code properly to wait for each process to be finished before moving on to the next one, so saving to XPS document will be properly loaded?

P.S. This doesn't happen if the data is not too large.

public class MyClass
{
    public static void CreatePortableFile(List<MyViewModelVM> myViewModels, string path)
    {
        List<MyViewV> views = new List<MyViewV>();
        List<FixedPage> fixedPages = new List<FixedPage>();
        List<PageContent> pageContents = new List<PageContent>();
        FixedDocument fixedDoc = new FixedDocument();

        Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
                foreach (MyViewModelVM item in myViewModels)
                {
                    views.Add(new MyViewV() { DataContext = item });
                }
                Console.WriteLine("Setting datacontext " + DateTime.Now.TimeOfDay);
            }), DispatcherPriority.Loaded);

        Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
                foreach (MyViewV item in views)
                {
                    FixedPage newFixedPage = new FixedPage();
                    newFixedPage.Children.Add(item);
                    fixedPages.Add(newFixedPage);
                }
                Console.WriteLine("Setting fixedpage " + DateTime.Now.TimeOfDay);
            }), DispatcherPriority.Loaded);

        Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
                foreach (FixedPage item in fixedPages)
                {
                    PageContent newPageContent = new PageContent();
                    ((System.Windows.Markup.IAddChild)newPageContent).AddChild(item);
                    pageContents.Add(newPageContent);
                }
                Console.WriteLine("Setting pagecontent " + DateTime.Now.TimeOfDay);
            }), DispatcherPriority.Loaded);

        Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
                foreach (PageContent item in pageContents)
                {
                    fixedDoc.Pages.Add(item);
                }
                Console.WriteLine("Setting fixeddoc " + DateTime.Now.TimeOfDay);
            }), DispatcherPriority.Loaded);

        Dispatcher.CurrentDispatcher.Invoke(new Action(() => WriteToXps(path, fixedDoc)), DispatcherPriority.Loaded);
    }

    private static void WriteToXps(string path, FixedDocument fixedDoc)
    {
        XpsDocument xpsDoc = new XpsDocument(path, FileAccess.Write);
        XpsDocumentWriter xWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
        xWriter.Write(fixedDoc);
        xpsDoc.Close();

        Console.WriteLine("Setting write " + DateTime.Now.TimeOfDay);
    }
}

Sample call:

MyClass.CreatePortableFile(listOfMyViewModels, path);

Console.Writeline result:

Setting datacontext 17:51:37.8885505
Setting fixedpage 17:51:37.8915518
Setting pagecontent 17:51:37.8935523
Setting fixeddoc 17:51:37.8945527
Setting write 17:51:40.1266807


texts: Container that holds objects of various types, and can be searched for an object convertible to a given type

texts:
I built a container that can hold objects of various types, and look up an object convertible to a given type.  I wrote something about my intended use-case here:

https://stackoverflow.com/questions/58562173/typesafe-way-to-provide-enriched-dependencies-to-derived-classes-in-c

Basically I want to be able to throw a bunch of dependencies onto a pile and then grab the exact version I want from calling code -- for instance, if I just need an IWidget, I can do

IWidget * widget = dependencies.get<IWidget *>();

but if the underlying widget is actually a FancyGreenWidget then I can do

FancyGreenWidget * widget = dependencies.get<FancyGreenWidget *>();

and if it's not fancy and green then I'll get a helpful runtime error during program initialization rather than a surprise segfault sometime while the program is running.

I'm not really familiar with C++17, but it seemed like I needed a bunch of C++17 features to implement my use-case.  I feel like someone who writes modern C++ on a daily basis can probably glance at this and tell me several things I'm doing wrong.  In particular I suspect there's a much cleaner way to write the visitor in the get<T>() method.

template<class... Types>
  class VariantContainer
  {
    private:

      std::vector<std::variant<Types...>> m_values;

    public:

      template<class T>
      void add(const T &t)
      {
        static_assert(std::disjunction_v<std::is_same<T, Types>...>);

        m_values.push_back(t);
      }

      template<class T>
      T get()
      {
        for(int i = 0; i < m_values.size(); i++)
        {
          std::optional<T> result = std::visit(
            [](auto&& arg) {
              using Targ = std::decay_t<decltype(arg)>;

              if constexpr(std::is_convertible_v<Targ, T>)
              {
                return std::optional<T>(static_cast<T>(arg));
              }
              else
              {
                return std::optional<T>();
              }
          },
          m_values[i]);

          if(result.has_value()) { return result.value(); }
        }

        std::string message = "Could not find member of type ";
        message += abi::__cxa_demangle(typeid(T).name(), 0, 0, nullptr);

        throw std::runtime_error(message);
      }
  };

Sample usage:

    VariantContainer<Base *, Derived1 *, Derived2 *> v;

    Derived2 d;

    v.add(&d);

    Base * b = v.get<Base *>(); // returns a pointer to d

    Derived1 * d1 = v.get<Derived1 *>(); // ERROR

    Derived2 * d2 = v.get<Derived2 *>(); // returns a pointer to d

I'm also in the market for a more descriptive name for this class if anyone has any ideas.


texts:
types = [
    { name: "Feature"}
    { name: "Enhancement"}
    { name: "Bug"}
    { name: "Spike"}
  ]

buildIndex = (source, property) ->
  array = []
  array[prop[property]] = prop for prop in source
  array

buildIndex types, 'name'

Result:

[Feature: Object, Enhancement: Object, Bug: Object, Spike: Object]
  Bug: Object
  Enhancement: Object
  Feature: Object
    name: "Feature"
  Spike: Object

This is my ugly code.  How to refactor this?  My problem is the buildIndex function.  Iyt works, but  it isn't elegant.


texts:
I made a 52 standard deck generator for practicing my C#. Just to let you know I am using the unity editor.
I would your feedback as to whether my code is good/bad or whatever you may desire.
using System;
using System.Collections.Generic;
using UnityEngine;

public class Standard52Deck {
    List<Card> deck = new List<Card>();

    enum Ranks {
        Ace,
        Two,
        Three,
        Four,
        Five,
        Six,
        Seven,
        Eight,
        Nine,
        Ten,
        Jack,
        Queen,
        King
    }

    enum Suits {
        Hearts,
        Spades,
        Clubs,
        Diamonds,
    }

    class Card {
        readonly Ranks rank;
        readonly Suits suit;

        public Card(Ranks rank, Suits suit) {
            this.rank = rank;
            this.suit = suit;
        }

        public override string ToString() {
            return $"{rank} of {suit}";
        }
    }

    IEnumerable<Card> GetSortedCardsBySuits() {
        var rankCount = Enum.GetValues(typeof(Ranks));
        var suitCount = Enum.GetValues(typeof(Suits));
        var deckCount = rankCount.Length * suitCount.Length;

        var index = 0;
        var rankIteration = 0;

        while (index < deckCount) {
            var rank = (Ranks)(index % 13);
            if (rank == 0 && index != 0) {
                rankIteration++;
            }
            var suit = (Suits)(rankIteration);

            index++;
            yield return new Card(rank, suit);
        }
    }

    void CreateSortedCards() {
        foreach (var card in GetSortedCardsBySuits()) {
            deck.Add(card);
        }
    }

    void Start() {
        CreateSortedCards();
    }
}


texts:
I have this task of modelling a system where given a group of users each can keep track of their expenses. The basic requirements are as followed:

To be able to give credit to an user.
Find all the transactions of a given user.
Filter out the transaction where either user is borrower or spender.

I have tried few things but I am not convinced at all.

const trxn = new Array();

class Transaction {
    constructor(amount, from, to) {
      this.timestamp = new Date();
      this.amount = amount;
      this.from = from;
      this.to   = to;
      trxn.push(this);
    }

    toString() {
      let dd = this.timestamp.getDate();
      let mm = this.timestamp.getMonth();
      let yy = this.timestamp.getFullYear();
      return `[Transaction: ${dd}/${mm}/${yy}] ${this.from} Gives ${this.amount} to ${this.to}`;
    }
}

class Person {
    constructor(name) {
      this.name = name;
      this._transactions = [];
    }

    transfer(amount, to) {
      let t = new Transaction(amount, this, to);
      this._transactions.push(t);
    }

    transactions() {
      return this._transactions;
    }

    toString() {
      return `${this.name.charAt(0).toUpperCase() + this.name.slice(1)}`;
    }
}

function history(transactions, user) {
  return transactions.filter((t) => {
    return t.to.name === user.name || t.from.name === user.name;
  });
}

let amy = new Person('amy');
let foo = new Person('foo');
amy.transfer(500, foo);
amy.transfer(500, foo);
foo.transfer(200, amy);

for (let t of amy.transactions()) {
  console.log('Transaction by AMY');
  console.log(t);
}

for (let f of foo.transactions()) {
  console.log('Transaction by FOO');
  console.log(f);
}

console.log('Transaction history');
console.log(history(trxn, amy));

Output of the above logic:

Transaction by AMY
[Transaction: 22/10/2016] Amy Gives 500 to Foo
Transaction by AMY
[Transaction: 22/10/2016] Amy Gives 500 to Foo
Transaction by FOO
[Transaction: 22/10/2016] Foo Gives 200 to Amy
Transaction history
[Transaction: 22/10/2016] Amy Gives 500 to Foo,
[Transaction: 22/10/2016] Amy Gives 500 to Foo,
[Transaction: 22/10/2016] Foo Gives 200 to Amy

How can I make my code more flexible and robust following the OOP practices?


texts:
I realize it could be argued that it is an overkill to create a ValueObject for such a simple type. I am just trying to make sure that I understand the principles of overriding/overloading these methods correctly. I would be grateful for some critical feedback. Specifically:

Are all the methods implemented correctly?
Have I compared the date of births correctly i.e. if (candidate.AddYears(21).Date > DateTime.Now.Date) assuming that I am using the western idea of age.

Please note that with regards to naming conventions; I have used what is advised here

public sealed class DateOfBirth
    {
        private readonly DateTime _value;
        public DateOfBirth(DateTime value)
        {
            if (value.TimeOfDay.TotalSeconds > 0)
                throw new ArgumentException("Date of birth cannot contain a time.", "DateOfBirth");
            if (IsValid(value) == true)
            {
                _value = value;
            }
        }

        public DateOfBirth(int year, int month, int day)
        {
            var value = new DateTime(year, month, day);
            if (IsValid(value)==true)
            {
                _value = value;
            }
        }

        public static bool IsValid(DateTime candidate)
        {
            if (candidate.AddYears(21).Date > DateTime.Now.Date)
                throw new ArgumentException("Age must be greater than 21.", "DateOfBirth");
            return true;
        }

        public DateTime Value
        {
            get
            {
                return _value;
            }
        }

    public override bool Equals(object obj)
        {
            return Equals(obj as DateOfBirth);
        }

        public override int GetHashCode()
        {
            return _value.GetHashCode();
        }

        public static implicit operator DateTime(DateOfBirth dateOfBirth)
        {
            return dateOfBirth._value;
        }

        public static bool operator ==(DateOfBirth dateOfBirth1, DateOfBirth dateOfBirth2)
        {
            if (!ReferenceEquals(dateOfBirth1, null) &&
                ReferenceEquals(dateOfBirth2, null))
            {
                return false;
            }
            if (ReferenceEquals(dateOfBirth1, null) &&
                 !ReferenceEquals(dateOfBirth2, null))
            {
                return false;
            }
            if (ReferenceEquals(dateOfBirth1, null) &&
                 ReferenceEquals(dateOfBirth2, null))
            {
                return true;
            }
            return dateOfBirth1.Equals(dateOfBirth2);
        }

        public static bool operator !=(DateOfBirth dateOfBirth1, DateOfBirth dateOfBirth2)
        {
            return !(dateOfBirth1 == dateOfBirth2);
        }

        public bool Equals(DateOfBirth other)
        {
            if (ReferenceEquals(other, null))
                return false;
            return _value == other._value;
        }
    }

Note: this is a follow-up question to this one.


texts:
I've written C# code for solving a maze problem.  It works, but I want to optimize it so that it could give me all paths.  To solve the maze, I walk on the zeros and assumed that the final is reaching -3.

const int MAZE_SIZE = 6;
static int[] allowed_move_row = { 0, -1, 0, 1 };
static int[] allowed_move_col = { 1, 0, -1, 0 };
const int MAX_ALLOWED_MOVES = 4;
static int[,] Optmaze = new int[MAZE_SIZE, MAZE_SIZE];
static int[,] maze  = new int[MAZE_SIZE, MAZE_SIZE] {
                       { -2 , 0  ,  0   , 0  ,  0  ,  -1 },
                       { -1 , 0  , -1   , 0  , -1  ,  0 } ,
                       { -1 , -1 , -1   , 0  ,  0  ,  0 } ,
                       { -1 , 0  , -1   , -1 ,  0  ,  -1 },
                       { -1 , -1 , -1   , 0  ,  0  ,  0 } ,
                       { -1 , 0  , -1   , -3 ,  0  ,  0 } };

static bool Solve(int previous_row, int previous_col, int next_step_no)
{
     for (int i = 0; i < MAX_ALLOWED_MOVES; i++)
     {
          int col = previous_col + allowed_move_col[i];
          int row = previous_row + allowed_move_row[i];
          if (col < 0 || col >= MAZE_SIZE)
              continue;
          if (row < 0 || row >= MAZE_SIZE)
              continue;

          if (maze[row, col] == -3)
              return true;

          if (maze[row, col] != 0)
              continue;

          maze[row, col] = next_step_no;

          if (Solve(row, col, next_step_no + 1))
              return true;

          else maze[row, col] = 0;
     }
            return false;
}

static void Main(string[] args)
{
    Print(maze);
    Console.WriteLine("-----------Solve-------------");
    if (Solve (0, 0, 1) )
        Print( maze);
    else
        Console.WriteLine("No Result");
}

static void Print(int[,] maze)
{
    for (int i = 0; i < maze.GetLength(0); i++)
    {
        for (int j = 0; j < maze.GetLength(1); j++)
        {
            Console.Write(" " + String.Format("{0,3}",maze[i, j]) + " ");
        }
        Console.WriteLine();
    }
}

Outputting:

       -2    0    0    0    0   -1
       -1    0   -1    0   -1    0
       -1   -1   -1    0    0    0
       -1    0   -1   -1    0   -1
       -1   -1   -1    0    0    0
       -1    0   -1   -3    0    0
       -----------Solve-------------
       -2    1    2    3    0   -1
       -1    0   -1    4   -1    0
       -1   -1   -1    5    6    0
       -1    0   -1   -1    7   -1
       -1   -1   -1    0    8    9
       -1    0   -1   -3   11   10


texts:
I'm taking a sentence and determining whether or not it is a palindrome. I'm doing this while learning about stacks.

Is there a way I can use pointers instead of char array 'sent' so that the number of input characters need not be constrained to 20 in the following code?
The code is working fine, but should there be any improvements in terms of performance or anything else?
Is there anything important about pointers I should remember while using stacks, like initializing it to NULL?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct node
{
    char data;
    struct node *link;
}StackNode;

void insertData(StackNode **);
void push(StackNode **, char);
void checkData(StackNode **);
bool pop(StackNode **,char *);

char sent[20] = "";

void main()
{
   StackNode *stackTop;
   stackTop = NULL;
   insertData(&stackTop);
   checkData(&stackTop);
   printf("\n");
   return;
}

void insertData(StackNode **stackTop)
{
    char c;
    int len;

    printf("Enter the Sentence\n");
    while( ( ( c = getchar() ) != '\n'))
    {
        if( ( ( c>='a' &&c<='z') || (c>='A' && c<='Z')))
        {
            if((c>='A' && c<='Z'))
            {
                int rem;
                rem = c-'A';
                c='a' + rem;
            }
            push(stackTop,c);
            len = strlen(sent);
            sent[len++]=c;
            sent[len]='\0';
        }
    }
    printf("Letters are %s\n\n",sent);
}

void push(StackNode **stackTop,char c)
{
    StackNode *pNew;
    pNew = (StackNode*) malloc(sizeof(StackNode));
    if(!pNew)
    {
        printf("Error 100:Out of memory\n");
        exit(100);
    }
    pNew->data = c;
    pNew->link = *stackTop;
    *stackTop = pNew;
}

void checkData(StackNode **stackTop)
{
    char c;
    int i=0;
    while(pop(stackTop,&c))
    {
        if( c !=sent[i++])
        {
            printf("Not palindrome");
            return;
        }
    }
    printf("Palindrome");
}

bool pop(StackNode **stackTop,char *c)
{
    StackNode *pNew;
    pNew = *stackTop;
    if(pNew == NULL)
        return false;
    *c = pNew->data;
    *stackTop = pNew->link;
    printf("char poped %c\n",*c);
    free(pNew);
    return true;
}


texts: Recursive Fibonacci with Generic delegates

texts:
Here is a fast recursive Fibonacci-like for loop. How can it be more readable, and is it possible remove TArgs?

public static class Fibonacci
{
    public static BigInteger Calculate(BigInteger number)
    {
        var fibo = AnonRecursiveFiboFunc<BigInteger>(
            func => (step, fibo1, fibo2) => step == number
            ? fibo2
            : func(++step, fibo1 + fibo2, fibo1));
        return fibo(0, 1, 0);
    }

    delegate Func<TArg1, TArg2, TArg3, TArg4>
        Recursive<TArg1, TArg2, TArg3, TArg4>(
        Recursive<TArg1, TArg2, TArg3, TArg4> r);

    private static Func<TArg, TArg, TArg, TArg>
        AnonRecursiveFiboFunc<TArg>(Func<Func<TArg, TArg, TArg, TArg>,
                                         Func<TArg, TArg, TArg, TArg>> function)
    {
        Recursive<TArg, TArg, TArg, TArg> recursive =
            rec => (step, fibo1, fibo2) =>
                function(rec(rec))(step, fibo1, fibo2);
        return recursive(recursive);
    }
}


texts: Recognizing number representation (and convert to decimal) from the base prefixes

texts:
Here is what appears to be a fairly easy problem:

  Write a program that prompts the user to enter several integers in any
  combination of octal, decimal, or hexadecimal, using the 0 and
  0x base prefixes; interprets the numbers correctly; and converts
  them to decimal form. Then your program should output the values in
  properly spaced columns like this:

0x4    hexadecimal    converts to     4      decimal
0123   octal          converts to     83      decimal
65     decimal        converts to     65      decimal

Here is a first (working) draft:

const string info ("This program recognizes multiple base prefixed numbers  dec:none, hex:0x, oct:0\nand converts them into decimals.\n");
const string prompt ("Please enter numbers with random base prefixes.\n>>");

const char octprefix ('0');
const char hexprefixLower ('x');
const char hexprefixUpper ('X');
const int inputLoop = 2;

int main(){
try{
    cout << info;

    string num;
    vector<string> inputNumbers;

    int numDecimals(0);
    vector <int> inputDecimals;

    for (int i=0; i < inputLoop; i++){
        // get number with prefix
        cout << prompt;
        cin >> num;
        inputNumbers.push_back(num);

        // return number (# of characters) back to cin stream for reinterpretation
        for (int i=0; i < num.length(); i++) cin.unget();

        // unset default flags so that prefixes are considered
        // and numbers with different bases converted directly to decimals
        cin.unsetf(ios::dec | ios::oct | ios::hex);
        cin >> numDecimals;
        inputDecimals.push_back(numDecimals);
    }

    // discern base from prefix
    // checks first two characters of every vector element to determine base prefix
    for (int i=0; i < inputNumbers.size(); i++){
        if (inputNumbers[i][0] != octprefix){
            cout << inputNumbers[i] <<" decimal "<<" converts to "<< inputDecimals[i]  <<" decimal\n";
        }
        if (inputNumbers[1][0] == octprefix && (inputNumbers[1][1] != hexprefixLower && inputNumbers[1][1] != hexprefixUpper)){
                cout << inputNumbers[i] <<" octal "<<" converts to " << inputDecimals[i] <<" decimal\n";
        }
        if (inputNumbers[1][0] == octprefix && (inputNumbers[i][1] == hexprefixLower || inputNumbers[i][1] == hexprefixUpper)){
                cout << inputNumbers[i] <<" hexadecimal "<<" converts to " << inputDecimals[i] <<" decimal\n";
        }
    }

}catch(exception& e){
    cerr << e.what() << endl;
    getchar();
}

getchar();
getchar();
return 0;
}

Are there any existent, unknown to me, language facilities that can be used to convert string to number that contains base prefix (0x, 0, i.e. numbers like: 020, 0x16, etc); facilities that recognize number base representation?

I'm trying to make it look more modular and separate it in different functions with a single task (read input, prefix recognition algorithm, print result), any ideas are welcome!


texts:
I'm getting data from an API in JSON format. It's getting the resting heart rate of the user and inserting it into my database. It gets today's date as well as a couple days in the past and updates the database accordingly. The code below does work (although it's inserting a blank row for some reason). My question is, is there a better/more efficient way of writing this code?

Here is the array:

[activities-heart] => Array (
[0] => Array (
    [dateTime] => 2018-03-22
    [value] => Array (
        [customHeartRateZones] => Array ( )
        [heartRateZones] => Array (
            [0] => Array (
                [caloriesOut] => 1135.7736
                [max] => 85
                [min] => 30
                [minutes] => 814
                [name] => Out of Range
                )
            [1] => Array (
                [caloriesOut] => 1260.7179
                [max] => 119
                [min] => 85
                [minutes] => 289
                [name] => Fat Burn
                )
            [2] => Array (
                [caloriesOut] => 690.64515
                [max] => 145
                [min] => 119
                [minutes] => 90
                [name] => Cardio
                )
            [3] => Array (
                [caloriesOut] => 0
                [max] => 220
                [min] => 145
                [minutes] => 0
                [name] => Peak
                )
            )
        [restingHeartRate] => 65
        )
    )
[1] => Array (
    [dateTime] => 2018-03-23
    [value] => Array (
        [customHeartRateZones] => Array ( )
        [heartRateZones] => Array (
            [0] => Array (
                [caloriesOut] => 1512.00346
                [max] => 85
                [min] => 30
                [minutes] => 1113
                [name] => Out of Range
                )
            [1] => Array (
                [caloriesOut] => 1315.59604
                [max] => 119
                [min] => 85
                [minutes] => 280
                [name] => Fat Burn
                )
            [2] => Array (
                [caloriesOut] => 98.14618
                [max] => 145
                [min] => 119
                [minutes] => 13
                [name] => Cardio
                )
            [3] => Array (
                [caloriesOut] => 0
                [max] => 220
                [min] => 145
                [minutes] => 0
                [name] => Peak
                )
            )
        [restingHeartRate] => 64
        )
    )
)

And here is the relevant code to process it:

$obj = new RecursiveIteratorIterator( new RecursiveArrayIterator( json_decode( $return, TRUE ) ), RecursiveIteratorIterator::SELF_FIRST );

foreach ( $obj as $key => $val ) {
    $$key = $val;

    $stmt = $connection->prepare( "INSERT INTO heartrate SET `encodedid` = ?, activitydate = ?, rhr = ? ON DUPLICATE KEY UPDATE rhr= ?" );
    $stmt->bind_param( 'ssii', $studentencodedid, $dateTime, $restingHeartRate, $restingHeartRate );
    $stmt->execute();

    if ( $stmt->affected_rows < 1 ) {
        header( "Location: " . $url . "/index.php?errormessage=Failed to updated the resting heart rate value." );
    }

    $stmt->close();
}


texts:
below is a code to play a game of a popular card game, Pontone. you play your game against the dealer. your hand is randomly made and so is the dealers from the set of cards. you play through the normal game of pontone either "hitting" or "sticking". When you finish your play the dealer plays his and the winner is decided at the end.

import random

unused_cards = ['AS','2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AC','2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AH','2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AD','2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD']
used_cards = []
player_1_hand = []
dealer_hand = []

this calculates the total of each players hands

def calculate_hand(player):
    global total
    total = 0
    for i in range(len(player)):
        card = player[i]
        if len(card) == 2:
            value = card[0]
        else:
            value = card[:2]

        if value == "A":
            total+=1
        elif value == "J" or value == "Q" or value == "K":
            total += 10
        else:
            total += int(value)

    return total

this part of the code is the dealer playing his hand

def dealer(j):
    global dealer_total
    for i in range(2):
        drawn_card = random.choice(j)
        used_cards.append(drawn_card)
        unused_cards = [f for f in j if f not in used_cards]
        dealer_hand.append(drawn_card)

    dealer_total = calculate_hand(dealer_hand)
    dealer_play = True

    while dealer_play:
        if dealer_total<12:
            drawn_card = random.choice(j)
            used_cards.append(drawn_card)
            unused_cards = [f for f in j if f not in used_cards]
            dealer_hand.append(drawn_card)

        elif dealer_total<=12 and dealer_total<16:
            determine_hit = random.randrange(2)
            if determine_hit == 1:
                drawn_card = random.choice(j)
                used_cards.append(drawn_card)
                unused_cards = [f for f in j if f not in used_cards]
                dealer_hand.append(drawn_card)

            else:
                dealer_play = False

        dealer_play = False

        dealer_total = calculate_hand(dealer_hand)

    if dealer_total > 21:
        dealer_win = False
    else:
        dealer_win = True

    print(dealer_hand)
    return dealer_win

this part draws the original hand for the player

def drawhand(j, player):
    global stick

    for i in range(2):
        drawn_card = random.choice(j)
        used_cards.append(drawn_card)
        unused_cards = [f for f in j if f not in used_cards]
        player.append(drawn_card)

    stick = False

    print(player)
    player_total = calculate_hand(player)

this is the main game loop where you play the game.

def gameloop(j):
    global stick
    global dealer_total

    win = True
    drawhand(j, player_1_hand)
    while not stick:
        play = input("stick or hit")

        if total == 21:
            print("pontone")
            stick = True

        if play == "stick":
            stick = True

        elif play == "hit":
            draw_card = random.choice(j)
            used_cards.append(draw_card)
            unused_cards = [j for j in j if j not in used_cards]
            player_1_hand.append(draw_card)
            player_total = calculate_hand(player_1_hand)
            print(player_1_hand)

            if total == 21:
                print("pontone")
                stick = True
            elif total>21:
                print("bust")
                win = False
                stick = True

    player_total = calculate_hand(player_1_hand)

    dealer_win = dealer(j)

    if (dealer_total <= player_total and win != False) or dealer_win == False:
        print("you win")
    else:
        print("you lose")

gameloop(unused_cards)

If you have any ways on how to improve this please share.


texts: Composing a prototype chain in JavaScript

texts:
As an exercise, I wrote a simple function that composes a prototype chain from a list of objects by appending to the prototype chain of the first object, the rest of the objects. This is the code (example usage and tests in this gist):

var assign = Object.assign || require('object.assign');

// Non-enumerable properties are omitted. Property attributes are not respected
// and getters and setters aren't copied.
function appendToProto(obj, proto)
{
  if (obj === null)
    throw new Error(
      'Prototype chains are assumed to be delimited by Object.prototype.'
    );
  else if (obj === Object.prototype)
    return proto;
  else
    return assign(
      Object.create(
        appendToProto(Object.getPrototypeOf(obj), proto)
      ),
      obj
    );
}

// Takes a list of objects. The first object will be the farthest away from root
// (Object.prototype).
function composeProtoChain(prototypes)
{
  return prototypes.reduce(appendToProto);
}

As noted above, I can identify three issues with this code:

Non-enumerable properties are omitted from the prototype chain.
Property attributes are not respected and getters and setters aren't copied.
The assumption that Object.prototype is the last object before null in the prototype chain of objects.

I don't think there is a solution for the first issue, but workarounds could be implemented for the second and third ones. I preferred to keep things simple here, so I avoided doing that.
(Exceeding the maximum recursion depth in appendToProto shouldn't be a problem.)

I have two questions:

Is throwing an error in appendToProto the right way to enforce the assumption from the third issue?
Are there any other caveats that I haven't considered?


texts: Hangman game with hard-coded word or phrase

texts:
I feel that this implementation can still be simplified.  I've tried to keep variable scopes low and have used as much of the standard library as I could.

It currently works with a hard-coded word or phrase, but I eventually plan on having it work with random words or phrases from a file.

My main concern is in regards to my functions.  Am I using too few or too many of them?  I still feel that main() is doing a little too much.

Note: I have not tagged this as c++11 because there's no utilization of it here, but I am open to any recommendations from C++11.

#include <iostream>
#include <string>

bool isCorrectGuess(const char guess, std::string const& word)
{
    return (word.find(guess) != std::string::npos);
}

std::string updateWrongGuesses(const char guess, std::string const& word, std::string wrongGuesses)
{
    return wrongGuesses += guess;
}

std::string updateCorrectGuesses(const char guess, std::string const& word, std::string correctGuesses)
{
    for (std::string::size_type i = 0; i != word.size(); ++i)
    {
        if (word[i] == guess)
        {
            correctGuesses[i] = guess;
        }
    }

    return correctGuesses;
}

void displayStatus(const unsigned int triesLeft, std::string const& guessedWord, std::string const& wrongGuesses)
{
    std::cout << "\n\nRemaining Tries: " << triesLeft;
    std::cout << "\nWrong Guesses  : " << wrongGuesses;
    std::cout << "\n\n" << guessedWord << "\n\n";
}

int main()
{
    const std::string word = "rabbit rabbit";

    std::string guessedWord;

    // set up placeholders for word to be guessed
    for (std::string::size_type i = 0; i != word.size(); ++i)
    {
        guessedWord += (isspace(word[i])) ? ' ' : '*';
    }

    unsigned int triesLeft = 8;
    std::string wrongGuesses;

    displayStatus(triesLeft, guessedWord, wrongGuesses);

    std::string attemptedGuesses;

    while (triesLeft > 0 && guessedWord != word)
    {
        std::cout << "\nGuess a letter: ";
        char guess;
        std::cin >> guess;
        guess = tolower(guess);
        attemptedGuesses += guess;

        if (isCorrectGuess(guess, word))
        {
            guessedWord = updateCorrectGuesses(guess, word, guessedWord);
        }
        else
        {
            wrongGuesses = updateWrongGuesses(guess, word, wrongGuesses);
            triesLeft--;
        }

        displayStatus(triesLeft, guessedWord, wrongGuesses);
    }

    if (guessedWord == word)
    {
        std::cout << "\n\nYou've guessed the word/phrase!\n\n";
    }
    else
    {
        std::cout << "\n\nYou've been hanged...\n\n";
        std::cout << "The word/phrase is: " << word;
    }
}


texts:
I am trying to find a best match for a name within a list of names.

I came up with the below code, which works, but I feel that the creation of the intermediate ratios list is not the best solution performance-wise.

Could it be somehow replaced? Would reduce be a good fit here (I have tried it, but could not get the index of best match and its value at the same time).

from fuzzywuzzy import fuzz

name_to_match = 'john'
names = ['mike', 'james', 'jon', 'jhn', 'jimmy', 'john']
ratios = [fuzz.ratio(name_to_match, name) for name in names]
best_match = names[ratios.index(max(ratios))]
print(best_match) # output is 'john'


texts: Intersect knockoutjs observablearray using linqjs

texts:
I wrote a extender function to observableArray in knockout js. What I'm looking for is a way to extract the intersection records based on one property. This works well on smaller number of arrays, but shows pretty poor performance in larger arrays. I dont know if it is the observables that makes it slower?

How would you guys write it?

obsArray2 - The array to compare with

Key - Name of the property to compare between

ko.observableArray.fn.intersect = function (obsArray2, Key) {
    var self = Enumerable.From(ko.unwrap(this));
    var arrValues1 = self.Select(function (item) { return ko.unwrap(item[Key]); });
    arrValues2 = Enumerable.From(ko.unwrap(obsArray2)).Select(function (item) { return ko.unwrap(item[Key]); });
    var IntersectedValues = arrValues1.Intersect(arrValues2).ToArray();

    return self.Where(function (item) { return IntersectedValues.contains(ko.unwrap(item[Key])) }).ToArray();
    return obsArray1.Intersect(obsArray2).ToArray();
};


texts:
I'm trying to implement search over two models. In this example Book and Article. Here are the attributes from both of these :

Article(id: integer, magazine: string, title: string, body: text, created_at: datetime, updated_at: datetime)
Book(id: integer, publisher: string, author: string, title: string, foreword: text, body: text, created_at: datetime, updated_at: datetime)

I'm trying to search over multiple attributes on both of these Models using the same search string and combining results. Because my next goal is to have a permlink to results.

Here is how I implemented search on these Models:

def self.search(q)
  Article.where('magazine like :value OR title like :value OR body like :value', value: "%#{q}%")
 end

def self.search(q)
  Book.where('publisher like :value OR author like :value OR title like :value OR foreword like :value OR body like :value', value: "%#{q}%")
end

Here is the controller :

class HomeController < ApplicationController
    def search
      articles = Article.search(params[:q])
      books = Book.search(params[:q])

      @results = articles + books
    end
end

I use haml so here is my searchresult page :

%div.main
  %div.pull.left
    =link_to 'Back to search', '/',:class => 'btn btn-primary btn-lg'
  %div.clearfix
  %table.table.table-condensed
    %thead
      %tr
        %th Id
        %th Title
        %th Type
    %tbody
      - @results.each do |item|
        %tr
          %td #{item.id}
          %td #{item.title}
          %td #{item.class.name}

Is there a more elegant way to actually do the search? I don't have that many experience with rails but I was reading trough this article :

http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

1. And I was thinking I could do this as 2. Extract Service Objects, but as two search methods search over different attributes I wasn't able to do this? I'd be glad to hear your take on this.

2. Regarding the permlink to my search. I'm wondering should I create another model named i.e SearchResult and then link the single search result to many Books and Articles?

Update

I'm not looking for solutions like Sunspot or Sphinx, as this is a small app in dev mode just for practising but still I want it to be as better as possible.


texts:
I am new to C and am writing a basic program to calculate the arithmetic sum of two numbers stored in a linked list.

My main question is idiomatic memory management in C. The program below allocates a new linked list node, but does not deallocate it. What is a good way to do so?

#include <stdio.h>
#include <stdlib.h>

typedef struct SinglyLinkedListInt {
  int value;
  struct SinglyLinkedListInt *next;
} SinglyLinkedListInt;

SinglyLinkedListInt *add_two_numbers(SinglyLinkedListInt *l1, SinglyLinkedListInt *l2) {
  SinglyLinkedListInt root = { .value = 0, .next = NULL };
  SinglyLinkedListInt *current = &root;

  int carry = 0;
  while (l1 || l2 || carry) {
    int a = l1 ? l1->value : 0;
    int b = l2 ? l2->value : 0;
    int value = carry + a + b;

    SinglyLinkedListInt *next = malloc(sizeof(SinglyLinkedListInt));
    next->value = value % 10;
    next->next = NULL;
    current->next = next;

    carry = value / 10;
    l1 = l1 ? l1->next : NULL;
    l2 = l2 ? l2->next : NULL;
    current = current->next;
  }

  return root.next;
}

int main() {
  SinglyLinkedListInt l13 = { .value = 3, .next = NULL };
  SinglyLinkedListInt l12 = { .value = 4, .next = &l13 };
  SinglyLinkedListInt l11 = { .value = 2, .next = &l12 };

  SinglyLinkedListInt l23 = { .value = 4, .next = NULL };
  SinglyLinkedListInt l22 = { .value = 6, .next = &l23 };
  SinglyLinkedListInt l21 = { .value = 5, .next = &l22 };

  SinglyLinkedListInt *result = add_two_numbers(&l11, &l21);

  while (result) {
    printf("%d ", result->value);
    result = result->next;
  }
  printf("\n");

  return 0;
}


texts:
I have recently forked/rewritten a SEDE query (here) that aims at figuring out where a site stands in terms of avid users and distribution of reputation scores, compared to a specific target (number of avid users in each major rep cluster).

declare @target_20k float
declare @target_10k float
declare @target_3k float
declare @target_2k float

set @target_20k = 3.0
set @target_10k = 10.0
set @target_3k = 80.0
set @target_2k = 120.0

/* only look at users that visited the site recently */
declare @lastActiveDays int
set @lastActiveDays = 60

select [20K], [10K], [3K], [2K],
       [TotalSiteRep],
       [UsersCount],
       round([TotalSiteRep]/cast([UsersCount] as float),2) [AvgRep],
       [AvidUsersRep],
       round([AvidUsersRep]/cast([TotalSiteRep] as float),2) [%AvidRep],
       [AvidUsersCount],
       round([AvidUsersCount]/cast([UsersCount] as float),2) [%AvidUsers],
       round([AvidUsersRep]/cast(AvidUsersCount as float),2) [AvgAvidRep]
from (

select round(sum([20K])/@target_20k, 2) [20K],
       round(sum([10K])/@target_10k,2) [10K],
       round(sum([3K])/@target_3k,2) [3K],
       round(sum([2K])/@target_2k,2) [2K],
       sum(Reputation) [TotalSiteRep],
       count(*) [UsersCount],
       sum(AvidRep) [AvidUsersRep],
       sum(AvidUser) [AvidUsersCount]
from (
  select Reputation,
    case when Reputation >= 20000 then 1 else 0 end [20K],
    case when Reputation >= 10000 then 1 else 0 end [10K],
    case when Reputation >= 3000 then 1 else 0 end [3K],
    case when Reputation >= 2000 then 1 else 0 end [2K],
    case when Reputation >= 150 then Reputation else 0 end [AvidRep],
    case when Reputation >= 150 then 1 else 0 end [AvidUser]
  from Users
  where datediff(d, LastAccessDate, getdate()) <= @lastActiveDays
) q
) r

I'm not crazy about the case when ... then .. else ... end part and about the sub-querying, but it seems to get the job done.

Is there a better way to aggregate conditional sums? (feel free to review everything else, ...except the broken indentation of the q query - that's already something I know I have to fix ;)

Here are the query's results for Code Review, as of the latest SEDE update:


texts: Thread safe reader-writer queue with C++11

texts:
Below is my honest attempt to write thread safe queue using C++11 features. Please review it and provide your comments.

#include <queue>
#include <condition_variable>
#include <atomic>
#include <iostream>

template <typename T>
class ThreadSafeQueue
{
    std::queue<T> m_queue;
    std::mutex m_mutex;
public :

    void Push(const T& data)
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_queue.push(data);
    }

    // Universal reference
    template <typename ...Args>
    void Emplace(Args&&... args)
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_queue.emplace(std::forward<Args>(args)...);
    }

    void PopFront(T& data)
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        data = m_queue.front();
        m_queue.pop();
    }

    void PopFrontNoLock(T& data)
    {
        data = m_queue.front();
        m_queue.pop();
    }

    size_t Size()
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        return m_queue.size();
    }

    bool Empty()
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        return m_queue.empty();
    }

    bool EmptyNoLock()
    {
        return m_queue.empty();
    }

    std::mutex& GetMutex()
    {
        return m_mutex;
    }

};

template <typename T>
class ReaderWriterQueue
{
    ThreadSafeQueue<T> m_safeQueue{};
    std::condition_variable m_condVar{};
    std::atomic<bool> m_writeCompleted{};
public :
    void Push(const T& data)
    {
        m_safeQueue.Push(data);
        m_condVar.notify_one();
    }

    // Universal reference
    template <typename ...Args>
    void Emplace(Args&&... args)
    {
        m_safeQueue.Emplace(std::forward<Args>(args)...);
        m_condVar.notify_one();
    }

    void PopFront(T& data)
    {
        std::unique_lock<std::mutex> lock(m_safeQueue.GetMutex());
        m_condVar.wait(lock, [this] {return (!m_safeQueue.EmptyNoLock() || m_writeCompleted); });
        m_safeQueue.PopFrontNoLock(data);
    }

    void NotifyWriteEnd()
    {
        m_writeCompleted = true;
    }

    bool IsWriteFinished() const
    {
        return m_writeCompleted;
    }

    bool Empty()
    {
        return m_safeQueue.Empty();
    }

};

Driver code to test thread safe queue:

void ProduceData(ReaderWriterQueue<int>& queue)
{
    int i = 0;
    while (i < 10)
    {
        queue.Emplace(i);
        i++;
    }
    queue.NotifyWriteEnd();
    std::cout << "Finished Writing" << std::endl;
}

void ReadData(ReaderWriterQueue<int>& queue)
{
    while (!queue.IsWriteFinished() || !queue.Empty())
    {
        int waitTime;
        queue.PopFront(waitTime);
        std::cout << "popped " << waitTime << "\n";
        std::this_thread::sleep_for(std::chrono::seconds(waitTime));
    }
    std::cout << "Finished Reading" << std::endl;
}

int main()
{
    ReaderWriterQueue<int> rwQueue;
    std::thread writer(ProduceData, std::ref(rwQueue));
    const int readerThreadCount = 2;
    std::thread readers[readerThreadCount];
    for (int count=0; count < readerThreadCount; count++)
    {
        std::thread reader(ReadData, std::ref(rwQueue));
        readers[count] = std::move(reader);
    }

    if (writer.joinable())
    {
        writer.join();
    }
    for (int count = 0; count < readerThreadCount; count++)
    {
        if (readers[count].joinable())
        {
            readers[count].join();
        }
    }
    return 0;
}


texts:
I am mostly interested in how the parse_string function could be improved.  But any comments on my test strategy also welcome.

The input is a string which can be either all digits in which case the result should be the digits string OR there can be string formatting outside angle brackets which must be removed.  the digit string is enclosed within the angle brackets in that case.

#include <stdio.h>
#include <string.h>

char* parse_string(const char* s, char* parsed) {
   /* sample string for angle brackets */
   const char* p = s;
   int lbrack = -1, rbrack = -1;
   while(*p) {
      if(*p == '<' && lbrack == -1)  /* grab first < */
         lbrack = p - s;
      else if(*p == '>') /* and last > char */
         rbrack = p - s;

      ++p;
   }

   /* strip everything BEFORE < and AFTER > if have brackets and in correct order */
   if(lbrack != -1 && rbrack != -1 && lbrack < rbrack) {
      memcpy(parsed, s+lbrack+1, rbrack-1-lbrack);
      parsed[rbrack-1-lbrack] = '\0';
   }
   else {
      strcpy(parsed, s ? s : "");
   }

   return parsed;
}

int main() {

   char buf[100];
   /* 4 normal cases, error cases  */
   const char* input[] = { "N<737867>Sales Line 1", "123456", "", "<123>", "<", ">", "", "<<<<123>", "<123>>>>", "<123", "123>" };
   const char* output[] = { "737867", "123456", "", "123", "<", ">", "", "<<<123", "123>>>", "<123", "123>" };
   size_t sz = sizeof(input) / sizeof(input[0]);

   size_t i;
   for(i = 0; i < sz; ++i) {
      printf("Test string \"%s\" => \"%s\", %s\n", input[i], output[i], strcmp(output[i], parse_string(input[i], buf)) == 0 ? "passed" : "failed");
   }
   return 0;
}


texts: For finding whether a puzzle state is solvable

texts:
I have code which returns whether or not a sliding tile puzzle state is solvable.
I was wondering whether there is any way I could either make the code a bit more readable or increase the performance in any way.

  public boolean isSolvable(int[] puzzle) {
        int parity = 0;
        int gridWidth = (int) Math.sqrt(puzzle.length);
        int row = 0; // the current row we are on
        int blankRow = 0; // the row with the blank tile

        for (int i = 0; i < puzzle.length; i++) {
            if (i % gridWidth == 0) { // advance to next row
                row++;
            }
            if (puzzle[i] == 0) { // the blank tile
                blankRow = row; // save the row on which encountered
                continue;
            }
            for (int j = i + 1; j < puzzle.length; j++) {
                if (puzzle[i] > puzzle[j] && puzzle[j] != 0) {
                    parity++;
                }
            }
        }

        if (gridWidth % 2 == 0) { // even grid
            if (blankRow % 2 == 0) { // blank on odd row; counting from bottom
                return parity % 2 == 0;
            } else { // blank on even row; counting from bottom
                return parity % 2 != 0;
            }
        } else { // odd grid
            return parity % 2 == 0;
        }
    }


texts: Applying dynamic filters to a SQL query using Python conditional expressions

texts:
I wrote this piece of code to eliminate the need for multiple if then statements based on the filters from the incoming REST request.

If the request has category in it, then the query has to be filtered by category, the same for product_location. I wrote a single statement instead of having to check for the filters and have multiple queries.

If the product_category is equal to All Category, then a filter need not be applied, etc.

query = \
    'select AVG(stock_date - order_date) as c,product_category from data_table_data where stock_date between :s1 and :s2 ' \
    + (('and product_category = :category ' if category
       != 'All Category' else '')) + (('and product_location = :loc '
         if store_location != 'All Stores' else '')) \
    + 'group by product_category'
data = engine.execute(text(query), s1=startDate, s2=endDate,
                      category=category, loc=store_location).fetchall()


texts: Is there a simpler way to write a row from one table to another?

texts:
I have the following code:

const String sqlSelect = "SELECT * FROM UserPasswords WHERE username='System Administrator';";
const String sqlInsert = "INSERT INTO UserPasswords VALUES (@username,@Password,@startDate,@Expired,@UserPasswordsID)";
using (var con1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dataConnectionString"].ConnectionString))
using (var con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["utilConnectionString"].ConnectionString))
{
  con1.Open();
  con2.Open();
  using (var selectCommand = new SqlCommand(sqlSelect, con1))
  {
    using (var reader = selectCommand.ExecuteReader())
    {
      if (reader.Read())
      {
        using (var insertCommand = new SqlCommand(sqlInsert, con2))
        {
          insertCommand.Parameters.Add(new SqlParameter("@username", reader.GetString(0)));
          insertCommand.Parameters.Add(new SqlParameter("@Password", reader.GetString(1)));
          insertCommand.Parameters.Add(new SqlParameter("@startDate", reader.GetDateTime(2)));
          insertCommand.Parameters.Add(new SqlParameter("@Expired", reader.GetBoolean(3)));
          insertCommand.Parameters.Add(new SqlParameter("@UserPasswordsID", reader.GetInt32(4)));
          insertCommand.ExecuteNonQuery();
        }
      }
    }
  }

All I need to do is copy the row with the 'System Administrator' info into another table as a backup. Though this code works is there someway to do this more elegantly?


texts:
Below the text of the exercise:

  We are given the head node root of a binary tree, where additionally
  every node's value is either a 0 or a 1.

  Return the same tree where every subtree (of the given tree) not
  containing a 1 has been removed.

  (Recall that the subtree of a node X is X, plus every node that is a
  descendant of X.)

  Note:

  The binary tree will have at most 100 nodes.
  The value of each node will only be 0 or 1.

I have the following code and it does not look nice to me as too many if statements strolling around. How can I make this shorter and nice looking (more readable). Tree has nodes that contain 0 or 1 as value. I make the node null if it does not contain any node having 1 as value.

public TreeNode pruneTree(TreeNode root) {
    if (root == null || (root.left == null && root.right == null && root.val == 0)) return null;

    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);

    while(!queue.isEmpty()) {
        TreeNode node = queue.poll();

        if (node.left != null && !containsOne(node.left)) {
            node.left = null;
        }

        if (node.right != null && !containsOne(node.right)) {
            node.right = null;
        }

        if (node.left != null) {
            queue.offer(node.left);
        }

        if (node.right != null) {
            queue.offer(node.right);
        }
    }

    return root;
}

private boolean containsOne(TreeNode node) {
    if (node == null) return false;
    if (node.val == 1) return true;
    return containsOne(node.left) || containsOne(node.right);
}