texts: Moving a bot through a maze with Depth First Search

texts:
This is supposed to be a depth first search. I just took the idea of what it does and made my own version of it. The bot works it's way through the maze, when it finds a dead end, it moves back to original spot, and continues in a different direction than it's already gone until it reaches E the end.

import java.util.Stack;
import java.lang.Comparable;
import java.util.*;

class Main {

  public static int[][] maze = {
    {9,9,9,9,9,9,9,9,9,9,9,9},
    {9,1,1,1,1,1,1,1,1,1,1,9},
    {9,1,0,1,0,1,1,0,0,0,5,9},
    {9,1,0,0,0,0,0,1,0,1,1,9},
    {9,1,1,0,1,1,0,1,0,0,1,9},
    {9,1,0,0,1,0,0,0,0,0,1,9},
    {9,1,1,0,1,1,1,1,1,0,1,9},
    {9,1,0,0,1,0,0,0,1,0,1,9},
    {9,1,1,0,1,0,1,0,1,1,1,9},
    {9,1,0,0,0,0,1,0,0,0,3,9},
    {9,1,1,1,1,1,1,1,1,1,1,9},
    {9,9,9,9,9,9,9,9,9,9,9,9}
    };

    public static Deque<Coordinate> deadEnd = new ArrayDeque<Coordinate>(10);
    public static Deque<Coordinate> deq = new ArrayDeque<Coordinate>(10);

  public static void main(String[] args) {

    printMaze();
    dfs(2,10);

  }

  public static boolean isDeadEnd(Coordinate coord){
    Iterator it = deadEnd.iterator();
    while(it.hasNext()){
      if(it.next().equals(coord)){
        return true;
      }
    }
    return false;
  }

  public static Coordinate setCoord(int i, int j){
    Coordinate coord = new Coordinate();
    coord.setCoord(i,j);
    return coord;
  }

  public static boolean checkCoord(Coordinate coord){
    return iterateCoord(coord);
  }

  private static boolean iterateCoord(Coordinate coord){
    Iterator it = deq.iterator();
    while(it.hasNext()){
      if(it.next().equals(coord)){
        return true;
      }
    }
    return false;
  }

  public static int dfs(int i, int j){
    if(i == 9 && j == 9){
      maze[9][10] =4;
      printMaze();
      System.out.println("You're Free!");
      return 0;
    }
    Coordinate coord = new Coordinate();

if(!checkCoord(coord) && !isDeadEnd(coord)){

    if(maze[i+1][j] == 0 || maze[i+1][j] == 3){
        coord = setCoord(i+1, j);
        deq.push(coord);
        maze[i+1][j] = 4;
        printMaze();
        return dfs(i+1,j);
    }
    else if(maze[i-1][j] == 0){
        coord = setCoord((i-1),j);
    deq.push(coord);
        maze[i-1][j] = 4;
        printMaze();
        return dfs(i-1,j);
    }
    else if(maze[i][j+1] == 0){
        coord = setCoord(i,(j+1));
        deq.push(coord);
        maze[i][j+1] = 4;
        printMaze();
        return dfs(i,j+1);
    }
    else if(maze[i][j-1] == 0){
        coord = setCoord(i,(j-1));
        deq.push(coord);
        maze[i][j-1] = 4;
        printMaze();
        return dfs(i,j-1);
    }
}

    deadEnd.push(deq.pop());
    int n = deq.peek().getX();
    int m = deq.peek().getY();
   // maze[m][n] = 0;
    return dfs(n,m);
  }

  public static void printMaze() {

    for(int i = 0; i < 12; i++){
      for(int j = 0; j < 12; j++){
        if(maze[i][j]==1){
         System.out.print(" X ");
        }
        if(maze[i][j]==0){
          System.out.print("   ");
        }
        if(maze[i][j]==2){
          System.out.print(" e ");
        }
        if(maze[i][j]==3){
          System.out.print(" E ");
        }
        if(maze[i][j]==4){
          System.out.print(" b ");
        }
        if(maze[i][j]==5){
          System.out.print(" b ");
          maze[i][j] = 1;
        }
      }
      System.out.println();
    }
  }
}

class Coordinate{
  Integer x = 0;
  Integer y = 0;

  public int getX(){
    return x;
  }
  public int getY(){
    return y;
  }
  public void setCoord(int i, int j){
    x = i;
    y = j;
  }
  @Override
  public boolean equals(Object obj) {

    if(obj == null){
      return false;
    }
    if(obj instanceof Coordinate){
      Coordinate test = (Coordinate) obj;
      if(test.x == this.x && test.y == this.y){
        return true;
      }
    }
    return (this == obj);
  }
  /*
  @Override
  public int hashCode(){
    return x + y * 31;
  }
    */
}


texts: Reverse the word in a string with the same order in javascript

texts:
I want reverse the string with the same order. We should not use the Array functions like split(), .reverse() and some other array functions also except array.length.

Here i am attached my code. How to achieve that thing more efficiently.

var str = "i am javascript";
// result "i ma tpircsavaj"
function reverseString(myStr){
    var strlen = myStr.length, result = "", reverseStr = "", reverseStrArr = [];
  for(var i = strlen-1; i >= 0; i--){
    reverseStr +=  myStr[i];
  }

    for(var j = 0; j < strlen; j++){
    if(reverseStr[j] == " "){
      reverseStrArr.push(result);
      result = "";
    }else{
      result += reverseStr[j];
      if(j + 1 == strlen){
        reverseStrArr.push(result);
        result = "";
      }
    }
  }

  for(var k=reverseStrArr.length - 1; k >= 0; k--){
    result += reverseStrArr[k] + " "
  }
  console.log(result);
}
reverseString(str);


texts:
I've written a code snippet that will get a (max.) 14 character string from the user input, and while the user is typing, simultaneously echo it out to the screen.

It seems a bit long and ugly, so I was wondering if any of you would happen to have ideas on how to shorten, and generally optimize this.

for(int i = 0; i < 15; i++)
{
    char npt = _getch(); // Get input

    if(i == 14) // Last character (user has to press \r or \b)
    {
        if(npt == '\r') // enter, break loop
            break;
        else if(npt == '\b') // backspace, re-loop
        {
            if(!name.empty())
                name.erase(std::prev(name.end()));
            if(i >= 1)
                i -= 2;
            else
                i--;
        }
        else // other input, meaning re-loop
            i--;

        SetConsoleCursorPosition(hOut, cDraw);
        printf("              "); // clear string area
        SetConsoleCursorPosition(hOut, cDraw);
        std::cout << name; // echo string
        continue;
    }
    else
    {
        if(npt == '\r')
            break;
        else if(npt == '\b')
        {
            if(!name.empty())
                name.erase(std::prev(name.end()));
            if(i >= 1)
                i -= 2;
            else
                i--;
        }
        else
            name += npt; // add input to string

        SetConsoleCursorPosition(hOut, cDraw);
        printf("              ");
        SetConsoleCursorPosition(hOut, cDraw);
        std::cout << name;
    }
}


texts: Moving character in Unity3D based on accelerometer input

texts:
I am building a infinite vertical platformer for mobile platforms using Unity3D. I am using the accelerometer to move the character left and right on the screen.

if (Input.acceleration.y > -0.2f && Input.acceleration.y < 0.2f) {
                        maxSpeed = 17;
                }

        if (Input.acceleration.y > -0.5f && Input.acceleration.y < -0.2f) {
            maxSpeed = 25;
        }
        if (Input.acceleration.y > 0.2f && Input.acceleration.y < 0.5f) {
            maxSpeed = 25;
        }
        if (Input.acceleration.y > -0.7f && Input.acceleration.y < -0.5f) {
            maxSpeed = 25;
        }
        if (Input.acceleration.y > 0.5f && Input.acceleration.y < 0.9f) {
            maxSpeed = 25;
        }
        if (Input.acceleration.y < -0.9f) {
            maxSpeed = 40;
        }
        if (Input.acceleration.y  > 0.9f) {
            maxSpeed = 40;
        }

Basically the farther the device is tilted the faster the character moves. I'm pretty sure there is a way better way to write this code but I'm pretty terrible at math and I can't figure it out. Any suggestions on cleaning this up a bit?


texts:
I have just begun learning Julia. Here is an implementation of experience replay memory for use in a reinforcement learning algorithm. It is pretty simple, essentially a ring buffer with the following requirements:

Used to store 1D arrays of numbers, typically Float32 or Float64. All the stored arrays are the same size.
Has a maximum capacity, after which new entries overwrite old ones
Has a sample function for retrieving a given number of entries

import Base.length

struct Memory{T <: Real}
   max_size::UInt32
   experiences::Vector{Vector{T}}
end

Memory{T}(max_size) where {T <: Real} = Memory{T}(max_size, Vector{Vector{T}}())

length(memory::Memory) = length(memory.experiences)

function remember!(memory::Memory, experience)
   size = length(memory)
   if size == memory.max_size
      memory.experiences[1 + size % memory.max_size] = experience
   else
      push!(memory.experiences, experience)
   end
end

function sample(memory::Memory{T}, count::Integer) where {T <: Real}
   size = length(memory)
   @assert count <= size
   return [memory.experiences[1 + rand(UInt32) % size] for i in 1:count]
end


texts:
Test Case:
Input- "I'm hungry!"
Output- "!yrgnuh m'I"

Approach 1: In this approach, I used a empty string and bind it with the input string reversely.

public static class ReverseString {

   public static string Reverse (string input) {

    //bind the string to an empty string reversly
    var reversedString = "";

    //check if the input is empty
    if (input == "")
    {
        return "";
    }
    else
    {
        for (int i = input.Length - 1; i >= 0; i--)
        {
            reversedString += input[i];
        }
       return reversedString;
    }
  }
}

Approach 2: In this approach, I've created an empty char array which has the same length of the string. Then I've copied the value of string's last index to char array's first index and so on.

public static class ReverseString {
   public static string Reverse (string input) {

      char[] chars = new char[input.Length];

      for(int i = 0, j = input.Length -1; i <= j; i++, j--)
      {
        chars[i] = input[j];
        chars[j] = input[i];
      }

      return new string(chars);
   }
}

There are lots of approaches like this(without using built in library). But I wonder which one is the most recommended among programmers preferably C# programmers.Which one do you recommend and why?


texts: Class to help dealing with files, with lazy properties

texts:
I have the following class to help me deal with files:

File class:

# -*- coding: utf-8 -*-

"""
file
~~~~~~~~~~~~~~~~
"""

from mimetypes    import MimeTypes
from os           import path
from lazyproperty import lazyproperty

class File(object):
    """Class to help dealing with files.
    """

    def __init__(self, path):
        """The constructor function.
        """
        self.path = path

    @lazyproperty
    def basename(self):
        """Return last portion of the file.
        """
        return path.basename(self.path)

    @lazyproperty
    def extension(self):
        """The extension name of the file, from the last occurrence of the
        . (period) character to end of string.
        """
        remaining, extension = path.splitext(self.path)
        return extension

    @lazyproperty
    def encoding(self):
        """The encoding of the file, if no encoding is found, None will be
        the default.
        """
        return self.__mime_type_and_encoding[1]

    @lazyproperty
    def abspath(self):
        """The absolute path of the file.
        """
        return path.abspath(self.path)

    @lazyproperty
    def mime_type(self):
        """The mime type associated with the file, if no mime type is found,
        None will be the default.
        """
        return self.__mime_type_and_encoding[0]

    # @private
    @lazyproperty
    def __mime_type_and_encoding(self):
        """Guess the type of a file based on its filename or URL, given by url.
        The return value is a tuple (type, encoding) where type is None if the
        type can’t be guessed (missing or unknown suffix) or a string of the
        form 'type/subtype', usable for a MIME content-type header.
        """
        return MimeTypes().guess_type(self.abspath)

lazyloading class:

# -*- coding: utf-8 -*-

"""
lazyproperty
~~~~~~~~~~~~~~~~
"""

class lazyproperty(object):
    """Class to create lazy properties.
    """

    def __init__(self, func):
        """The constructor function.
        """
        self.func = func

    def __get__(self, instance, cls):
        if instance is None: return self
        value = self.func(instance)
        setattr(instance, self.func.__name__, value)
        return value

I would like to improve the lazyproperties mime_type and encoding, this two parts:

return self.__mime_type_and_encoding[1]
return self.__mime_type_and_encoding[0]

Are making my sad, this magic numbers are very bad for maintenance. What i'm doing:

I'm using python 2.5 because i'm working in this legacy code, and the only way to get the mime type of file in this version is using the MimeTypes class:

mime_type = MimeTypes().guess_type("path/to/file")

Returns a tuple, -> ("mime_type", "encoding")

Which doesn't make any sense, since i'm asking for the  mime type, not the encoding... any way... so, i created the __mime_type_and_encoding lazyproperty to avoid calling the MimeTypes() two times, in the encoding and mime_type.

Is it possible to avoid the magic numbers, and still do what i want?


texts: Extracting grouped objects into a flattened list

texts:
I need to optimize this javascript method because it is a bit slow, I don't want to use the flat() command, as for some reason my angular6 app does not understand the vanilla flat() command, or display some annoying warning messages.

So check the below:

  my original object
  my result object desired
  my slow solution (works, but is slow)

1. my original object:

  const data = [
      {
        "id": 1,
        "name": "Application",
        "groups": [
          {
            "groupName": "",
            "configurations": [
              {
                "id": 17,
                "icon": "access_time",
                "title": "Daily Order Cut-Off Time",
                "description": "Daily Order Cut-Off Time",
                "code": "daily-order-cut-off-time",
                "value": "09:35",
                "valueType": "Time",
                "configurationTypeId": 11,
                "definition": {
                  "step": "none"
                },
                "isDefault": false
              }
            ]
          }
        ]
      },
      {
        "id": 3,
        "name": "Processing",
        "groups": [
          {
            "groupName": "",
            "configurations": [
              {
                "id": 1078,
                "icon": "flash_on",
                "title": "Auto Process",
                "description": "Will process all orders that are in the same batch",
                "code": "processing-auto-process",
                "value": "0",
                "valueType": "Boolean",
                "configurationTypeId": 6,
                "definition": null,
                "isDefault": false
              },
              {
                "id": 1074,
                "icon": "subdirectory_arrow_right",
                "title": "Allow Under Picking",
                "description": "Allow under pick when processing order?",
                "code": "processing-allow-under-picks",
                "value": "0",
                "valueType": "Boolean",
                "configurationTypeId": 6,
                "definition": null,
                "isDefault": false
              }
            ]
          }
        ]
      }
    ];

2. object desired:

 [
      {
        "id": 17,
        "code": "daily-order-cut-off-time",
        "value": "09:35"
      },
      {
        "id": 1078,
        "code": "processing-auto-process",
        "value": "0"
      },
      {
        "id": 1074,
        "code": "processing-allow-under-picks",
        "value": "0"
      }
    ]

My slow solution:

const result = data.map(module => module.groups.map(configurations => configurations.configurations.map(config => ({ id: config.id, code: config.code, value: config.value })))).reduce((l,n) => l.concat(n), []).reduce((l2,n2) => l2.concat(n2),[]));


texts: JavaScript function for to create HTML-elements

texts:
I have written this function for creating complete HTML-elements including arbitrary attributes and inner HTML.

I want to keep and reuse it. Therefore I have tried to document the usage well.

I would be interested in hints concerning:

Could the code be improved? So that it is becomes more succinct and efficient?
Can one expect the function to work as intended even when it isn't used correctly?
Is the documentation understandable? Or does it have to be improved?
Is there a way to check if a valid HTML node name has be assigned as first parameter? Currently I'm only checking if the parameter has been assigned and is of type string.

/**
 * Returns an HTML-element of the specified node type,
 *  with the specified attributes and text.
 *
 * @param { string } nodeName - E.g. 'div', 'li', 'p'
 * @param { string } attrs - The attributes of the
 *  HTML-element. Each attribute has to be defined
 *  as <name>=<value>. Multiple attributes have to
 *  be separated with a blank between each pair.
 *  Example:
 *  'value=12 class=option-item data-test=123Demo'
 * @param { string } innerHtml - String for the
 *  innerHTML of the HTML element.
 *
 * @return { Object } - The created HTML element.
 * @throws { Object } - In case of error.
 *
 * Usage example:
 * wrap.appendChild( getHtmlElement(
     'div',
            'class=spec data-shipping=express id=123',
            'Your package will be shipped soon.' ));
 */

function getHtmlElement(nodeName, attrs, innerHtml) {
  var ret = null;

  if (!nodeName || typeof nodeName !== 'string') {
    throw { message: 'No nodeName-parameter assigned.' }
  }

  attrs = attrs || '';
  innerHtml = innerHtml || '';

  ret = document.createElement(nodeName);

  attrs = attrs.split(/\s/g);

  if (attrs[0]) {
    attrs.forEach(function(attr) {
      attr = attr.split(/=/);

      if (attr[1]) {
        ret.setAttribute(attr[0], attr[1]);
      }
    });
  }

  ret.innerHTML = innerHtml;

  return ret;
}

// Usage-example:
document.body
        .appendChild(getHtmlElement(
                     'p',
                    'class=inserted-paragraph data-info=paragraph-number-one',
                     'Lorem ipsum dolor sit amet, consectetuer ' +
                       'adipiscing elit. Aenean commodo ligula eget dolor.'));


texts: Structuring a reusable angular component with multiple communicating directives

texts:
I have a nested JSON of multiple levels. The last level has the "series data" that is to be added to the highcharts options to render the chart data of interest.

I am sniffing the JSON and populating the options in each level which is set as a watched model in the controller and modifying the chart data, which is watched inside of the directive and chart updated on the change of these models.

I am looking to structure this as a reusable component and wondering on the best practice to do so. Seems to me, the "JSON selection" part and the "chart rendering" part can be best as their own directives that communicate amongst each other.

Do you concur or suggest an alternative approach?

Controller:

app.controller('MyCtrl',function($scope,Data,ForwardChart){
    http.get('scripts/lib/bds2.json').success(function(api_data){
        $scope.r_api_data = api_data.res;

        var available_options = [];
        var chosen_options= [];
        var current_json = $scope.r_api_data;
        for (var i=0; i<2; i++){
            var json_options = _.keys(current_json);
            available_options.push(json_options);
            chosen_options.push(json_options[0]);

            current_json = current_json[json_options[0]];
        }

        $scope.plot_data = function(){
            var bdfs_chart = {
                series : Data.get_serieses($scope.r_api_data,$scope.chosen_options)
            };
            $scope.bdfs_chart = $.extend(true,angular.copy(ForwardChart),bdfs_chart);
        };

        $scope.chosen_options = [];
        $scope.available_options = available_options;

        $scope.$watch('chosen_options', function(){
            $scope.plot_data();
        },true);

        $scope.chosen_options = chosen_options;
    })
});

Directive:

app.directive('intchart', function(){
    return {
        restrict: 'E',
        template: '

',
        scope: {
            chartData: "=chartId"
        },

        link: function(scope, element, attrs){
            var chartsDefaults = {
                chart: {
                    renderTo: element[0],
                    type: attrs.type || null,
                    height: attrs.height,
                    width: attrs.width
                },
                colors: attrs.color.split(",")
            };
            var chart = {};
            scope.$watch(function() { return scope.chartData; }, function(value){
                var chart_json = {};
                if (chart.hasOwnProperty('series') && chart.series.length>0){
                    for (var i = 0; i < value.series.length; i++) {
                        chart.series[i].setData(value.series[i].data);
                    }
                } else{
                    $.extend(true, chart_json, chartsDefaults, value);
                    chart = new Highcharts.Chart(chart_json);
                }
            }, true);
        }
    }
})


texts: Transferring data for a given month from one sheet to another

texts:
I have dollar amounts sorted by month that I want to transfer from sheet entry to sheet actuals. I only want to do it for a specified month prompted from user. Each dollar amount has a corresponding cost center/ID and description in separate columns. I want to copy the amounts and description from entry to the row in actuals matching the same ID.

Sometimes, multiple amounts share the same ID so I need to place them one below the other.

Sub month()

Dim actualsWS As Worksheet
Dim dataWS As Worksheet
Dim answer As String
Dim month As String
Dim loc As Range
Dim start As Integer
Dim rowCol As Variant
Dim dropRow As Integer
Dim dropCol As Integer
Dim locActual As Range

'store worksheets into variables
Set actualsWS = ThisWorkbook.Worksheets("Actuals by Month")
Set dataWS = ThisWorkbook.Worksheets("FAS Data Entry")

MsgBox ("If macro dies, it's likely a missing cost center.") 'warning for user

answer = InputBox(prompt:="What month?") 'prompt user for current month

'set month from user input
Select Case answer

    Case 1
    month = "January"
    'dropCol = 9
    Case 2
    month = "February"
    'dropCol = 10
    Case 3
    month = "March"
    'dropCol = 11
    Case 4
    month = "April"
    'dropCol = 12
    Case 5
    month = "May"
    'dropCol = 13
    Case 6
    month = "June"
    'dropCol = 14
    Case 7
    month = "July"
    'dropCol = 15
    Case 8
    month = "August"
    'dropCol = 16
    Case 9
    month = "September"
    'dropCol = 17
    Case 10
    month = "October"
    'dropCol = 18
    Case 11
    month = "November"
    'dropCol = 19
    Case 12
    month = "December"
    'dropCol = 20
    Case Else
    MsgBox ("Bad month. Exiting...")
    Exit Sub

End Select

Dim ccArray(99) 'cost center
Dim amountArray(99) As Currency 'amount
Dim descriptArray(99) 'description
Dim ccArrayLength As Integer

With dataWS

    'locate starting range for current month
    Set loc = .Cells.Find(month)

    'check previous row for carried over month (revising asset) Will break if 2 or more
    If loc.Offset(-1, 0) = "" Then 'if previous row is blank
        start = loc.row 'starting row is same row as found location above
    Else
        start = loc.row - 1 'else it's 1 row above
    End If

    i = 0

    'store data into arrays
    Do While .Cells(start + i, 1) <> "" 'loop through column A while there is a month present (not blank)

        ccArray(i) = .Cells(start + i, 11).Value 'store cost center
        amountArray(i) = .Cells(start + i, 13).Value 'store amount
        descriptArray(i) = .Cells(start + i, 9).Value 'store description

        i = i + 1

    Loop

End With

ccArrayLength = Application.Count(ccArray) 'store number of items

With actualsWS

    .Columns("V:W").ClearContents 'clear previous data

    'hide unnecessary months
    If month = "January" Or month = "February" Or month = "March" Or month = "April" Then
        .Columns("M:Q").EntireColumn.Hidden = True
    End If

    'drop data into respective cells onto "actuals by month" tab
    For x = 0 To ccArrayLength - 1

        On Error Resume Next
        Set locActual = .Cells.Find(ccArray(x)) 'find cost center location
        If locActual = 0 Then GoTo died 'not found
        'Debug.Print locActual
        'rowCol = locActual.Address
        dropRow = .Range(locActual.Address).row 'store row of cost center

        'for loop to find first empty cell to drop into
        For y = 0 To 99 'no cost center should have over 99 rows

            If .Cells(dropRow + y, 22).Value = "" Then 'column v blank
                .Cells(dropRow + y, 22).Value = amountArray(x) 'drop amount
                .Cells(dropRow + y, 22).Offset(0, 1).Value = descriptArray(x) 'drop description on row below
                Exit For
            End If

        Next

    Next

    .Cells(8, 22).Select 'bring cursor to top

End With

died:
'quit before msgbox if on last item
If x = ccArrayLength Then Exit Sub

MsgBox ccArray(x) & " not found." 'cost center not found
Exit Sub

End Sub


texts:
I decided to make my own version of snprintf in C. I intentionally changed some things though. My version guarantees the buffer printed to will be null-terminated, and it returns the number of characters printed to the buffer, not the number that would have been printed if the buffer's size was not limited. And I only worried about some of the main formatting features, like %s, %c, %d, %h, and %H.

I would love to know what I could do better in this and improve, or what aspects of it I did or did not implement well.

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int INT_TO_STR_DIGITS_L[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
int INT_TO_STR_DIGITS_U[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

int int_to_str(int x, char *buf, size_t size, int base, int uppercase) {
    int length = (int)ceil(log((double)x)/log((double)base));
    int r, i = 0;
    char c;

    if (size < length) {
        x /= (int)pow(base, (float)(length - size));
        length = size;
    }

    do {
        if (i >= size) break;
        r = x % base;
        if (uppercase) {
            c = INT_TO_STR_DIGITS_U[r];
        } else {
            c = INT_TO_STR_DIGITS_L[r];
        }
        buf[length-i-1] = c;
        x /= base;
        i++;
    } while (x != 0);

    return i;
}

int my_snprintf(char *str, size_t max_size, const char *fmt, ...) {

    va_list arg_list;
    va_start(arg_list, fmt);

    int chars_printed = 0;
    char *start_str = str;

    char c, *str_arg;
    int num, len;
    int uppercase = 0, base = 10;

    for (int i = 0; fmt[i] != 0; i++) {
        if (max_size - chars_printed <= 0) {
            break;
        } else if (fmt[i] == '%') {
            i++;
            switch (fmt[i]) {
            case 'c':
                c = va_arg(arg_list, int);
                str[chars_printed++] = c;
                break;
            case '%':
                str[chars_printed++] = '%';
                break;
            case 's':
                str_arg = va_arg(arg_list, char *);
                len = strnlen(str_arg, max_size - chars_printed);
                strncpy(str+chars_printed, str_arg, len);
                chars_printed += len;
                break;
            case 'H':
                uppercase = 1;
            case 'h':
                base = 16;
            case 'd':
                num = va_arg(arg_list, int);
                len = int_to_str(num, str+chars_printed, max_size - chars_printed, base, uppercase);
                chars_printed += len;
                break;
            default:
                printf("Invalid format.\n");
                va_end(arg_list);
                return -1;
            }
        } else {
            str[chars_printed++] = fmt[i];
        }
    }

    if (chars_printed == max_size) chars_printed--;
    str[chars_printed] = 0;

    va_end(arg_list);
    return chars_printed;
}


texts: Checking if characters in a string can be rearranged to make a palindrome

texts:
Can I please have some advice on optimizing, cleaning up my code, and places where I could save space/time?

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

bool pal_perm(char*);
int main()
{
    printf("The output is %sa palindrome.\n", pal_perm("abbas")? "": "not "); //Output: The output is a palindrome.
    printf("The output is %sa palindrome.\n", pal_perm("deeds")? "": "not "); //Output: The output is a palindrome.
    printf("The output is %sa palindrome.\n", pal_perm("dead")? "": "not "); //Output: The output is not a palindrome.
    return 0;
}

bool pal_perm(char* str)
{
    char alpha[256];
    int oddCount =0;
    int size = strlen(str);
    memset(alpha, 0, sizeof(alpha));

    //see how many occurances of each letter
    for(char ch = 'a'; ch <= 'z'; ch++)
    {
        for(int i=0; i < size; i++)
        {
            if(str[i] == ch)
                alpha[str[i]]++;
        }
    }

    //count the number of times a letter only appears once
    for(int j=0; j<256; j++)
    {
        if(alpha[j] == 1 || (alpha[j]%2==1))
            oddCount++;

    }
    //if there is more than one letter that only occurs, then it
    //cannot be a palindrome.
    if(oddCount <= 1)
        return true;
    else
        return false;
}


texts: How to make my code with for/if loop more efficient in R

texts:
My code is structured so that I create an ellipse through my first three points of data. Then I go through each next row, and if the point falls outside the ellipse, I record the minimum distance between the point and ellipse. These points have datetime associated with it so I can only keep points 10 minutes old in my ellipse (so it doesn't get too big). The code works great until I have to process 100K+ of observations. Then the process time goes from minutes to hours. My question is, is there any part of my for loop portion of code that I can restructure to cut process time? I vectorized what I could (I think), and I know taking conditions out of for loop helps but now sure how to do it. Code below for reference. Any help is greatly appreciated.
library(sp)
library(cluster)
#create new empty column in dataframe
df$Distances <- NA

#get first three points and fit an ellipse around it
FlashPoints <- cbind(df$Lat[1:3],df$Long[1:3])
EllipseShape <- ellipsoidhull(FlashPoints)
EllipseShape

#get set of points that represent ellipse
EllipsePoints <- predict(EllipseShape)
EllipseGroup <- cbind(EllipsePoints[,2],EllipsePoints[,1])

#function to check if the next flashpoint (xp, yp) belongs to the ellipse with parameters a,b,... with tolerance eps
onEllipse <- function (xp, yp, a, b, x0, y0, alpha, eps=1e-3) {
  return(abs((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 - 1) <= eps)
}

#function to check if the point (xp, yp) is inside the ellipse with parameters a,b,...
insideEllipse <- function (xp, yp, a, b, x0, y0, alpha) {
  return((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 <= 1)
}

#loop from row 4 to last row
for (i in 4:nrow(df)){

#get location of next point
nextFlash <- cbind(df$Long[i],df$Lat[i])

#Establish/Re-establish parameters
xp <- df$Lat[i]
yp <- df$Long[i]
x0 <- EllipseShape$loc[1] # centroid locations
y0 <- EllipseShape$loc[2]
eg <- eigen(EllipseShape$cov)
axes <- sqrt(eg$values)
alpha <- atan(eg$vectors[1,1]/eg$vectors[2,1]) # angle of major axis with x axis
a <- sqrt(EllipseShape$d2) * axes[1]  # major axis length
b <- sqrt(EllipseShape$d2) * axes[2]  # minor axis length

#Check to see if next point is outside the ellipse, then get distance. If it is, add to distance list
if((insideEllipse(xp, yp, a, b, x0, y0, alpha)==FALSE) && onEllipse(xp, yp, a, b, x0, y0, alpha)==FALSE){
  nextDist <- min(spDistsN1(EllipseGroup, nextFlash, longlat = TRUE))
  df$Distances[i] <- nextDist

#Omit points 10 minutes old from group
  movingGroup <- subset(df[1:i,], difftime(df$DateTime[1:i],df$DateTime[i],units = "mins")<10)
  movingTstorm
  FlashPoints <- cbind(movingGroup$Lat[1:i],movingGroup$Long[1:i])
  FlashPoints

  #Fit an ellipse around flashpoints
  EllipseShape <- ellipsoidhull(FlashPoints)
  EllipseShape

  #Get set of points that make an ellipse
  EllipsePoints <- predict(EllipseShape)
  EllipseGroup <- cbind(EllipsePoints[,2],EllipsePoints[,1])
}

next(i)
}
}
```


texts: Editing HTML based on instructions in a data structure

texts:
My getExtend() function, which will be included via require.js, has two inputs and one output:

  HTML file content
  config object which determine how to update the HTML, for example to create new script (as the first object in the array
  extendedHtmlObject ) or update existing script content such as
  attributes values)
  the output should be the extended HTML with all the modifications.

Here is an example config object.
Please notice that that in the first element of the array (there is scenario which the next attribute is not provided which say to put the new script at the bottom) the next said put the script tag after script that have ID "ui-boot"

var extendedHtmlObject = [{
                    type: 'script',
                    action: 'new',
                    content: 'console.log(‘hello world’);',
                    next: "ui-boot"
                }, {
                    type: 'script',
                    id: "ui-boot",
                    action: 'upd',
                    innerElem: [{
                        type: 'attr',
                        id: 'data--ui-comersion',
                        content: '1.17'
                    }, {
                        type: 'attr',
                        id: 'src',
                        content: '/test/test2/-co.js'
                    }]
                }

This is the main function:

getExtend: function(htmlContent, extendedHtmlObject) {
    var self = this;
    if (extendedHtmlObject) {
        extendedHtmlObject.forEach(function(configs) {
            switch (configs.type) {
                case 'script':
                    htmlContent = self._handleScriptElement(htmlContent, configs);
                    break;
                case 'head':
                    break;
            }
        });
    }
    return htmlContent;
},

This method determines if I need to create a new script or update existing script attributes according to the input object

_handleScriptElement: function(htmlFilecontent, configEntry) {

    var oExtendedHTML = htmlFilecontent;
    switch (configEntry.action) {
        case 'new':
            oExtendedHTML = this._createNewScript(htmlFilecontent, configEntry);
            break;
        case 'upd':
            var sParsedHtml = this._htmlParser(oExtendedHTML);
            oExtendedHTML = this._updateScript(oExtendedHTML, configEntry, sParsedHtml);
            oExtendedHTML = this._convertHtmlBack(oExtendedHTML);
            break;
    }
    return oExtendedHTML;
},

This is the method for creating new script with two option

  the first fork need to parse the html
  the second for doesn't.

_createNewScript: function(htmlFilecontent, configEn) {
    var sScriptContent = this._createScript(configEntry.content);
    if (configEn.next != null) {
        var sParsedHtml = this._htmlParser(htmlFilecontent);
        $(sScriptContent).insertAfter(sParsedHtml.find('#' + configEn.next));
        htmlFilecontent = this._convertHtmlBack(sParsedHtml);
    } else {
     //when the script is at the end of file
        var iHeadEndTagPos = htmlFilecontent.search("(| )*</(| )*head(| )*>");
        htmlFilecontent = htmlFilecontent.substr(0, iHeadEndTagPos) + sNewScript + htmlFilecontent.substr(iHeadEndTagPos);
    }
    return htmlFilecontent;
},

This code is redundant(_htmlParser & _convertHtmlBack ) and not efficient(I'm fairly new to JS and use it inside the create and update), could I maybe improve it with JS prototype?
I want to do the parse just once in the start and the parseBack at the end(of looping the input object) but the problem is that in the createNewScript the second fork doesn't need to use the parser.

update
If I can improve this question and add more info please let me know how, Im really need the code review community help since the code should go to prod and I want it to be more efficient


texts: Reorder list such that each element is followed by the value closest to it

texts:
I just started playing with Python and was hoping to get some feedback regarding the quality of the following snippet. Does this look like proper Python? What would you change? Is this small script well structured?

Quick description of functional goal: reorder list such that each element is followed by the value closest to it, starting from 20 (AKA shortest-seek-first algorithm).

example:    [15, 24, 12, 13, 48, 56, 2]
becomes:    [24, 15, 13, 12, 2, 48, 56]

better example: [22, 19, 23, 18, 17, 16]
becomes: [19, 18, 17, 16, 22, 23]

fcfs_working = [15, 24, 12, 13, 48, 56, 2]
fcfs_track = []
track_number = 20
while len(fcfs_working) > 0:
    track_number = min(fcfs_working, key=lambda x:abs(x-track_number))
    fcfs_working.remove(track_number)
    fcfs_track.append(track_number)


texts: Taking and saving pictures using promises

texts:
I have the following 4 functions that work, however, I am sure that utilising promises will improve my code. I just find them so confusing.

$scope.takePictures = function() {

    document.addEventListener("deviceready", function() {

        var options = {
            quality: 75,
            destinationType: Camera.DestinationType.DATA_URL,
            sourceType: Camera.PictureSourceType.CAMERA,
            allowEdit: true,
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 200,
            targetHeight: 200,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: true
        };

        getImagesFromDevice(options);

    }, false);

}

$scope.getPictures = function() {

    var options = {
        quality: 50,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
        targetWidth: 200,
        targetHeight: 200
    };

    getImagesFromDevice(options);
}

var getImagesFromDevice = function(options) {
    $cordovaCamera.getPicture(options).then(function(imageData) {

        saveFileToParse(imageData);

    }, function(err) {
        // error
    });
}

var saveFileToParse = function(imageData) {
    var parseFile = new Parse.File("mypic.jpg", {
        base64: imageData
    });
    parseFile.save().then(function(response) {
        // The file has been saved to Parse.
        console.log(response._url);

        $scope.activeExercise.images.push(response._url);
        $scope.$apply();
        $scope.customImage = true;

    }, function(error) {
        // The file either could not be read, or could not be saved to Parse.
    });
}

It would be fantastic if someone can improve the above code but further explain the pitfalls in how I have coded it and how it can be improved. If you are able to force a promise explanation in my head that would be great too!


texts: Check if a type is of any from a list of types?

texts:
I need to check whether a generic type parameter is in a set of valid types and have created extension methods to do a run time check:

public static bool Is(this Type type, params Type[] types) {
  return types.Any(t => t == type);
}

public static bool Is<T1>(this Type type) {
  return type.Is(typeof (T1));
}

public static bool Is<T1, T2>(this Type type) {
  return type.Is(typeof (T1), typeof (T2));
}

With additional methods for T3 - T#...

Usage (in constructor for the generic class):

if(!typeof(T).Is<Int32, String, Boolean, CustomClass, Whatever>())
    throw new ArgumentException("T must be a type.");

But I would prefer a compile time check (which I don't believe is possible). Failing that, any suggestions on improvements are appreciated.


texts: Sieve of Eratosthenes - Standard and Optimized implementation

texts:
I am a Java developer who is taking Python for the first time.

I'm sure this is not at all elegant since I am thinking more in C syntax.

"""
This module contains two implementations of the algorithm Sieve of
Eratosthenes.
"""

# import ############################################################### import #
import math
import numpy
#
 # fun1 ################################################################# fun1 #
def SieveBasic(n):
 """
 This function runs the basic sieve of eratosthenis algorithm (non-optimized)
 and returns a list of prime numbers. The algorithm is implemented as described @:
 http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Example

 """

 l = list(range(2, n+1))
 isPrime = [True] * (n-1)

 for m,n in enumerate(l):
     currentCheck = n
     for i,x in enumerate(l[m+1:]): #take each number and compare with later numbers
       if x % currentCheck == 0:
            isPrime[i+m+1] = False

 primes = [0,1]
 for i,x in enumerate(isPrime):
     if x==True:
         primes.append(2+i)

 return primes

 """
 This function generates a list of Js required for optimized sieve of eratosthenis algorithm.

 """
def generateJs(i,n):
    j=i**2
    if j<n:
        yield j

    while j+i<=n:
        j+=i
        yield j

def SieveOptimized(n):
 """
 This function runs the optimized sieve of eratosthenis algorithm
 and returns a list of prime numbers. The algorithm is implemented as described @:
 http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation

 """
 l = list(range(2, n+1))
 isPrime = [True] * (n+1)
 maxChk = math.sqrt(n)

 for q,r in enumerate(l):
    if r>maxChk:
        break

    for z in generateJs(r,n):
       isPrime[z] = False

 return numpy.where(isPrime)[0] # how cool is this


texts:
I am solving problem GRAVITY on SPOJ. Each test case is a rectangular ASCII grid of dimensions m × n, and you have to determine whether it is possible to find a path from the 'S' square to the 'T' square, moving using the space squares and avoiding '#' obstacles, in at most O steps (diagonal steps allowed).

I am using normal BFS but I am getting TLE. The time limit is 2 sec and my code should easily run within this limit.

#include <bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair <int , int > pii;

#define INF (1000000000)
#define ull unsigned long long
#define s(n) scanf("%d",&n)
#define s2(a,b) scanf("%d %d",&a,&b)
#define s3(a,b,c) scanf("%d %d %d",&a,&b,&c)

int O,m,n;
int dr[]={0,0,-1,1,1,1,-1,-1}; //right,left,up,down,down-right,down-left,up-right,up-left
int dc[]={1,-1,0,0,1,-1,1,-1};
int inRange(int a,int b){ if(a>=0 && a<m && b>=0 && b<n) return 1;return 0;}

char arr[101][101];map <pii,int > dist;

int bfs(int a,int b)
{
    queue <pii> q;
    dist[pii(a,b)]=0;
    q.push(pii(a,b));
    while(!q.empty())
    {
        pii front=q.front();q.pop();
        a=front.first;b=front.second;
        for(int i=0;i<8;i++)
        {
            int x=a+dr[i],y=b+dc[i];

            if(inRange(x,y) && arr[x][y]!='#' && dist[pii(x,y)]==INF)
            {
                dist[pii(x,y)]=dist[pii(a,b)]+1;
                q.push(pii(x,y));
            }
            if(inRange(x,y) && arr[x][y]=='T')
            {
                dist[pii(x,y)]=dist[pii(a,b)]+1;
                return dist[pii(x,y)];
            }
        }
    }
    return INF;
}

int main()
{
    int t;
    s(t);
    while(t--)
    {

        int Sx=-1,Sy=-1,Tx=-1,Ty=-1;
        s3(O,m,n);
        char ch;
        scanf("%c",&ch);    //for end of line character

        dist.clear();
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                scanf("%c",&ch);
                arr[i][j]=ch;
                dist[pii(i,j)]=INF;
                if(arr[i][j]=='S')
                    Sx=i,Sy=j;
                if(arr[i][j]=='T')
                    Tx=i,Ty=j;
            }
            scanf("%c",&ch);   //for end of line character
        }

        if(Sx==-1 || Sy==-1 || Tx==-1 || Ty==-1)
        {
            printf("Impossible\n");
            continue;
        }
        int val=bfs(Sx,Sy);
        if(val <= O)
            printf("Possible\n");
        else
             printf("Impossible\n");
    }
    return 0;
}


texts: follow-up review of a custom Undo Manager

texts:
This is a follow up review of question 'a custom Undo Manager'.

After reviewing all the comments and answers, my code has been revised (completely rewritten) based on the review.

Summary

The intent of the code is to provide a means to keep track of events in c#. Each Action has an undo and redo event (Command) and is pushed onto a redo or undo Stack<Command>. An object can create an instance of the StateManager, which should be private in order keep the undo and redo events encapsulated. For example purposes, I created a class called Car, which has a property of type StateManager which handles all the events. Your comments and suggestions are appreciated.

public interface ICommand
{
    // Executes this command.
    void Execute();

    // Undoes this command.
    void Undo();
}

/// <summary>
/// The Command class holds a reference to an Event and the Undo Event
/// </summary>
public class Command:ICommand
{
    private readonly Action _action;
    private readonly Action _undoAction;

    public Command(Action action, Action undoAction)
    {
        _undoAction = undoAction;
        _action = action;
    }

    public void Execute()
    {
        _action();
    }

    public void Undo()
    {
        _undoAction();
    }

}

public interface IStateManager
{
    // Executes the specified commmand and adds it to the Undo stack.
    void ChangeState(Command commmand);

    // Undoes the last command in the Undo stack.
    void RestorePreviousState();

    // Redoes the last command in the Redo stack.
    void RedoPreviousState();
}

public class StateManager:IStateManager
{
    private Stack<Command> _undoCommands = new Stack<Command>();
    private Stack<Command> _redoCommands = new Stack<Command>();

    public void ChangeState(Command command)
    {
        command.Execute();
        _undoCommands.Push(command);
    }

    public void RestorePreviousState()
    {
        if (this._undoCommands.Any()) {

            var command = _undoCommands.Pop();
            command.Undo();
            _redoCommands.Clear();// clear the redo stack
            _redoCommands.Push(command);// push event on redo stack
        }

    }

    public void RedoPreviousState() {

        if (this._redoCommands.Any())
        {
            var commandPop = this._redoCommands.Pop();
            commandPop.Execute();
            this._undoCommands.Push(commandPop);  // put the event on the undo stack

        }
    }
}

public class Car
{
    /// <summary>
    /// StateManager - manages the state of properties/methods that call  StateManager.ChangeState.
    /// The StateManager is set to private for encapsulated - The State of the object is only handled
    /// by the object that instantiates it.
    /// </summary>
    private StateManager _manager { get; set; }

    private String color;

    public String Color
    {
        get { return color; }
        set {
            string currentValue = color;
            _manager.ChangeState(new Command(() => color = value,
                                                    () => color = currentValue));
        }
    }
    public Car()
    {
        _manager = new StateManager();
    }

    /// <summary>
    /// Undo the last event.
    /// </summary>
    public void Undo() {

        _manager.RestorePreviousState();
    }

    /// <summary>
    /// Redo the last event
    /// </summary>
    public void Redo()
    {
        _manager.RedoPreviousState();
    }

}


texts: Webshop Conversion - Binary testing is not even

texts:
Everytime a new visitor comes to my webshop I write a cookie (1d) which sets a session entry with mt_rand(1,2) to A or B group.

if(empty($_GET["cltestuser"])) {
    if(empty($_COOKIE['cl_customergroup_test'])) {
        $cookieValue = "cl_use_default";
        if(mt_rand(1, 2) == 1) {
            $cookieValue = "A";
        } else {
            $cookieValue = "B";
        }
        setcookie("cl_customergroup_test", $cookieValue, time() + (86400 * 30)); //1 day
        $_COOKIE['cl_customergroup_test'] = $cookieValue;
    }

    $_SESSION["Customergroup"]->cl_testuser = $_COOKIE['cl_customergroup_test'];
} else {
    $cookieValue = strtoupper($_GET["cltestuser"]);
    setcookie("cl_customergroup_test", $cookieValue, time() + (86400 * 30)); //1 day
    $_COOKIE['cl_customergroup_test'] = $cookieValue;

    $_SESSION["Customergroup"]->cl_testuser = $_COOKIE['cl_customergroup_test'];

}

So the site is the same now for A and B visitors.
The testing sample is 15,000 visitors where 150 people bought goods.

(Note: 15,000 times in a for loop with the mt_rand(1,2) is nearly even (7500/7500))

But the conversion for B is about 30% higher then A.

When you have cookies blocked you cannot buy. There are no returning customers.

Is this breaking the law of the great numbers? Where does this come from?


texts:
I've created a basic cipher program that will turn your string into a Rot13 cipher. I'm pretty sure there are much easier ways to do this, so a little input on what I've done would be great:

What did I do well?
What can be done better?
Are there easier ways to do this?

using System;

namespace Rot13
{
    class CeasarCipher
    {
        static string Encrypt(string toEncrypt, int shift)
        {
            char[] buffer = toEncrypt.ToCharArray();

            for (int i = 0; i < buffer.Length; i++)
            {
                char letter = buffer[i];
                letter = (char)(letter + shift);

                if (letter > 'z')
                {
                    letter = (char)(letter - 26);
                }
                else if (letter < 'a')
                {
                    letter = (char)(letter + 26);
                }
                buffer[i] = letter;
            }
            return new string(buffer);
        }

        static void Main(string[] args)
        {
            Console.Write("Enter string to cipher: ");
            var toCipher = Console.ReadLine();

            Console.WriteLine(Encrypt(toCipher, 13));
        }
    }
}


texts: Find A Series of Numbers Who when Squared and Summed are equal to a given Square

texts:
I am working on a CodeWars titled 'Square into Squares. Protect trees!' it can be found here: https://www.codewars.com/kata/54eb33e5bc1a25440d000891/train/javascript

I have a working solution, the issue is that the performance is so horrid that if I run it with an argument higher than around 15 my browser/tab freezes. I would like some suggestions as towards how I could create a more efficient algorithm for this kind of problem, or just improve my current algorithm to be more performant.

Codewars times out as a result of its bad performance on the full test kit for the Kata. I am entirely certain that the issue is caused by calculating the square of every number beneath my argument number, but since I'm not particularly talented at math that was my procedural way of finding the correct values. I thought if I could find a way of eliminating many of the values before calculating their square that would solve the problem, but I haven't thought of a way yet.

let sol = []

function decompose(n) {
    sol = []
    let expMap = {}
    for(let i = 1; i < n; i++){
      expMap[i] = Math.pow(i, 2)
    }

    for(let prop in expMap){
      solutionFinder(prop, expMap, Math.pow(n, 2), [])
    }
    if(sol.length > 0) return sol
    return null
}

const solutionFinder = (val, set, currentValue, currentSet) => {
  const dataArr = [...currentSet]
  const dataClone = {...set}

  currentValue -= dataClone[val]
  dataArr.push(val)
  delete dataClone[val]

  if(currentValue < 0) return;

  if(!(currentValue === 0)){
    for(let prop in dataClone){
      solutionFinder(prop, dataClone, currentValue, dataArr)
    }
  }

  if(currentValue === 0){
    if(sol.length === 0 || arrSum(sol) < arrSum(currentSet)){
      sol = dataArr.map(i => parseInt(i)).sort((a, b) => a - b)
      return
    }
  }

  return
}

const arrSum = arr => arr.reduce((a,b) => a + b, 0)

I am relatively new to programming (Started in February), and still struggle with developing algorithms with good time complexity, any advice about how to make this algorithm more efficient or an algorithm that would work better for this job would be welcome.


texts:
The task
is taken from leetcode

  Given n non-negative integers a1, a2, ..., an , where each represents
  a point at coordinate (i, ai). n vertical lines are drawn such that
  the two endpoints of line i is at (i, ai) and (i, 0). Find two lines,
  which together with x-axis forms a container, such that the container
  contains the most water.

  Note: You may not slant the container and n is at least 2.

My first solution:

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = height => {
  let max = 0;
  height.forEach((hL, i) => {
    height.slice(i + 1).forEach((hR, j) => {
      max = Math.max(max, Math.min(hL, hR) * (1 + j));
    });
  });
  return max;
};

My second solution:

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea2 = height => {
  let l = max = 0;
  let r = height.length - 1;
  while (l < r) {
    const area = Math.min(height[l], height[r]) * (r - l);
    if (height[l] > height[r]) {
      r--;
    } else {
      l++;
    }
    max = Math.max(max, area);
  }
  return max;
};

Is it possible to solve it mathematically and make it faster?


texts: Convert data frame to list of lists by row

texts:
I am rewriting some old code where I take a dataframe in r and convert it using the tidyverse packages to a list of lists, where each element is one row of the original dataframe - which is itself a list with each column an element.

My previous function achieved it like so:

library(tidyverse)

feat <- function(coords, height = 20, vjust = 75,  fill = "orange"){
  inst <- purrr::flatten(purrr::by_row(coords, ..f = function(x)
    rec <- list(type = "rect",
                x = as.numeric(x[1]),
                y = vjust,
                width = as.numeric(x[2]-x[1]),
                height = height,
                fill = fill),
    .labels = FALSE))
  return(inst)
}

However by_row() has been depreciated from the purrr package and so I would like to rewrite it. This is my attempt:

feat2 <- function(coords, height = 20, vjust = 75,  fill = "orange"){
  inst <- coords %>%
    mutate(type = "rect",
           x = as.numeric(start),
           y = vjust,
           width = as.numeric(end-start),
           height = height,
           fill = fill) %>%
    select(-start, -end) %>%
    mutate(count = 1:n()) %>%
    nest(-count) %>%
    select(-count) %>%
    mutate(data = map(data, ~ flatten(.x))) %>% pull()
  return(inst)
}

which does the job but I feel there should be a quicker, more elegant way to achieve this. Do you have any ideas on that aspect?

Here is an example data set:

coords <- structure(list(start = c(126, 433, 603, 1604), end = c(327, 495,
644, 1831)), .Names = c("start", "end"), row.names = c(NA, -4L
), class = "data.frame")

and the desired output:

result <- list(structure(list(type = "rect", x = 126, y = 75, width = 201,
    height = 20, fill = "blue"), .Names = c("type", "x", "y",
"width", "height", "fill")), structure(list(type = "rect", x = 433,
    y = 75, width = 62, height = 20, fill = "blue"), .Names = c("type",
"x", "y", "width", "height", "fill")), structure(list(type = "rect",
    x = 603, y = 75, width = 41, height = 20, fill = "blue"), .Names = c("type",
"x", "y", "width", "height", "fill")), structure(list(type = "rect",
    x = 1604, y = 75, width = 227, height = 20, fill = "blue"), .Names = c("type",
"x", "y", "width", "height", "fill")))


texts: "Sherlock and the Beast" challenge in Java

texts:
I have been trying to solve the following problem on hackerrank.com, but when I submit the code it shows unsuccessful submission due to timeout. Can anyone help me out?

Sherlock and the Beast

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class test {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int t = in.nextInt();
    int a[] = new int[t];

    // reading test cases

    for( int i=0; i<t; i++){
        a[i] = in.nextInt();
    }

    int n = 0;  // length of decent string

    boolean break1 ; // for breaking 2 for loops after getting the output for each test case

    for( int i=0; i<t; i++){
        n = a[i];
        int testx = n/3;
        int testy = n/5;
        break1 = false;

        for( int x = testx; x >= 0; x--){

            for( int y = testy; y >= 0; y--){

                if( ( x==0 && y== 0 ) ){

                    System.out.println("-1");

                    break1 = true;
                    break;
                }

                else if ( n % (3*x+5*y) == 0){

                    System.out.println( getdecentString(x, y) );

                    break1 = true;
                    break;

                }

            }

            if ( break1 == true)
                break;

        }
    }

}

// function to generate decentString

static String getdecentString(int x, int y){
    String decentString = "";
    x = 3*x;
    y = 5*y;

    for( int j=1; j <= x; j++)
        decentString =  decentString + "5";

    for( int k=1; k <= y; k++)
        decentString =  decentString + "3";

    return decentString;

}

}


texts:
I am working my way through some exercises, using Java, to learn about programming. I have just finished the following Code Golf challenge:

  Here is some example input, so I can explain what the problem is:

  ((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))

  Think of this line of text as a topographic map of some mountains. Each set of parentheses illustrates one unit of altitude.

  If we "view" this from the side, so that we see the mountains vertically, we will see:

           4 5                cherries    woohoo
  1 2  3       moo       lik          e
                      i

  Given one of these topographic maps, output the map, but on a vertical scale, like the output above. Separate the different items in the map with the number of characters to the next item. For example, there are 4 spaces in the output between moo and i. Likewise, there are 4 characters in the input between moo and i.

As a beginner, I am certainly not aiming to fulfill the challenge of the fewest characters. I'm merely trying to learn. I haven't looked at any other answers yet in case it puts me off posting this for feedback. So, here is my code:

public static String getLevelContent(String str, int count){

    int levelToPrint = 0;
    int spaceCount = -1;

    StringBuilder s = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {

        spaceCount++;

        if (str.charAt(i) == '(') {
            levelToPrint++;
        }

        if (str.charAt(i) == ')') {
            levelToPrint--;
        }

        if (levelToPrint == count && str.charAt(i) != '(' && str.charAt(i) != ')') {

            for (int j = 0; j < spaceCount; j++) {
                s.append(" ");
            }

            spaceCount = -1;
            s.append(str.charAt(i));

        }
    }
    return s.toString();
}

public static void printTopographic(String str){

    for (int i = 3; i >= 1; i--) {
        System.out.println(getLevelContent(str, i));
    }
}

public static void main(String[] args) {

    String str = "((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))";
    printTopographic(str);
}

Output:

           4 5                cherries    woohoo
  1 2  3       moo       lik          e
                      i

I am largely trying to better my efforts of structuring code. My questions are:

The reason I made getLevelContent a separate method is to avoid multiple for loops for each level of the output (3, 2, and 1). Is separating into methods, as I have done here, a good way to solve the problem?
In the printTopographic method, is the for loop more necessary, or more readable, than three separate lines, each calling separately on its own? (I suppose with this loop in place it would be more useful for dozens of lines as opposed to just three.)
Are there parts of my code which are just plain inefficient and should/would generally be written in a different way?
In projects like this, where I am simply testing what happens and how, I have completely gotten used to labeling static methods, pretty much out of laziness than anything else (for when calling from other methods). Is this a bad habit?


texts: Determine the longest segment of integers within an inclusive range that doesn't contain a bad number using Python

texts:
I am new to python.
Got a question in Hackerrank.
Given an Array of bad numbers and a range of integers, how can I determine the longest segment of integers within that inclusive range that doesn't contain a bad number?
For example, you are given the lower limit l = 3 and the upper limit r = 48, The array badNumbers = [37,7,22,15,49,60]. Segments without bad numbers are [3,6], [8,14], [16,21], [23,36] and [38,48]. The longest segment is [23,36] and it is 14 elements long.
Problem : Function Description Complete the function goodStatement in the editor below. The function must return an integer denoting the length of the longest contiguous range of natural number in the range l to r, inclusive, which does not include any bad numbers.
goodSegment has the following parameter(s): badNumbers[badNumbers[0],...badNumbers[n-1]]: an array of integers l: an integer, the lower bound, inclusive r: an integer, the upper bound, inclusive
Constraints \$1 \le n \le 10^5\$, \$1 \le badNumbers[i] \le 10^9\$, badNumbers contains distinct elements
def goodSegment(badNumbers, l, r):
    ranges = []
    subrange = []
    large=0
    for i in range(l,r+1):
        if badNumbers.count(i)==0:
            if len(subrange)==0:
                subrange.append(i)
            else:
                if i==r:
                    subrange.append(i)
                    ranges.append(subrange)
                    if len(range(subrange[0],subrange[1]+1))>large:
                        large=len(range(subrange[0],subrange[1]+1))
        else:
            if len(subrange)==1:
                subrange.append(i-1)
                ranges.append(subrange)
                if len(range(subrange[0],subrange[1]+1))>large:
                    large=len(range(subrange[0],subrange[1]+1))
                subrange=[]
            else:
                subrange=[]

    return large

badNumbers=[5,4,2,15]
l=1
r=10

result = goodSegment(badNumbers, l, r)
print(result)

The code is working fine. But this is not getting executed in 10 seconds as per the hackerrank test cases. How can I optimize this for a faster execution?


texts: Parsing a URL from a document and matching it from an array

texts:
I need help in improving this script that I have written to parse a URL and check it from an array.

This is what I have done till now: (fiddle)

This is working fine. Was this done correctly? What exactly I need is to search URLs in a list (ul) (which will be a domain specific), and then match if the URL is found in an array (array will have 500+ domains). If it is found then I need to append some text.

Is this function fine to use if there is a long list of domain names in a document and an array has 100+ domains?

Should I use regex to get the domain or is finding it from a CSS selector a good idea?

            Link 1

            Link 2

            Link 3

            Link 4

            Link 5

            Link 6

            Link 7

            Link 8

var arr = ['http://www.azaz.com', 'http://www.123.com'];
        $("#links li").each(function () {
        var aa = $(this).find('a').attr('href');
        var found = $.inArray(aa, arr) > -1;
        if(found === true){
            $(this).append("true");
        }
});


texts: Play audio files when buttons are clicked in Simon Says

texts:
function playGreen(){
       var audio = document.getElementById("audioG");
       audio.play();
                 }
  function playRed(){
       var audio = document.getElementById("audioR");
       audio.play();
                 }
  function playYellow(){
       var audio = document.getElementById("audioY");
       audio.play();
                 }
  function playBlue(){
       var audio = document.getElementById("audioB");
       audio.play();
                 }

It will function as is.. but it seems like I should be able to reduce the four function's into one with a variable? can I get some guidance on that, along with any other pointers too.. just starting on the pseudo logic for the rest of the javascript.

        <audio preload="auto"  id="audioG" data-pad="1">
          <source src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"/>
        </audio>

        <audio preload="auto"  id="audioR" data-pad="2">
          <source src="https://s3.amazonaws.com/freecodecamp/simonSound2.mp3" type="audio/mpeg"/>
        </audio>

        <audio preload="auto"  id="audioY" data-pad="3">
          <source src="https://s3.amazonaws.com/freecodecamp/simonSound3.mp3" type="audio/mpeg"/>
        </audio>

        <audio preload="auto"  id="audioB" data-pad="4">
          <source src="https://s3.amazonaws.com/freecodecamp/simonSound4.mp3" type="audio/mpeg"/>
        </audio>

Shall we
play a game?

https://codepen.io/TurtleWolf/pen/awdoxQ?editors=1010


texts: Python jinja2 filter to find hosts matching a group in ansible

texts:
I have a need to search for ansible inventory in the current play by group type and grabbing an arbitrary number of them.

I mostly want advice on if the _first_run variable is the best way to handle this inspection. I put it there so that a key error doesn't occur during the iterable creation.

Also, I'm unfamiliar with iterator speed in the real world. Is there any speed gain by putting the generator outside of the main function?

If you are unfamiliar with ansible's hostvars it is a dictionary of all the inventory. Each piece of inventory has the full list of groups so I can grab any arbitrary one.

I realize with strict inputs I could make this much simpler. I just wanted review on a situation where I had to support either input.

# This is what the top level input can be. In retrospect I could just
# force users to send me the full hostvars dictionary and simplify this
# and not accept arbitrary hosts (in this case 'a host'/'b host'.
# {'hostvars': {'a host': 'groups': {<the keys in here are what I want>}
#               'b host': 'groups': {<identical keys to the above>}
# }

def hosts_in_group(hostvars, active_hosts, group):
    """
    Return an iterable of all the hosts in a group.

    Example use case:
        Want a single host in group linux from the hosts in the current play ('ansible_play_hosts')
    Example usage:
        {{ hostvars|hosts_in_group(ansible_play_hosts, 'linux')|first }}

    :param hostvars: The full hostvars dictionary
    :param active_hosts: List of hosts to search. ex. ansible_play_hosts
    :param group: Group name to search ex. 'linux'
    :return: iterable of matching hosts
    """
    for hostname in hostvars.keys():
        hostvar = hostvars[hostname]
        break
    else:
        raise RuntimeError("No inventory found. Was hostvars the argument? Do you have inventory defined?")

    for host in active_hosts:
        if host in hostvar['groups'][group]:
            yield host

def _hosts_group_iterable(vars, active_hosts, group):
    """Iterable for hosts_in_group"""
    for host in active_hosts:
        if host in vars['groups'][group]:
            yield host

class FilterModule(object):
    def filters(self):
        return {
            'hosts_in_group': hosts_in_group,
        }


texts: Maximum subset sum with no adjacent elements

texts:
Write a function that takes an array of integers (Both Positive and negative) and return the maximum sum of non adjacent elements. Note that even if all values are negative, I don't have an option to choose empty subset and return sum as 0.
Recursive solution that I wrote:
public static int maxSubsetSumNoAdjacent(int[] array) {
  if (array.length == 0) return 0;
  else if (array.length == 1) return array[0];
  else if (array.length == 2) return Math.max(array[0], array[1]);

  return Math.max(
      array[0] + maxSubsetSumNoAdjacent(Arrays.copyOfRange(array, 2, array.length)),
      array[1] + maxSubsetSumNoAdjacent(Arrays.copyOfRange(array, 3, array.length))
  );
}

The recursive solution works. I've tried an iterative solution, but that didn't work.
Test cases
Positive Numbers:

75, 105, 120, 75, 90, 135
Ans : 330 (75 + 120  + 135)

Negative Numbers:

-1, -10, -10, -1, -2
Ans: -2 (-1 + -1)

I'd like a review of the code provided.


texts: Optimization - Prime Factorizations of Numbers <= 10^7

texts:
I am using Trail Division Method with a pre-calculated list of primes to calculate the prime factorization of all numbers less than M (M <= 10^7).

I am using an array of vectors of pairs.  The format for 10 is as follows:

PF[10][0].first = 2 // Base
PF[10][0].second = 1 // Exp
PF[10][1].first = 5
PF[10][1].second = 1

My approach is working fine but it is too slow.  For M=10^7 it took 36.841 sec to compute PF of all numbers <=M on my system.

Questions

Which is the best approach for this question?
For my approach what other optimizations can i do?

My code

#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include "math.h"
#include "stdio.h"
using namespace std;

const int lim=45000;
const int Max=10000000;
char prime[lim];

vector<pair <int,unsigned char> > PF[Max];

void prep()
{
    //Calculation of Prime Numbers
    for(int i=1;i<lim;prime[i++]=1);
    for(int i=2;i*i<lim;i++)
        if(prime[i])
            for(int j=i+i;j<lim;prime[j]=0,j+=i);

    for(int i=2;i<Max;i++) {
        int num=i;
        unsigned char pq=0;
        //Check for powers of 2
        while(num%2==0)  {
            pq++;
            num=num/2;
        }
        if(pq>0)
            PF[i].push_back( make_pair(2,pq) );
        int pan=num;
        //Loop for all primes j such that j*j<num
        for(int j=3;j*j<=num;j+=2) {
            if(prime[j]) {
                pq=0;
                while(num%j==0) {
                    pq++;
                    num=num/j;
                }
                if(pq>0)
                    PF[i].push_back( make_pair(j,pq) );
            }
        }
        if(num>1)
            PF[i].push_back( make_pair(num,1) );
    }
}

main()
{
    prep();
}

Timing

My Code

real    0m36.841s
user    0m36.624s
sys     0m0.265s

Igor ostrovsky Code

real    0m41.628s
user    0m41.390s
sys     0m0.265s


texts:
A class that keeps track of lines and columns in a text file. I use it in a parser so that when an error occurs, I can print out the line and column at which it occured.

Here's line col.hpp

#ifndef line_col_hpp
#define line_col_hpp

#include <cctype>
#include <cstdio>
#include <cassert>

///Keeps track of lines and columns in text.
///Great for writing error messages in parsers
class LineCol {
public:
  using LineType = unsigned int;
  using ColType = unsigned int;
  static const ColType SIZE_OF_TAB = 8;
  static const LineType FIRST_LINE = 1;
  static const ColType FIRST_COL = 1;

  explicit LineCol(LineType line = FIRST_LINE,
                   ColType  col  = FIRST_COL);

  ///Move line and col according to the char.
  ///Call this at the end of the loop with the char you just processed
  void update(char);
  ///This calls update(char) for each char in the null terminated string
  void update(const char *);
  ///This calls update(char) for the first n chars in the string
  void update(const char *, size_t);
  ///Sets line to FIRST_LINE and col to FIRST_COL
  void reset();

  LineType getLine() const;
  ColType getCol() const;
  const char *getStr() const;
private:
  LineType line;
  ColType col;
};

#endif

Here's line col.cpp

#include "line col.hpp"

LineCol::LineCol(LineType line, ColType col)
  : line(line), col(col) {
  assert(line >= FIRST_LINE);
  assert(col >= FIRST_COL);
}

void LineCol::update(char c) {
  switch (c) {
    case '\t':
      col += SIZE_OF_TAB;
      break;
    case '\n':
      line++;
      col = FIRST_COL;
      break;
    //vertical tab and form feed do the same thing on my system
    case '\v':
    case '\f':
      line++;
      break;
    case '\r':
      col = FIRST_COL;
      break;
    case '\b':
      //backspace doesn't move up lines
      //when backspacing tabs it treats them as spaces so it only
      //moves back one char
      if (col != FIRST_COL) {
        col--;
      }
      //i don't have to put a break here but should I even though we'll
      //fallthrough to another break?
    case '\0':
    case EOF:
      break;

    default:
      if (std::isprint(c)) {
        col++;
      }
  }
}

void LineCol::update(const char *str) {
  assert(str);
  while (*str) {
    update(*str);
    str++;
  }
}

void LineCol::update(const char *str, size_t size) {
  assert(str);
  while (size) {
    update(*str);
    str++;
    size--;
  }
}

void LineCol::reset() {
  line = FIRST_LINE;
  col = FIRST_COL;
}

LineCol::LineType LineCol::getLine() const {
  return line;
}

LineCol::ColType LineCol::getCol() const {
  return col;
}

const char *LineCol::getStr() const {
  //The largest 64 bit integer value is 18446744073709551615 which is
  //20 characters. 20 + ':' + 20 + '\0' = 42
  static char str[42];
  std::snprintf(str, 42, "%u:%u", line, col);
  return str;
}

Heres an example of how the class is used.

const char *buf;
size_t size;
LineCol lc;
for (const char *c = buf; c < buf + size; c++) {
  //do stuff with the character
  //maybe print lc.getStr()
  lc.update(*c);
}

How could this be improved? Are there any special characters that I've missed?


texts: Replacing letters with numbers with its position in alphabet

texts:
If anything in the text isn't a letter, ignore it and don't return it.

  a being 1, b being 2, etc.

  As an example:

  alphabet_position("The sunset sets at twelve o' clock.") Should return
  "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3
  11" as a string.

It is my naive solution and my code is below in python 2.7

def alphabet_position(text):
    dictt = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8',
    'i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17',
    'r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'
    }
    arr = []
    new_text = text.lower()
    for i in list(new_text):
        for k, j in dictt.iteritems():
            if k == i:
                arr.append(j)
    return ' '.join(arr)


texts: Find all permutations in an array of string in ruby

texts:
I was at the job interview yesterday. And there is a question that asks me to find all the permutations in an array of string in ruby:

input: ['abc', 'cba', 'ab', 'ba', 'acbdef']
output: ['abc', 'cba',
'ab', 'ba']

Here is my implementation:
def find_permutation(arr)
  result = []
  arr.each do |element|
    next if result.include?(element.reverse)
    if arr.include?(element.reverse)
      result << element << element.reverse
    end
  end
  result
end

I am wondering if there is a better way to solve the problem in ruby since I don't think my solution is really 'pure' ruby.


texts:
Is pattern matching within a unit test a code smell?
Do I really need to throw an exception just for my test to fail if the function under test receives invalid arguments (i.e. not Succeeded case value)?

Here's my test:

[<Test>]
let ``get available positions for black soldier`` () =

    // Setup
    let piece = Black ( BlackSoldier , (1,5) )

    // Test
    let available = startGame () |> getPositions
                                 |> optionsFor piece
    // Verify
    match available with
    | OptionsResponse.Succeeded coordinates ->
        let northWestAvailable = coordinates |> List.exists (fun pos -> pos = (0,4))
        let northEastAvailable = coordinates |> List.exists (fun pos -> pos = (2,4))

        (northWestAvailable && northEastAvailable) |> should equal true

    | _ -> failwith "Failed to get options"

Here's the function under test:

let optionsFor piece positions =

    let duplicatesFound = positions |> Seq.countBy id
                                    |> Seq.map snd
                                    |> Seq.exists (fun count -> count > 1)
    if duplicatesFound
    then OptionsResponse.DuplicatesNotAllowed positions
    else match piece |> isKing with
         | false -> let options = positions |> availablePositions
                                            |> List.filter (optionsForSoldier piece)
                    OptionsResponse.Succeeded options

         | true  -> let options = positions |> availablePositions
                                            |> List.filter (optionsForKing piece)
                    OptionsResponse.Succeeded options

Appendix:

type Coordinate = int * int

type Space =
    | Occupied  of Piece
    | Available of Coordinate

type OptionsResponse =
    | DuplicatesNotAllowed of Space list
    | Succeeded            of Coordinate list


texts:
I needed this small function for one of my project.

Fetch Attributes

function fetchAttrs(node) {

  if (!node || !node.hasAttributes()) return {};
  var attrs = node.attributes;
  var res = {};
  var length = attrs.length;
  for (var i = 0; i < length; i++) {
    var attr = attrs[i];
    res[attr.name] = attr.value;
  }
  return res;
}

It's working fine as expected but I wanted to know if I am missing something from a performance point of view or good coding practices. Just need a second opinion :)

Update

How to handle exceptions, is it a good practice?


texts: Determine whether any permutation of a given array exists such that the sum of all subarrays of length K are equal

texts:
I was asked this question in an interview.

  You are given an array consisting of N integers. You need to determine whether any permutation of a given array exists such that the sum of all subarrays of length K are equal. N is divisible by K i.e. N mod K = 0.
  If the array is [1,2,1,3,2,3] and K = 2, it is False.
  If the array is [1,2,1,3,2,3] and K = 3, it is True.

My logic was this.

  If N == K, return True.
  Else store each of the distinct element in the array in a
  dictionary. If the number of distinct elements in the dictionary
  is greater than K, return False.
  Else store the count of each distinct element in the dictionary.
  If the count of any distinct element is less than (N/K), return False.
  Finally return True.

Here is my code in Python:

def check(nums, n, k):
if n == k:
    return True
else:
    my_dict = {}
    for i in nums:
        if i not in my_dict:
            my_dict[i] = 1
        else:
            my_dict[i] += 1
    if len(my_dict) > k:
        return False
    count = int(n/k)
    for i,j in my_dict.items():
        if j < count:
            return False
    return True

Am I doing the right approach ?


texts:
This is code that handles pushing data to an analytics API, and IMO it feels too much like Java.

logActivity is a method that uses Dispatch to POST the data to this API. I am worried that an exception could occur and that is why I wrapped the methods in a try/catch block. However, this feels very Javaesque.

Do I even need the try/catch block? Can logActivity method fail and cause the end point to stop working? Any better ways to do this?

  def buyLinkAnalytics(notif: Notification, reqInfo: RequestInfo): Unit = {
    try {
      logActivity(buy_link_requested, Some(LoggedInAccount(AccountId(notif.emails.get.to._id))), notif.productId.get._id.toString, None, reqInfo)
    } catch {
      case e: Exception => {
        log.error(e.toString)
      }
    }
}

  def productShareAnalytics(notif:Notification, reqInfo:RequestInfo): Unit = {
    try {
      logActivity(product_shared, Some(LoggedInAccount(AccountId(notif.emails.get.to._id))), notif.productId.get._id.toString, None, reqInfo)
    } catch {
      case e: Exception => {
        log.error(e.toString)
      }
    }
  }

  def welcomeAnalytics(notif:Notification, reqInfo:RequestInfo): Unit = {
    val uri = reqInfo.stripedUri
    try {
      logActivity(welcome, Some(LoggedInAccount(notif.accounts.get.from.get)), uri, None, reqInfo)
    } catch {
      case e: Exception => {
        log.error(e.toString)
      }
    }
  }

  def myCatalogAnalytics(notif:Notification, reqInfo:RequestInfo): Unit = {
    val uri = reqInfo.stripedUri
    try {
      logActivity(welcome, Some(LoggedInAccount(notif.accounts.get.from.get)), uri, None, reqInfo)
    } catch {
      case e: Exception => {
        log.error(e.toString)
      }
    }
  }

  def handleAnalytics(notif:Notification, reqInfo:RequestInfo) {
    notif.notification match {
      case BuyProduct => buyLinkAnalytics(notif, reqInfo)
      case ProductShare => productShareAnalytics(notif, reqInfo)
      case Welcome => welcomeAnalytics(notif, reqInfo)
      case MyCatalog => myCatalogAnalytics(notif, reqInfo)
      case _ => log.debug("Notification Type not found. Nothing put into analytics")
    }
  }

  def sendActivityLog[A] (account_id: String, activityLog: A, authParams: Map[String, String] = Map.empty[String, String], endpoint: String)(implicit fmt: Format[A]) = {
    val activityLogJson = Json.stringify (Json.toJson (activityLog))
    val scv = url(s"${config.getString("activity_log.url")}$endpoint/$account_id?key=wc_analytics") << activityLogJson <:< Map("Content-Type" -> "application/json") <:< authParams
    logger.debug(s"LOGGED: ${scv.url} << $activityLogJson")
    Http (scv OK as.String)
  }

  def logActivity (
    action      : String,
    visitor     : Option[Visitor],
    uri         : String,
    target_id   : Option[String],
    requestInfo : RequestInfo,
    context     : String = "-") = {
    import core.security.AppId.WcApp
    // In theory, no loggable business event should ever occur without an AppId.
    // But default to WC if we have to.

    val appId = requestInfo.appId.getOrElse (WcApp)._id

      val authParams = findAuthParams(requestInfo)

    if (visitor == None) {
      sendActivityLog ("None", ActivityLog (appId, action, uri, "-", context), authParams, activity_account)
    }
      visitor.foreach {
        case LoggedInAccountWithOther (account_id, other_id) =>
          sendActivityLog (
            account_id._id,
            ActivityLog (
              appId,
              action,
              uri,
              target_id.getOrElse (other_id._id),
              context
            ),
            authParams,
            activity_account
          )
        case v =>
          sendActivityLog (v.accountId._id, ActivityLog (appId, action, uri, "-", context), authParams, activity_account)
      }

  }


texts:
I have written a python script that has tallies representing digits 1-9 (0 is just ":" ) Unlike true Unary languages that are in the form 1^k. I represent values for n as per their decimal digits. The integer 121 is 1_11_1 Overall every k digit out of n "integer" is in Tally notation, and the amount of tallies is the sum of all the digits in a given n "integer" such as 121 = 4, 1_11_1 = 4.

Its called a many-one reduction. If you can transform Instance A(9,33,4) into Instance B(1111_1111 1, 111----111, 1111) in poly-time, then its NP-complete

Transformation rules is to just to enter each integer sequentially when asked in the while loop. Also, when your integer is a negative you do not give a "-" symbol for input. It will ask for input if its a negative integer.

Input

(9,33,4) "9, and then 33 and then 4. One at a time for each input."

Output

'111_1111 1' = 9

    111
33>>
    111

    11 11    =4

Algorithm for the Reduction

# This algorithm is very simple and inconsequential.
# It converts integers into a unary like language
# in poly time. All tallies are represented vertically.

print('If your integer is a negative, the script will ask.')
print("DO NOT GIVE -X integers for input!!!")
print('Script will output multiple - symbols for a negative integer transformation')

while 0 == 0:
  ask = input('Enter an integer from a subset-sum instance sequentially.')
  askStr = str(ask)
  res = list(map(int, str(askStr)))
  x = (res)
  asktwo = input('Is your integer a negative integer? y or n: ')
  if asktwo == str("y"):
     twinkle = str('-')
  else:
     twinkle = str(" ")
  for n in x:
      if n == 0:
       tallyone = ":"
       print(twinkle, tallyone)
      if n == 1:
       print(twinkle, "1")
      if n == 2:
       print(twinkle, "11")
      if n == 3:
       print(twinkle, "111")
      if n == 4:
       print(twinkle, "11 11")
      if n == 5:
       print(twinkle, "111 11")
      if n == 6:
       print(twinkle, "111 111")
      if n == 7:
       print(twinkle, "111_111 1")
      if n == 8:
       print(twinkle, "1111 1111")
      if n == 9:
       print(twinkle, "1111_1111 1")

 Question

In what way, is this code sloppy? Am I using while loops and variable names in an ugly way? Is my tallies in the print statements hard to read? What is the ugliest parts of my code and how would I improve them?

The code works. But, I don't know enough about python so what mistakes are you seeing in my code?


texts:
Explanation: Although merge sort runs in Ω(nlgn) and insertion sort runs in Ω(n^2), the constant factors in insertion sort can make it faster in implementation for small problem sizes.  This sorting implementation should still be stable.
Recursive Merge sort subroutine method:
private static void recursiveMergeSort(double[] arr, int lowerBound, int upperBound) {
    if (lowerBound < upperBound) {
        // Split the sub array into halves
        int mid = lowerBound + (upperBound - lowerBound) / 2;
        recursiveMergeSort(arr, lowerBound, mid);
        recursiveMergeSort(arr, mid + 1, upperBound);
        merge(arr, lowerBound, mid, upperBound);
    }
}

Merge method: *note-
I would like to replace the while loop with for and if-else statements.
private static void merge(double[] arr, int left, int mid, int right) {
    int i = 0, j = 0, k = left;
    //System.out.println("used merge");

    // Sizes of the temporary arrays to be copied
    int n1 = (mid - left) + 1;
    int n2 = (right - mid);

    // Create temporary arrays and copy data
    double[] leftTemp = Arrays.copyOfRange(arr, left, mid + 1);
    double[] rightTemp = Arrays.copyOfRange(arr, mid + 1, right + 1);

    // Merge the temp arrays back into arr[left...right]
    while (i < n1 && j < n2) {
        if (leftTemp[i] <= rightTemp[j]) {
            arr[k++] = leftTemp[i++];
        } else {
            arr[k++] = rightTemp[j++];
        }
    }

    // Copy remaining elements, if any
    while (i < n1) {
        arr[k++] = leftTemp[i++];
    }
    while (j < n2) {
        arr[k++] = rightTemp[j++];
    }
}

Insertion sort subroutine method:
private static void insertionSort(double[] arr, int left, int right){
    for (int i = left + 1; i <= right; i++) {
        double key = arr[i];
        int j = i - 1;

        while (j >= left && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

Hybrid merge/insertion sorting method:
Optimized is a value that is best set between [25,100]
private static void insertionRecursiveMergeSort(double[] arr, int left, int right) {
    // If <= OPTIMIZED use insertion sort subroutine
    if (right <= left + OPTIMIZED - 1) {
        insertionSort(arr, left, right);
    } else {
        int mid = left + (right - left) / 2;
        insertionRecursiveMergeSort(arr, left, mid);
        insertionRecursiveMergeSort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }
}

For test runs, I used array sizes 1M, 2M, 3M, and 5M with optimized set to 25, 50, 100, and 125.


texts:
In the Excel vba sub below, I need to insert the number of rows equal to variable j after row k.

So if j=17 and k=2 then I want 17 empty rows after row 2.

How can I improve this code?

sub stuck()
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim LastRow As Long
    Dim i As Long, z As Long
    Dim j As Long, k As Long, x As Long
    Dim rngtocopy As Range
    Dim rngFinal As Range
    Dim r As Range

    Set ws1 = Sheets("Calc")
    Set ws2 = Sheets("Dealer Orders")

    LastRow = ws1.Cells(ws1.Rows.Count, "E").End(xlUp).Row

    Set rngtocopy = ws1.Range("E2", ws1.Cells(LastRow, "F"))
    Set rngFinal = ws2.Range("K2", ws2.Cells(LastRow, "K"))

    j = ws1.Cells(ws1.Rows.Count, "E").End(xlUp).Row
    z = ws2.Cells(ws2.Rows.Count, "E").End(xlUp).Row
    k = 3
    x = 1
    Set r = Range("A" & k)
    Do While x < z
        With ws2
            If j > 0 Then
                  ws2.Range(("A" & k), ws2.Range("A" & k).Offset(j, 0)).EntireRow.Insert
                        Set r = Cells(r.Row + j, 1)

                        For i = 2 To rngtocopy.Rows.Count
                            With ws2.Range("K" & k)
                                .Offset(0, 0).Value = rngtocopy(i, 1)
                                .Offset(0, 1).Value = rngtocopy(i, 2)
                            End With
                        k = k + 1
                        Next i
            End If
            k = k + 4
        End With
    x = x + 1
    Loop
    end sub


texts: Caml light and finding the prime factors

texts:
I wrote the following Caml light code to find prime factors of a number (part of an early Project Euler question).

  Largest prime factor

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143?

let rec find_factors target check =
if (check > (int_of_float (sqrt (float_of_int target)))) then [] else
        (find_factors target (check+1))@if target mod check == 0 then
[ check; (target/check)] else[] ;;

let display n =
print_int n;print_newline();;

do_list display (find_factors 10 1);
print_newline();;

I'm very new to functional programming and I suspect I'm all over the place - if anyone would like to give me some tips that would be ideal. :)


texts: Is it good practice in Java to pass a StringBuffer to a method to get error messages

texts:
I have a class that has a method which takes a user as an argument and performs several validation checks on the user and returns a boolean to indicate if theyare valid.

I want to be able to get error messages back from the validation method along with the boolean return value.

I was thinking of doing it by passing a StringBuffer as an argument along with the user and in the validation code appending error messages to the buffer so that the caller gets the boolean returned and then can look at the StringBuffer for error messages.

// validation class
public boolean validateUser(User user, StringBuffer errors) {
    ...
}

// caller
StringBuffer errors = new StringBuffer();
boolean validUser = validateUser(user, errors);
if (!validUser) {
    log(errors.toString();
}

Is this good practice in Java?  Or would it be better to log the errors to a buffer in the validation class and have a public method to get the errors?  Or should the validateUser() method return an object that contains the boolean and errors?

Thank you!


texts: Simple c# for-loop program for calculating theoretical earnings from investing (beginner)

texts:
I am new to programming and "programming thinking" as well. I have created a simple program that calculates future earnings from investing. It seems to be working correctly, but I want to be sure and ask some smarter guy out here, whether the program is really working as it should or whether it could be written in a better and cleaner form. Input in first month is 15000, Other months: 1000, End of time period, when I want to see the earnings: 72 months, growth/month: 0.75 %; Each new input grows every month by its 0.75 %

static void Main(string[] args)
        {
            double inpInt, inpMonth, inpMonthTrue, growMonth, monthCount, sum, inpTotal, earnTotal;
            inpInt = 15000;
            inpMonth = 0;
            inpMonthTrue = 1000;
            growMonth = 0.75;
            monthCount = 72;
            inpTotal = inpInt + inpMonthTrue * (monthCount - 1);
            sum = inpInt + inpMonth;
            inpInt += inpInt / 100 * 0.75;
            monthCount--;
            Console.WriteLine("Value in months:" );
            Console.WriteLine(inpInt);
            for (int i = 0; i < monthCount; i++)
            {
                inpMonth += inpMonthTrue;
                inpInt += inpInt / 100 * growMonth;
                inpMonth += inpMonth / 100 * growMonth;
                sum = inpInt + inpMonth;
                Console.WriteLine(sum);
            }
            earnTotal = sum - inpTotal;
            Console.WriteLine(String.Format("Total input: {0}", inpTotal));
            Console.WriteLine(String.Format("Total value: {0}", sum));
            Console.WriteLine(String.Format("Total earnings: {0}", earnTotal));
            Console.ReadLine();
        }

Thanks


texts: Program finds the first almost matching string in a list - Advent Of Code 2018 Day 2 Part 2

texts:
Advent of Code 2018, day 2, part 2:

  The [two IDs you are looking for] differ by exactly one character at the same position in both strings. For example, given the following IDs:

abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz

  The IDs fghij and fguij differ by exactly one character, the third (h and u). Those must be the correct IDs.

The code checks a list of strings to find two that match apart from a character at one position. So "abc" and "abz" would match.

I'm very green with Clojure, so feedback about any aspect of this code is appreciated.

(require 'clojure.set)

(def not-empty? (complement empty?))

(def input-lines (line-seq (clojure.java.io/reader "input.in")))

;; Given a string
;; Return a set of similar strings, with an asterisk replacing each character
;; eg "abc" gives #{[\* b c] [a \* c] [a b \*]}
(defn get-match-patterns [id]
  (set (map #(assoc (vec id) % \*) (range (count id)))))

((fn [ids seen-patterns]
  (when (empty? ids)
    (throw (Exception. "Didn't find match")))

  (let [[next-id & other-ids] ids
        match-patterns (get-match-patterns next-id)
        matches (clojure.set/intersection match-patterns seen-patterns)]
    (if (not-empty? matches)
      (prn (apply str (filter #(not= \* %) (first matches))))
      (recur other-ids (apply conj seen-patterns match-patterns))))) input-lines #{})

Sample input:

abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz

Sample output:

fgij


texts: Filtering a recursive directory listing, discarding subfolders

texts:
I needed a function that would take a list of folders and removed all sub folders, so that only the top level folders stayed in the list.

For example, given the list:

c:\stuf\morestuff
c:\stuf\morestuff\sub1
c:\otherstuf
c:\otherstuf\sub1
c:\otherstuf\sub2

I wanted the list to be reduced to:

c:\stuf\morestuff
c:\otherstuf

So I came up with this solution:

// remove empty strings and sub folders
private static void CleanUpFolders(List<string> uniqueFolders)
{
    uniqueFolders.RemoveAll(
        delegate(string curFolder)
        {
            // remove empty
            if (string.IsNullOrEmpty(curFolder))
                return true;

            // remove sub paths
            if (uniqueFolders.Exists(
                delegate(string s)
                {
                    if (!string.IsNullOrEmpty(s) &&
                        curFolder.StartsWith(s) &&
                        string.Compare(s, curFolder) != 0)
                        return true;
                    return false;
                } ))
                return true;

            return false;
        }
    );
}

This seems to work (not very well tested though) but I was left wondering about some things:

is there an issue with using variables inside anonymous methods that were declared outside?
any potential issues with nested anonymous methods?
any other issues or best practices worth mentioning?