texts: Text reading and string inputting program

texts:
The Main program. This program pulls from a .txt document with two separate strings, and outputs a  .cs program that will display those two string via console when run. It uses a structure.txt file for the code it inputs the strings into.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication3
{
class Program
{
    static void Main(string[] args)
    {

        //structure.txt contains the program we will enter our values into.
        String filePath = "Structure.txt";

        WriteToFile(filePath);

    }

    public static void WriteToFile(string filePath)
    {
        //create a string array to gather our text file information.

        StreamReader reader = new StreamReader(filePath);
        StreamReader info = new StreamReader("Structure.txt");

        StreamWriter writer = new StreamWriter("Hello.cs", true);
        String temp = String.Empty;

        while (!info.EndOfStream)
        {
            String tempstring = String.Empty;
            tempstring = reader.ReadLine();

            while (!reader.EndOfStream)
            {

                temp = reader.ReadLine();
                writer.WriteLine(temp);
                if (temp == "//break")
                {
                    writer.WriteLine($"String1 = {tempstring}");

                }
                else if (temp == "//break 2") {
                    writer.WriteLine($"String2 = {tempstring}");
                }

            }
        }
        reader.Close();
        info.Close();

        writer.Close();
    }

}
}

structure.txt is just a basic program that prints the two strings gathered from the main program unto the console.

using System;
namespace HelloWorld
{
class Hello
{
    static void Main()
    {
//break

//break 2

    Console.WriteLine(string1);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to continue.");
        Console.ReadKey();

    Console.WriteLine(string2);
    Console.ReadKey();
    }
}
//end
}

This program runs, but I am wanting to improve the code and increase its efficiency.


texts: Java reflection: Inject data generically and safely

texts:
I have become interested in reflection and I wrote a class to wrap an Object so that I can access its private instance fields. The code works great. I do not need to wory about the exceptions in the get() and set() methods because I cast the values appropriately through my wrappers accessor/mutators, but I was wondering if there is a better way of dealing with different types?

Example

public class Driver {
    public static void main(String... args) {
        Point p = new Point();

        System.out.printf("Point initialized: %s\n", p);

        PointDecorator mp = new PointDecorator(p);

        mp.setX(2);
        mp.setY(4);

        p = mp.getPoint();

        System.out.printf("Point updated:     %s\n", p);
    }
}

Output

Point initialized: (0, 0)
Point updated:     (2, 4)

As you can see, I have modified the Point Objects fields, although they are inaccessible through traditional method calls. I was able to bypass Java's typechecking which I find both neat and dangerous. Does this mean that anyone can just wrap another persons class, unless it is immutable, and inject data?

Point.java

public class Point {
    private int x, y;

    public Point() {
        this(0, 0);
    }

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public String toString() {
        return String.format("(%d, %d)", x, y);
    }
}

PointDecorator.java

import java.lang.reflect.Field;

public class PointDecorator extends Point {

     protected Point point;

    public PointDecorator(Point point) {
        this.point = point;
    }

    public void setX(int x) {
        set("x", x);
    }

    public int getX() {
        return (Integer) get("x");
    }

    public void setY(int y) {
        set("y", y);
    }

    public int getY() {
        return (Integer) get("y");
    }

    public Point getPoint() {
        return point;
    }

    protected Object get(String fieldName) {
        try {
            return field(fieldName).get(point);
        } catch (Exception e) { }

        return null;
    }

    protected void set(String fieldName, Object value) {
        try {
            field(fieldName).set(point, value);
        } catch (Exception e) { }
    }

    private Field field(String fieldName) {
        try {
            Field f = point.getClass().getDeclaredField(fieldName);
            f.setAccessible(true);
            return f;
        } catch (Exception e) { }

        return null;
    }
}


texts: Quicksort in JavaScript using destructuring and spread syntax

texts:
I'm learning Haskell, and there was quicksort implementation, so I thought that I could implement it in a similar way in JavaScript. The result:

const quicksort = ([x, ...xs], compareFn = (a, b) => a - b) => {
  // If x is undefined, the array is empty
  if (x === undefined) return [];
  const smallerSorted = quicksort(xs.filter(a => compareFn(a, x) <= 0), compareFn);
  const biggerSorted = quicksort(xs.filter(a => compareFn(a, x) > 0), compareFn);
  return [...smallerSorted, x, ...biggerSorted];
};

// Example usage:
console.log(quicksort(
  Array.from({ length: 10 }).map(_ => Math.floor(Math.random() * 100))
));

console.log(quicksort(
  Array.from('a quick brown fox jumped over a lazy dog'),
  (a, b) => a.charCodeAt(0) - b.charCodeAt(0)
).join(''));
.as-console-wrapper { max-height: 100% !important; }

I realize that calling filter() twice might be inefficient, so I made an alternative version, using the _.partition() function from Lodash:

const quicksort = ([x, ...xs], compareFn = (a, b) => a - b) => {
  // If x is undefined, the array is empty
  if (x === undefined) return [];
  const [smallerSorted, biggerSorted] = _.partition(
    xs,
    a => compareFn(a, x) <= 0
  ).map(arr => quicksort(arr, compareFn));
  return [...smallerSorted, x, ...biggerSorted];
};


texts: Converting Between Clojure Maps and Lists

texts:
In an attempt to learn better functional programing I've attempted to convert some Python to idiomatic Clojure, but I'm not sure how well I did with parts of it.

One thing I found myself doing a lot was destructuring a map into a list and then converting it back into a map as in the following example that takes a map of products and ratings (e.g. {:m1 3.5 :m2 2}) and a multiplier and multiplies each rating by the multiplier and returns a map with the corresponding products.

(defn corrected-prod [person multiplyer]
  (into {} (map (fn [[k v]] [k (* v multiplyer)]) person)))

Is there a better way to do this? For context you can reference the code on GitHub.


texts: Returning distinct characters in combined Strings

texts:
I am trying to return distinct characters from the combination of 2 Strings. The following is my solution which seems to work based on my tests.

Is there a more efficient way of going about this? I have converted the strings to arrays, to sets, to a StringBuilder and back to a String. I'm wondering if I have overcomplicated something which could have been resolved a lot simpler.

public String longest (String s1, String s2) {

    String[] s1Arr = s1.split("");
    String[] s2Arr = s2.split("");

    Set<String> arr1 = new HashSet<>(Arrays.asList(s1Arr));
    Set<String> arr2 = new HashSet<>(Arrays.asList(s2Arr));

    arr1.addAll(arr2);

    StringBuilder sb = new StringBuilder();
    Iterator<String> it = arr1.iterator();
    while (it.hasNext()){
        String element = it.next();
        sb.append(element);
    }

    return sb.toString();
}


texts: Weather Application - Reavling Module Pattern

texts:
I'm trying to practice and learn design patterns, and I decided to create a weather app using the revealing module pattern. How can I improve on this, and what mistakes did I make?

Main.js

import '../styles/main.scss';
import {weatherModule} from './weather';
import {dateModule} from './date';

dateModule.getCurrentDate();
weatherModule.render();

Weather.js

let weatherModule = (function() {

  let APPID = '09ca7c40368550f8e6a0a2851a56acd5';
  let dailyUrl = 'http://api.openweathermap.org/data/2.5/weather?';
  let weatherTemperature;
  let weatherLocation;
  let weatherDescription;

  function getPositionByGeolocation(lat, lon) {
    dailyUrl += 'lat=' + lat + '&lon=' + lon + '&APPID=' + APPID + '&units=metric';
    sendRequest(dailyUrl);
  }

  function sendRequest(url) {
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4 && xhr.status == 200) {
        let data = JSON.parse(xhr.responseText);
        let dailyWeather = {};
        dailyWeather.location = data.name;
        dailyWeather.temp = data.main.temp + ' &deg;C';
        dailyWeather.desc = data.weather[0].description;
        update(dailyWeather);
      }
    };
    xhr.open('GET', url, true);
    xhr.timeout = 5000;
    xhr.ontimeout = () => {
      let timeOutText = 'Request timed out';
      console.log('Current weather request timed out');
      document.getElementById('text--timeout').style = 'display: block';
      weatherLocation.innerHTML = timeOutText;
      weatherTemperature.innerHTML = timeOutText;
      weatherDescription.innerHTML = timeOutText;
    }
    xhr.send();
  }

  function update(dailyWeather) {
    weatherLocation.innerHTML = dailyWeather.location;
    weatherTemperature.innerHTML = dailyWeather.temp;
    weatherDescription.innerHTML = dailyWeather.desc;
  }

  function render() {
    window.onload = () => {
      weatherLocation = document.getElementById('weather-location');
      weatherTemperature = document.getElementById('weather-temperature');
      weatherDescription = document.getElementById('weather-description');

      if ("geolocation" in navigator) {
        function getPosition(position) {
          getPositionByGeolocation(position.coords.latitude, position.coords.longitude);
          document.getElementById('text--warning').style = 'display: hidden';
        }
        navigator.geolocation.getCurrentPosition(getPosition);
      }
      let geoLocationWarningText = "Your browser does not support geolocation. Pleae enable geolocation in your browser.";
      let geoLocationWarning = document.getElementById('text--warning');
      geoLocationWarning.innerHTML = geoLocationWarningText;
      document.getElementById('text--warning').style = 'display: block';
    }

  }

  return {
    render: render,
    sendRequest: sendRequest
  }

})();

export {weatherModule};

Date.js

let dateModule = (function() {

  let getCurrentDate = function() {

    let daysOfWeek = {
      0: 'Sunday',
      1: 'Monday',
      2: 'Tuesday',
      3: 'Wednesday',
      4: 'Thursday',
      5: 'Friday',
      6: 'Saturday'
    };

    let monthsInYear = {
      0: 'January',
      1: 'February',
      2: 'March',
      3: 'April',
      4: 'May',
      5: 'June',
      6: 'July',
      7: 'August',
      8: 'September',
      9: 'October',
      10: 'November',
      11: 'December'
    }
    let date = new Date();
    let dayOfWeek = date.getDay();
    let dayOfMonth = date.getDate();
    let month = date.getMonth();
    let year = date.getFullYear();

    let day = daysOfWeek[dayOfWeek] + ' ' + dayOfMonth + ' ' + monthsInYear[month] + ' ' + year;
    document.getElementById('current-date').innerHTML = day;

  }
  return {
    getCurrentDate: getCurrentDate
  }

})();

export {dateModule};


texts:
I was looking for a way to start elevated (i.e. administrator permissions) and/or invisible processes via batch in Windows. It turns out that this is kind of impossible with batch only, so I googled some vbs stuff and hacked it all together into a neat command line power utility.

The interface is as follows:

exec [/action: elevate, open, read, print] [/display: hide, show] exe [arguments]

/action defaults to open. /display defaults to show. exe is the path to an executeable, could be a script, image, whatever as well. arguments are applied to the exe.

Example: This starts a background node.js deamon with admin rights.

exec /action:elevate /display:hide node myDeamon.js

Everything works just fine, but I'm pretty sure that it's not perfect yet, as I basically have no idea about VBScript. I'd like to hear your opinions or ideas!

Set objShell = CreateObject("Shell.Application")

intOffset = 0

' get action
strAction = "open"
If (WScript.Arguments.Named.Exists("action")) Then
  intOffset = intOffset + 1
  Select Case WScript.Arguments.Named.Item("action")
        Case "elevate" strAction = "runas"
        Case "open" strAction = "open"
        Case "read" strAction = "read"
        Case "print" strAction = "print"
        Case Else strAction = "open"
    End Select
End If

' get display mode
intMode = 1
If (WScript.Arguments.Named.Exists("display")) Then
    intOffset = intOffset + 1
    Select Case WScript.Arguments.Named.Item("display")
        Case "0" intMode = 0
        Case "false" intMode = 0
        Case "hide" intMode = 0
        Case "hidden" intMode = 0
        Case Else intMode = 1
    End Select
End If

' get application to execute
strApplication = WScript.Arguments(intOffset)

' get arguments
strArguments = ""
For i = intOffset+1 To WScript.Arguments.Count-1
    strArguments = strArguments & WScript.Arguments(i)
Next

' execute application
If (WScript.Arguments.Count >= 1) Then
    objShell.ShellExecute strApplication, strArguments, "", strAction, intMode
Else
    WScript.Quit
End If

Gist


texts:
This just opens all drawing files in solidworks and saves as a *.pdf file. I just wanted to to get a second set of eyes on this before I let it go on the actual drawings database (i.e. all our files) and hopefully make sure it won't encounter any errors.

using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.IO;

namespace PDF.csproj
{
    public partial class SolidWorksMacro
    {

        public void Main()
        {
            string pdfPath;
            string Path = "C:\\Users\\SAFEROADS201\\Desktop\\01-VMS Trailer";
            string txtPath = Path + "\\UpdatedPDFs.txt";
            string Date = DateTime.Now.ToShortDateString();
            string[] drwPaths = System.IO.Directory.GetFiles(Path, "*.slddrw", SearchOption.AllDirectories);
            foreach (string s in drwPaths)
            {
                if (!s.Contains("~$"))
                {
                    ModelDoc2 swDoc = null;
                    int longstatus = 0;
                    int longwarnings = 0;
                    pdfPath = s;
                    pdfPath = pdfPath.Replace("Drawings", "PDFs").Replace("SLDDRW", "PDF");
                    (new FileInfo(pdfPath)).Directory.Create();
                    swDoc = ((ModelDoc2)(swApp.OpenDoc6(s, 3, 0, "", ref longstatus, ref longwarnings)));
                    longstatus = swDoc.SaveAs3(pdfPath, 0, 0);
                    swDoc = null;
                    swApp.CloseAllDocuments(true);
                }
            }
            System.IO.File.WriteAllText(txtPath, Date);
         }

        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}


texts: Classifying test data into several classes

texts:
The following code is to classify the test data into several classes:

function pdfmx = pdfparzen(train, test, winwidth)
% computes probability density for all classes
% using Parzen window approximation
% train - train set; the first column contains label
% used to  compute mean and variation for all classes
% test - test set (without labels)
% winwidth - width of the Parzen window
% pdfmx - matrix of probability density for all classes
%   class with label idx is stored in pdfmx(:,idx)
classnb = rows(unique(train(:,1)));
pdfmx = ones(rows(test), classnb);
for samp=1:rows(test)
for cl=1:classnb
clidx = train(:,1) == cl;
indiv = zeros(sum(train(:,1) == cl), columns(test));
for feat=1:columns(test)
indiv(:,feat) = normpdf(test(samp,feat),
train(clidx, feat + 1), winwidth);
end
pdfmx(samp,cl) = mean(prod(indiv,2));
end
end

Matlab command line usage:

ercf_parzen = bayescls(train, test, @pdfparzen, 0.25 * ones(1,4), 0.1);

Parzen classification error:

0.35581

How can I reduce the error coefficient of this code?

Training data: train.txt
Test data: test.txt

Driver Program

function errcf = bayescls(train, test, hpdf, apriori, winwidth)
% Bayes classifier
% train - training set; the first column contains label
% test - test set; the first column contains label
% hpdf - handle to function used to compute probability density
% apriori - row vector of a priori probabilities for all classes
% winwidth - window width (just for Parzen window hpdf function)
  clpdf = hpdf(train, test(:,2:end), winwidth);
  clpr = clpdf .* repmat(apriori, rows(test), 1);
  [val lab] = max(clpr, [], 2);
  errcf = mean(test(:,1) ~= lab);


texts: Google Foobar challenge: Rabbit Test Subjects

texts:
The diabolical Professor Boolean has captured you and a group of your
  hapless rabbit kin as test subjects for his terrible experiments!
  You're not sure what his real plans are, but currently it seems he's
  trying to make everyone faster and smarter? He's exposing rabbit test
  subjects to novel chemicals, genetic manipulations, and pathogens;
  then measuring their completion time for various puzzles and
  exercises. Then again, there's a rumor he's developing a kind of
  zombie rabbit. You don't want to become a zombit!

  Unfortunately, due to insubordination, and laziness, Professor Boolean
  just "eliminated" the lab assistant tracking all data from this
  research. Now, he's forcing you to sort through the notes and find
  something useful from the chaos. You have no choice but to abide by
  your captors evil rules. For now.

  Of the subjects that have survived, each has a distinct file, with
  anywhere from 1 to 100 measurements of completion time for the tests.
  The measurements from the before and after cases are listed
  separately, but the ordering has been mixed up. You have to figure out
  the degree of improvement (0% to 99%, rounded to the nearest whole
  number) based on the two lists of results.

  For example, if the first list of times is [22.2, 46, 100.8] and the
  second list is [23, 11.1, 50.4] you would return 50, because the times
  got 50% shorter: the 22.2 entry improved to 11.1, the 46 improved to
  23, and the 100.8 improved to 50.4. Even though the data points are in
  different order, each improves by the same amount.

  Write a function answer(x, y) which takes two lists of floating
  point performance scores and returns the improvement percentage,
  rounded to the nearest integer.

  Test cases:

  Inputs:

(double list) y = [1.0]
(double list) x = [1.0]

  Output:

(int) 0

  Inputs:

(double list) y = [2.2999999999999998, 15.0, 102.40000000000001, 3486.8000000000002]
(double list) x = [23.0, 150.0, 1024.0, 34868.0]

  Output:

(int) 90

The test cases are successful, but for some reason when I try to verify my answer, it says: There was a problem evaluating your code.

Is there a better way to solve this?

def answer(y,x):
    totalTime1 = 0
    totalTime2 = 0
    for time in x:
        totalTime1 += time
    for time in y:
        totalTime2 += time
    improvement = (1-(totalTime1 / totalTime2)) * 100
    return int(improvement)


texts: Most efficient way to insert into ordered sequence

texts:
I have a dashboard like interface, that can have many tabs. There can be as many or as few tabs as the user likes, with the user being allowed to re order them as they wish. Exactly like browsers do.

My problem is moving the tabs position, for example, look at these tabs:

[Sales] [Admin] [Finance] [Development]

If the user wants to move the [Development](index 3) tag to be after [Sales], giving it a new index of 1, how should I bump Finance and Development along to 2 and 3 respectively?

I am using JSON to store it so data.dashboard[0].sequence merely means the sequence value for the first dashboard.

At the moment I am using the following bit of code, which seems a bit hacky and not as efficient as it could be. The function is called with the start index(3 in this case) and the desired or end index (1 in this case). I've tried my best to explain with the comments, but feel free to ask anything you don't understand:

function changeSequence(start, end){
  var newVal = 999;
  for(d=0;d<data.dashboards.length;d++){
    if(data.dashboards[d].sequence == start){    // set [Development] to 999 temporarily
      data.dashboards[d].sequence = newVal;
    }
  }
  if(start > end){
    for(i=start; i>end; i--){
      var d = i;
      d--;
      for(j=0;j<data.dashboards.length;j++){     // if [Development] (index3) is after
        if(data.dashboards[j].sequence == d){    // [Admin] (index1), bump indexes
          data.dashboards[j].sequence = i;       // 1 and 2 along one (to 2 and 3)
        }
      }
    }
  } else {
    for(i=start; i<end; i++){
      var d = i;
      d++;
      for(j=0;j<data.dashboards.length;j++){     // else if [Development] (index3) is
        if(data.dashboards[j].sequence == d){    // before [Admin] (index1), which it
          data.dashboards[j].sequence = i;       // isn't in this case, bump them all
        }                                        // down one
      }
    }
  }
  for(d=0;d<data.dashboards.length;d++){
    if(data.dashboards[d].sequence == newVal){   // then set [Development]'s new
      data.dashboards[d].sequence = end;         // index to what its meant to be
    }
  }
}

This code works, but I feel like I've gone the long way and simply going from

[Sales] [Admin] [Finance] [Development]

to

[Sales] [Development] [Admin] [Finance]

Should be that hard

Edit: Still learning, so even unrelated ways to improve my code would be great


texts: Initiating Child ViewController from UIStoryBoard in iOS

texts:
I'm trying to use inheritance in UIViewController where base class has XIB in storyboard. I'm troubling with initiating different children classes with that XIB.
I cannot use XIB file separately instead of storyboard because it has static UITableViewCells.

So here is how I'm managing it currently using object_setClass method in SWIFT:
Parent Class:

class MeetingViewController: UITableViewController {

    private(set) var project: CDProject?
    private(set) var meeting: CDMeeting?

    static func initWith(project: CDProject?, meeting: CDMeeting?) -> MeetingViewController {
        let storyboard = UIStoryboard(name: "Meeting", bundle: nil)
        let meetingVC = storyboard.instantiateViewController(withIdentifier: "MeetingVCId") as! MeetingViewController
        meetingVC.project = project
        meetingVC.meeting = meeting
        return meetingVC
    }
}

Child Class-1:

class MeetingInfoViewController: MeetingViewController {

    static func initWith(meeting: CDMeeting) -> MeetingInfoViewController {
        let meetingVC = MeetingViewController.initWith(project: nil, meeting: meeting)
        object_setClass(meetingVC, MeetingInfoViewController.self)
        return meetingVC as! MeetingInfoViewController
    }
}

Child Class-2:

class MeetingCreateViewController: MeetingViewController {

    static func initWith(project: CDProject) -> MeetingCreateViewController {
        let meetingVC = MeetingViewController.initWith(project: project, meeting: nil)
        object_setClass(meetingVC, MeetingCreateViewController.self)
        return meetingVC as! MeetingCreateViewController
    }
}

This is working very fine, not any issue; but I'm just curious if:
1 there's any other way to handle this scenario?
2 this approach has any side-effects?
3 this can be improved somehow?

Also feel free to point out other things than initialisation!


texts: TextView vs Button for Android AlertDialog

texts:
I want to open an AlertDialog on the click of either a Button or TextView but I am not sure what would work best. When a selection is made in the AlertDialog, I want the bottom text to be updated with the selection. Here are the two options I have:

TextViews only. Here, the LinearLayout will have listener and will open AlertDialog.

<LinearLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Label" />

    <TextView
        android:id="@+id/selection"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginStart="5dp"
        android:textSize="18sp"
        android:text="Select..." />

</LinearLayout>

TextView and Button. Here, the Button will open the AlertDialog and the text inside the Button will be replaced with the selection.

<TextView
    android:id="@+id/label"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="5dp"
    android:layout_marginStart="5dp"
    android:text="Label"
    android:textSize="16sp"
    android:textColor="@android:color/white" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/label"
    android:layout_marginTop="-20dp"
    android:text="Select..."
    android:textAllCaps="false"
    android:textColor="@android:color/white"
    android:gravity="start|center_vertical"
    android:paddingLeft="15dp"
    android:paddingStart="15dp"
    android:paddingRight="15dp"
    android:paddingEnd="15dp"
    android:paddingTop="15dp"
    android:textSize="18sp"
    android:background="@android:color/transparent" />


texts: Starting a new transaction inside a single bean

texts:
I thinking of a way to start a new transaction inside a single EJB bean. Typical use case would be to process every item from a list in a separate transaction.

One way to do it would be to use UserTransaction:

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class ManagerBean implements Manager {
    @Resource
    private UserTransaction tx;

    @Override
    public void processAll(List<Object> list) throws Exception {
        for (Object obj : list) {
            tx.begin();
            try {
                processOne(obj);
                tx.commit();
            } catch (Exception ex) {
                tx.rollback();
            }
        }
    }

    private void processOne(Object obj) {
        /* ... */
    }
}

But I find it error prone to directly use commit() and rollback(). I'd prefer to leave transaction handing to the container. So I've come up with this pattern:

ManagerBean.java

@Stateless
public class ManagerBean implements Manager, ManagerInternal {
    @Resource
    private SessionContext context;

    @Override
    public void processAll(List<Object> list) {
        ManagerInternal txThis = context.getBusinessObject(ManagerInternal.class);
        for (Object obj : list) {
            txThis.processOne(obj);
        }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void processOne(Object obj) {
        /* ... */
    }
}

@Local
interface ManagerInternal {
    void processOne(Object obj);
}

Manager.java:

@Local
public interface Manager {
    void processAll(List<Object> list);
}

Though I'm unsure if it's ok to have package-private local interface. It works on JBoss 4.2, but I don't know about other app servers.
What do you think about this pattern?

Alternative using self-injection:

Instead of using SessionContext.getBusinessObject(interface) I suppose you can inject EJB into itself:

ManagerBean.java

@Stateless
public class ManagerBean implements Manager, ManagerInternal {
    @EJB
    private ManagerInternal txThis;

    @Override
    public void processAll(List<Object> list) {
        for (Object obj : list) {
            txThis.processOne(obj);
        }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void processOne(Object obj) {
        /* ... */
    }
}

@Local
interface ManagerInternal {
    void processOne(Object obj);
}

Manager.java stays the same.

EJB interfaces with package access seem to be not allowed by Wildfly.


texts: Standardizing Controller + Service method signatures

texts:
In my controllers, I have the following:

    [System.Web.Http.HttpPost]
    [Route("api/report")]
    public async Task<HttpResponseMessage> Report(ReportDto report)
    {
        await _profileService.SubmitReportAsync(User.Identity.Name, report);
        return Request.CreateResponse(HttpStatusCode.OK, true);
    }

Then in my service method (and in all service methods), I have the following:

public async Task<ApiResponseDto> SubmitReportAsync(string username, string ReportDto report)
{
    try // repeated
    {
       using (var db = new DbContext()) // repeated
       {
         // this is where the unique stuff is
       }
    }
    catch(Exception e){ // repeated
       HandleServiceLayerException();
    }
 }

My issue is that I'm repeating so much "signature" code in my service methods.  How can I simplify, keeping in mind that service methods have varying parameter signatures?


texts: User class for future inheritance in other programs involving user activity

texts:
I am making an user class which I could inherit and use in the future.
(recently started learning Python and OOP)

import mysql.connector as mycon
class user:
    host = "localhost"
    user = "root"
    password = "pass"
    database = "USERS"
    table = "UserData"

    def __init__(self,firstName,lastName,userName,email):
        self.firstName = firstName
        self.lastName = lastName
        self.userName = userName
        self.fullName = firstName + " " + lastName
        self.email = email

    @classmethod
    def login(cls,userName,password):
        db = mycon.connect(host = cls.host,user = cls.user,password = cls.password,database = cls.database)
        cursor = db.cursor()
        r=cursor.execute("SELECT * FROM {} WHERE UserName = '{}';".format(cls.table,userName))
        userInfo = cursor.fetchone()
        if(userInfo!=None):
            if(userInfo[2]==password):
                print("Login Successful")
                return cls(userInfo[0],userInfo[1],userInfo[3],userInfo[4])
            else:
                print("INVALID PASSWORD",password,userInfo[2])
        else:
            print("USER DOES NOT EXIST")
        db.close()

    @classmethod
    def register(cls,firstName,lastName,password,userName,email):
        db = mycon.connect(host = cls.host,user = cls.user,password = cls.password,database = cls.database)
        cursor = db.cursor()
        r=cursor.execute("Insert into {} values('{}','{}','{}','{}','{}');".format(cls.table,firstName,lastName,password,userName,email))
        db.commit()
        db.close()

with a table UserData with description


texts: Translating binary data from a file into a very large base-ten integer

texts:
I'm making an experimental Java algorithm that translates binary data from a file into a (very large) base ten integer. I am using BigInteger since this number may have millions of digits. I am trying to translate this number into a sum of powers of 2.

I tried this code, which theoretically works, but is sluggishly slow. Using this code for a 200000 digit number takes about 5 minutes to complete with my i5 @4.5GHz. The execution time for a number with over a billion digits could take a day or more.

How could I optimize this code so that the execution time is significantly lowered?

byte[] bytes = Files.readAllBytes(outFile.toPath());
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
        sb.append(String.format("%02X", b));
    }
    BigInteger dataInt = new BigInteger(sb.toString(), 16);
    BigInteger remainder = dataInt;
    double dataLength = dataInt.bitCount();
    while (dataLength > BASE.bitCount()) {
        int increment = (int) Math.round(Math.pow(dataLength, 1 / BASE.doubleValue()));
        BigInteger base = BASE;
        int exp = 2;
        while (base.compareTo(remainder) < 0) {
            base = BASE.pow(exp);
            exp += increment;
        }
        while (base.compareTo(remainder) > 0) {
            base = BASE.pow(exp);
            exp--;
        }
        remainder = remainder.subtract(base);
        dataLength = remainder.bitCount();
    }

In this case, the constant BASE is 2.


texts: How to handle same code parts in Factory Method?

texts:
I have classes:

public abstract class House{
   public string Name {set;get;}
   public SomeClass Property1 {set;get;}
   public OtherClass Property2 {set;get;}
}

public class WoodenHouse:House{
   public string WoodType {set;get;}
   public int WoodAge {set;get;}
}

public class StoneHouse:House{
  public string StoneType{set;get;}
}

And trying to create Factory Method patthern for this:

    abstract class Creator
    {
        public abstract HouseInfo Info { get; set; }

        public Creator()
        {
        }

        public abstract House FactoryMethod();
    }

    class WoodenHouseCreator : Creator
    {
        public override HouseInfo Info { get; set; }

        public WoodenHouseCreator(WoodenHouseInfo info)
        {
            Info = info;
        }

        public override House FactoryMethod()
        {
            var info = Info as WoodenHouseInfo;

            var woodenHouse = new WoodenHouse();
            woodenHouse.Name = info.Name;
            woodenHouse.Floors = info.Floors;
            woodenHouse.RoofType = info.RoofType;
            woodenHouse.WoodType = info.WoodType;
            woodenHouse.WoodAge = info.WoodAge;
            return woodenHouse;
        }
    }

    class StoneHouseCreator : Creator
    {
        public override HouseInfo Info { get; set; }

        public StoneHouseCreator(StoneHouseInfo info)
        {
            Info = info;
        }

        public override House FactoryMethod()
        {
            var info = Info as StoneHouseInfo;

            var stoneHouse = new StoneHouse();
            stoneHouse.Name = info.Name;
            stoneHouse.Floors = info.Floors;
            stoneHouse.RoofType = info.RoofType;
            stoneHouse.StoneType = info.StoneType;
            return stoneHouse;
        }
    }

Here is classes what contains information to create house:

    class HouseInfo
    {
        public string Name { set; get; }
        public int Floors { set; get; }
        public string RoofType { set; get; }
    }

    class WoodenHouseInfo : HouseInfo
    {
        public string WoodType { set; get; }
        public int WoodAge { set; get; }
    }

    class StoneHouseInfo : HouseInfo
    {
        public string StoneType { set; get; }
    }

And Usage:

        var houseInfo = new WoodenHouseInfo{
            Name = "HouseName",
            Floors = 2,
            RoofType = "Triangle",
            WoodType = "Pine",
            WoodAge = 100
        };

        House house;

        if(houseInfo is WoodenHouseInfo)
        {
            var creator = new WoodenHouseCreator(houseInfo);
            house = creator.FactoryMethod();
            Console.Write((house as WoodenHouse).WoodAge);
        }

Full code fiddle.

My problem that how to handle code duplication. I mean here is a lot of lines what fills base House object properties. How can i write that code only once?
Or i should not to use Factory Method?

Add Populator Class

class HousePopulator
    {
        public void PopulateHouse(HouseInfo info, House house)
        {
            house.Name = info.Name;
            house.Floors = info.Floors;
            house.RoofType = info.RoofType;
        }
    }

And usage:

abstract class Creator
{
    public abstract HouseInfo Info{get;set;}
    public HousePopulator HousePopulator {get;set;}
    public Creator()
    {
        HousePopulator = new HousePopulator();
    }
    public abstract House FactoryMethod();
}

class WoodenHouseCreator : Creator
{
    public override HouseInfo Info{get;set;}

    public WoodenHouseCreator(WoodenHouseInfo info)
    {
        Info = info;
    }
    public override House FactoryMethod()
    {
        var info = Info as WoodenHouseInfo;

        var woodenHouse = new WoodenHouse();
        HousePopulator.PopulateHouse(Info, woodenHouse);
        woodenHouse.WoodType = info.WoodType;
        woodenHouse.WoodAge = info.WoodAge;
        return woodenHouse;
    }
}


texts: A method to insert a database entry for a newly registered account

texts:
I've started to learn an OOP and I've built a class called accountactions, and I would like to know if I did a good job writing it.

The class is in the file: accountactions.class.php.

<?php

class accountactions(){

    public function register($login, $password, $email){

        //Zapisujemy dane wysłane formularzem
        $this->username = mysql_real_escape_string($login);
        $this->password = mysql_real_escape_string($password);
        $this->email = mysql_real_escape_string($email);

        //Hash password
        $this->password = md5(sha1($this->password));

        $db->simplequery("INSERT INTO radio_users(id, username, password, email) VALUES('', '$this->username', '$this->password', '$this->email')");

    }

}

?>

The register.php file:

<?php

    require_once("accountactions.class.php");

    $account = new accountactions();

    $account->register('samplelogin', 'samplepassword', 'sample@email');

?>

And I am having some issues with this fragment:

$db->simplequery("INSERT INTO radio_users(id, username, password, email) VALUES('', '$this->username', '$this->password', '$this->email')");

How do I join my db class to my account class?

I'd like to keep a model where I can do something like:

$account->register('$_POST['login']', '$_POST['password']', '$_POST['email']');

Unless there is a better way to do this.

Im newbie in OOP so any tips and guidelines are appreciated.


texts:
I'm trying to create my user.class.php constructor but I don't know really much about POO so I'm going to tell you what I'm doing and I hope you could help me.

user.class.php

class user {
    private $fullname;
    private $age;
    private $email;
    private $sex;
    private $nacionality;

        public function __construct($usrId){
            $mysqli = new connection_mysqli(); // I've already implemented this and it works.
            $query = "SELECT * FROM USERS WHERE USER_ID = $userId";
            if ($result = $mysqli->query($query)) {
               $userData = $result->fetch_assoc();
               $this->fullname = $userData['fullname'];
               $this->age = $userData['age'];
               $this->email = $userData['email'];
               //.....
            }
        parent::__construct($usrId);

    }
}

What I'm going to do on my index.php is this:

index.php

<?php
include('scripts/class/user.class.php');
$user = new user($_SESSION['userid'];
echo $user->fullname;
?>

So, is this going to work right? Is this well-programmed? Any tips?


texts:
I know Perl now has given and when to simulate switch/case statements, but these are still experimental and are not guaranteed to be in future versions.  Also there was a Switch module for Perl that existed in older versions, but it used source filtering and was considered not very good either so it went away.

Because of this, I decided to write my own module to simulate switch/case statements.

package Switch;

# Always use these
use strict;
use warnings;

# Imported modules
use Carp;

# Exporter
use Exporter qw(import);
our @EXPORT = qw(switch case break);

# Variable used to break out of the switch statement
my $BREAK;

sub switch {
    my $switch = shift;
    my @cases  = @_;

    # Check that each case has a function associated with it
    if (scalar @cases % 2) {
        croak "Invalid format in switch statement";
    }

    # Initialize BREAK
    $BREAK = 0;

    # Loop through each case
    while (my ($case, $code) = splice @cases, 0, 2) {

        # Check that $code is a code reference
        if (ref $code ne 'CODE') {
            $case = ref 'ARRAY' ? join ', ', @{$case} : $case;
            croak "case($case) does not have a valid function";
        }

        # Handle the default case
        if ($case eq 'default') { $code->(); next; }

        # Handle all other cases
        for (@{$case}) {
            $code->() if $_ eq $switch;
        }

        # Exit loop if BREAK is true
        last if $BREAK;
    }
}

# Construct an array reference of cases
sub case {
    return \@_;
}

# BREAK from the switch statement
sub break {
    $BREAK = 1;
}

1;

__END__

=head1 NAME

Switch - switch statements for Perl.

=head1 VERSION

$Revision: 1.1 $

=head1 SYNOPSIS

  use Switch;

  # Define a switch variable
  $switch = 3;

  # Implement a simple switch statement
  switch($switch,
      case(1)    => sub { print "\$switch = 1\n";      break; },
      case(2, 3) => sub { print "\$switch = 2 or 3\n";        },
      case(3)    => sub { print "\$switch = 3\n";      break; },
      default    => sub { print "default\n";                  },
  );

=head1 DESCRIPTION

The Switch module is designed to implement C-style switch statements in Perl.  The provided
switch variable will be tested against each case and will execute any/all matching cases until all
cases are tested or a break is encountered.

I have included some simple POD documentation that describes the usage.

To me the syntax looks quite elegant (it was the best I could do without using some sort of source filter myself).

What do you think?

What could be Improved?


texts: Return combined DTO from async controller

texts:
I have an asynchronous controller.
It is supposed to make a couple async calls then return combined data from then as one DTO.

[HttpGet("[action]/{name}")]
public async Task<CombinedDTO> GetSummonerData(string name)
{
    SummonerEndPoint endPoint = new SummonerEndPoint();
    SummonerDTO summonerData=  await endPoint.GetSummonerData(name);
    MatchesEndPoint endPoint2 = new MatchesEndPoint();
    MatchListDto matchesData =  await endPoint2.GetMatches(summonerData.accountId.ToString());
    return await TestMethod(summonerData, matchesData);
}
public async Task<CombinedDTO> TestMethod(SummonerDTO summonerData, MatchListDto matchData)
    {
         return await Task.Run(() => {
               return new CombinedDTO {
                    summoner = summonerData,
                    matches = matchData }; });
    }

Code above seems to be working but I am not sure is this is the best way to combining two DTOs into one.

for context endpoints:

public class SummonerEndPoint : BaseEndPoint
{
    public SummonerEndPoint() => Url = @"https://eun1.api.riotgames.com/lol/summoner/v3/summoners/by-name/";

    public async Task<SummonerDTO> GetSummonerData(string summonerName)
    {
        var data = await client.MakeAsyncRequest(url + summonerName).ConfigureAwait(false);
        return JsonConvert.DeserializeObject<SummonerDTO>(data);
    }
}

public class MatchesEndPoint : BaseEndPoint
    {
        public MatchesEndPoint() => Url = @"https://eun1.api.riotgames.com/lol/match/v3/matchlists/by-account/";
        public async Task<MatchListDto> GetMatches(string accountId)
        {
            var data = await client.MakeAsyncRequest(Url + accountId + "?beginIndex=0&endIndex=10").ConfigureAwait(false);
            return JsonConvert.DeserializeObject<MatchListDto>(data);
        }
    }

public class BaseEndPoint
    {
        protected string url;
        protected string Url { get => url; set => url = value; }
        protected RiotApiRequest client = new RiotApiRequest();
    }

public class RiotApiRequest : RiotApiRequestBase
    {
        public async Task<string> MakeAsyncRequest(string url)
        {
            using (var response = await MakeRequest(url).ConfigureAwait(false))
            {
                return await GetResponseContentAsync(response).ConfigureAwait(false);
            }
        }

        protected async Task<string> GetResponseContentAsync(HttpResponseMessage response)
        {
            using (response)
            using (var content = response.Content)
            {
                return await content.ReadAsStringAsync().ConfigureAwait(false);
            }
        }
    }

public class RiotApiRequestBase
    {
        protected async Task<HttpResponseMessage> MakeRequest(string url)
        {
            using( HttpClient client = new HttpClient())
            {
                //later this may be moved elsewhere ;)
                client.DefaultRequestHeaders.Add("X-Riot-Token", "Token");
                return await client.GetAsync(url).ConfigureAwait(false);

            }
        }
    }


texts: Batch script to start the service in a gap of 10 min

texts:
I have created a batch script to start the services in a gap of 10 min. My batch file will start the service on the local system and then will wait for 10 mins and starts the service on another system and then another. I have used the timeout command with nobreak statement which does not allows the user to stop the waiting time. If any changes need to be done, please suggest something.

@echo off
set timeout=600
set host1=Server_IP
set host1_service_name=swiftalm
set host2=Server_IP
set host2_service_name=swiftalm
set host3=Server_IP
set host3_service_name=swiftalm
set host4=Server_IP
set host4_service_name=swiftalm

echo ******Starting the Digite service on host1*****.
sc \\%host1% start %host1_service_name%
timeout /t %timeout% /nobreak
echo ******Starting the Digite service on host2*****.
sc \\%host2% start %host2_service_name%
timeout /t %timeout% /nobreak
echo ******Starting the Digite service on host3*****.
sc \\%host3% start %host3_service_name%
timeout /t %timeout% /nobreak
echo ******Starting the Digite service on host4*****.
sc \\%host4% start %host4_service_name%
timeout /t %timeout% /nobreak


texts: Styling android widgets programmatically

texts:
I have code which styles standard Android widgets programmatically (not from XML). The code is working, but I have this bunch of if instanceof else if instanceof block which is ugly.

I have read discussions on Stack Overflow, and my conclusion is instanceofis better on my case, but I'm not so sure, maybe I'm missing something?

public static void styleAllControls2(Context c, List<View> controls, CxpResources cxpr) {
    if (cxpr == null) {
        return;
    }
    File xfiles = c.getExternalFilesDir(null);
    if (xfiles == null) {
        Log.e(TAG, "couldnt get external files dir!");
        return;
    }
    Resources res = c.getResources();
    String filepath = xfiles.getAbsolutePath() + File.separator;
    for (View view : controls) {
        ViewModifier vModfr = null;
        if (view instanceof RatingBar) {
            // viewModifier = new RatingBarModifier(res, cxpr, filepath);
        } else if (view instanceof SeekBar) {
            vModfr = new SeekBarModifier(res, cxpr, filepath);
        } else if (view instanceof ProgressBar) {
            vModfr = new ProgressBarModifier(res, cxpr, filepath);
        } else if (view instanceof CheckBox) {
            vModfr = new CheckBoxModifier(res, cxpr, filepath);
        } else if (view instanceof RadioButton) {
            vModfr = new RadioButtonModifier(res, cxpr, filepath);
        } else if (view instanceof Switch) {
            vModfr = new SwitchModifier(res, cxpr, filepath);
        } else if (view instanceof ToggleButton) {
            vModfr = new ToggleButtonModifier(res, cxpr, filepath);
        } else if (view instanceof Button) {
            vModfr = new ButtonModifier(res, cxpr, filepath);
        } else if (view instanceof Spinner) {
            vModfr = new SpinnerModifier(res, cxpr, filepath);
        } else if (view instanceof EditText) {
            vModfr = new EditTextModifier(res, cxpr, filepath);
        }
        if (vModfr != null) {
            vModfr.modify(view);
        }
    }
}

ViewModifier class:

public abstract class ViewModifier<T extends View> {
    private static final String TAG = "ViewModifier";
    protected final CxpResources cxpResources;
    protected final String basedir;
    protected final Resources resources;
    protected final TypedValue typedValue;

    public ViewModifier(Resources resources, CxpResources cxpResources, final String basedir) {
        this.resources = resources;
        this.cxpResources = cxpResources;
        this.basedir = basedir;
        typedValue = new TypedValue();
        typedValue.density = resources.getDisplayMetrics().densityDpi;
    }

    public abstract void modify(T v);

    // some helper codes....
}

All xxxModifier class inherit from ViewModifier class.

My questions:

Is a bunch of instanceofs really the best way? As far as I know, I can't use visitor pattern because I can't modify Android widgets.
Am I using generics right? Particularly in ViewModifier class signature.
Which is better, my current implementation, or to make modify an interface and then have xxxModifier classes implement that? ViewModifier has a bunch of helper methods though.
Review of my code in general, according to Android and Java best practices and conventions.
Intellij Idea / Android Studio tricks to help self-review perhaps?


texts:
I often get into the dilemma of how to use string constants, this is the way I use now:
UIImage *image = [UIImage imageNamed:@"apple.png"];
NSArray *imageNames = @[@"apple01.png",@"apple02.png"];
NSDictionary *imageKeyValues = @{@"Avatar" : @"apple.png"};

Once I encounter this type of code, I often use string pointers to refactor, because I don't know what the string code means:
static NSString *appleImage = @"apple.png";
UIImage *image = [UIImage imageNamed:appleImage];

NSArray *imageNames = @[@"apple01.png",@"apple02.png"];

static NSString  *avatarKey = @"Avatar";
NSDictionary *imageKeyValues = @{avatarKey : appleImage};

My question now is: Should I assign each string to a variable? Many strings are not shared and will only be used once. Is it worth modifying like this? Is there a better way?


texts: Creating range of numeric values based on array of strings

texts:
Basically I have an array of strings. In this array, a range separator word might exist. For this example, I'm going to use the word to as range separator. We can assume that the range separator is not the first or last entry in the array. If we find the range separator we need to get the entry before and the entry after the separator, compare the two entries that we can assume are safe to parse as integer and find the character that differs between them. We then need to create new entries by counting up the number that is different, and return an IEnumerable<string> containing the new entries. We can also assume that only one character will differ between the start of the range and the end of the range.

For example, if the array contains these values:

1102
to
1602

we need to return

1202
1302
1402
1502

And here's my code:

public static IEnumerable<string> GetRangeSegments(string[] segments, string rangeIndicator)
{
    var rangeIndicatorIndex = Array.IndexOf(segments, rangeIndicator);
    var rangeSegments = new string[] { };

    if (rangeIndicatorIndex < 0)
    {
        return rangeSegments;
    }

    var rangeStart = segments[rangeIndicatorIndex - 1];
    var rangeEnd = segments[rangeIndicatorIndex + 1];

    var startChars = rangeStart.ToCharArray();
    var endChars = rangeEnd.ToCharArray();

    if (startChars.Length != endChars.Length)
    {
        return rangeSegments;
    }

    var diffIndex = -1;

    for (var i = 0; i < startChars.Length; i++)
    {
        if (startChars[i] == endChars[i])
        {
            continue;
        }

        diffIndex = i;
        break;
    }

    if (diffIndex == -1)
    {
        return rangeSegments;
    }

    var start = int.Parse(startChars[diffIndex].ToString()) + 1;
    var end = int.Parse(endChars[diffIndex].ToString());

    var numbers = Enumerable.Range(start, end - start);
    return rangeSegments.Concat(numbers.Select(number => rangeStart.Remove(diffIndex, 1).Insert(diffIndex, number.ToString())));
}


texts: Concise Proof of the Monty Hall Problem in R

texts:
This is an attempt at a concise proof of the Monty Hall problem in probability and statistics in R.

For those unfamiliar, the scenario is this:

There exists a contestant on a game show. This contestant chooses between three doors (A, B, and C), behind one of which is a new car.
The host (Monty Hall) reveals what is behind one of the other two doors.
The contestant is offered to either stick with their same door, or switch.
The question is: which choice offers the highest probability of success (winning the car)?

To complete this problem, there is some necessary background:

The probability that the car is behind any door before anything happens is uniformly distributed.
The host will never reveal the car on the first opening of a door (this is what offsets the probability).

Assume (arbitrarily) that the contestant chooses door A. If the car is behind door A, the host will open door B or C with equal (50/50) probability - this is intuitive. If the car is behind door B however, the host must open door C to prevent revealing the car, thus the probability of opening door B is zero. This foreknowledge of the location of the car is what skews the problem.

The result is that the contestant ends up with a 66% chance of winning by switching their chosen door, and a 33% if they stick with their current choice. In the code below, it is compulsory for the contestant to switch - this was to improve computational efficiency:

doors <- c("A", "B", "C")
wins <- 0
n <- 10000

for (i in 1:n) {
  # Choose which door the car is behind
  car <- sample(doors)[1]

  # The contestant chooses a door
  contestant <- sample(doors)[1]

  # Monty opens a door that the car is not behind
  monty <- sample(doors[which((doors != car) & (doors != contestant))])[1]

  # Force the contestant to switch
  contestant <- sample(doors[which((doors != monty) & (doors != contestant))])[1]

  # Count the wins
  if(contestant == car){wins <- wins+1}
}

(wins/n)


texts: Random Walk simulator seems slow, are there ways to optimize my code?

texts:
I'm trying to write a short random walk simulator in which an agent has a 50% chance on each "round" to either move toward x or back to its initial position. If the agent is already at its initial position and has to move back, it stays there instead.

I'm getting a lot of variance in the results and running the function with a distance to x of 2000 steps is already taking a while.

I was thinking I'd run the simulator over 200 steps 100 times and take the average of that, but with 40200 steps when x is 200 steps away on average, it's taking almost 10 seconds to run 100 times, which seems extremely slow.

Are there things I could optimize in my code to make it faster? Also, if you see glaring problems with design, suboptimal memory usage, etc...please don't hesitate to comment on those as well, thank you.

PS: I use a random int function of [0,1] for my 50% probability.

import numpy as np
import random as rand

def randomWalk(x):

    position = 0
    steps = 0

    while (position != x):
        move = rand.randint(0,1)
        steps += 1

        if (move == 1):
            position += 1

        elif (move == 0) & (position != 0):
            position -= 1

    return steps

trials = [0] * 100

for i in range(100):
    trials[i] = randomWalk(200)

sum = 0.

for trial in trials:
    sum += trial

avg = 0.

avg = sum / len(trials)

print avg


texts:
This one is kind of involved. Is there a simpler way to implement this prefix code in base python, my existing code goes below but any help in modification or review will be helpful.

# Lagged fibonacci numbers the sequence starts: 1,2,3,5,8,11
def fibonacci(n):
    a = 1
    b = 1
    out = []
    for i in range(n):
        out.append(a)
        a,b = a+b,a
    return out

# There has to be a better way to do this, right?
# Go through the list for the first few fibonacci numbers from greatest to
# make a list of fibonacci numbers that add up to each code number (1,2,3...)
# The code is then the indexes of those fibonacci numbers, with leading zeroes
# removed, reversed, with an additional "1" at the end.
def makeCodebook(decode=False):
    F = fibonacci(10)
    F.reverse()
    codes = []
    for x in range(1,27):
        while x != 0:
            code = []
            for f in F:
                if f <= x:
                    code.append("1")
                    x = x-f
                else:
                    code.append("0")

            while code[0] == "0":

                code.pop(0)
            code.reverse()
            code.append("1")
            codes.append("".join(code))

    # Matchup codes with letters
    D = {}
    alpha = "ETAOINSRHLDCUMFPGWYBVKXJQZ"
    if decode == False:
        for a,b in zip(alpha,codes):
            D[a] = b

    if decode == True:
        for a,b in zip(alpha,codes):
            D[b] = a
    return D

def prefixCode(text,decode=False):

    # Build the codebook
    D = makeCodebook(decode=decode)

    # When encoding we simply translate each letter to its code
    if decode == False:
        out = []
        for letter in text:
            out.append(D[letter])
        return "".join(out)


texts: Which will be better declaration go to with TypeScript?

texts:
This is a simple question, but during my migration to TypeScript, I'm seeing that in many cases my code could take these two directions... which one could be a better direction to go with: class.ts or interface.ts?

class.ts

export class ActionSet {
  constructor(private name: string) {}

  get ACTION(): string {
    return this.name;
  }

  get PENDING(): string {
    return `${this.name}_PENDING`;
  }

  get FULFILLED(): string {
    return `${this.name}_FULFILLED`;
  }

  get REJECTED(): string {
    return `${this.name}_REJECTED`;
  }
}

export function createActionSet(name: string): ActionSet {
  return new ActionSet(name);
}

interface.ts

export interface IActionSet {
  ACTION: string;
  PENDING: string;
  FULFILLED: string;
  REJECTED: string;
}

export function createActionSet(name: string): IActionSet {
  return {
    ACTION: name,
    PENDING: `${name}_PENDING`,
    FULFILLED: `${name}_FULFILLED`,
    REJECTED: `${name}_REJECTED`
  };
}

Due to ActionSet is not being used in many places, will it be worth to create a class for it? or is this implementation an overkill?


texts:
Java problem to left rotate an array upto n times. It would be nice if anyone can review this code.

Task:

A left rotation operation on an array of size  shifts each of the array's elements  unit to the left. For example, if left rotations are performed on array , then the array would become .

Given an array of  integers and a number, , perform  left rotations on the array. Then print the updated array as a single line of space-separated integers.

solution

public class LeftRotateArray {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        int Array_Size = in.nextInt();
        int Rotation_Number = in.nextInt();
        int arr[] = new int[Array_Size];
        for (int i = 0; i < Array_Size; i++) {
            arr[i] = in.nextInt();
        }
        for (int i = 0; i <= Array_Size - 1; i++) {
            if (i < Array_Size - Rotation_Number)
                System.out.print(arr[i + Rotation_Number] + "\t");

            else
                System.out.print(arr[i - Array_Size + Rotation_Number] + "\t");

        }
    }

}


texts:
This is a rot-n (rotate n times) encrypt/decrypt algorithm, where n can be any integer (+/-).

It's written to encrypt/decrypt all the alphabets (upper/lower case) and leaving behind all non-alphas.

rot-n where n is the key, is given in the first line of input file.

Everything is working fine.  I just need help in optimizing it.

  Challenge description

  Your submission will be tested against an input file that contains
  ASCII characters. The input file starts at the very first line with a
  N-digits positive or negative integer number that is your cipher,
  followed by a new-line character. The second line starts with the
  payload of the encrypted text until the end of file. Note that only
  words (alphanumeric sequences) are encrypted and that every other
  character (i.e. punctuation) must not be processed by your algorithm
  and must also be copied ‘as is’ to the standard output.*

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class Fightsopa {

public void process(String input, int n) {
    int abcd = n;
    if (abcd < 0) {
        abcd = (26 - ((0 - abcd) % 26));
    }
    int rot = 26 - abcd % 26;  //for decrypting
 // int rot=       abcd % 26;  //for encrypting
    char out = 0;
    for (char ch : input.toCharArray()) {
        if (ch >= 65 && ch <= 90) {
            if (ch + rot <= 90) {
                out = (char) (ch + rot);
                System.out.print(out);
            } else {
                out = (char) (ch + rot - 26);
                System.out.print(out);
            }

        } else if (ch >= 97 && ch <= 122) {
            if (ch + rot <= 122) {
                out = (char) (ch + rot);
                System.out.print(out);
            } else {
                out = (char) (ch + rot - 26);
                System.out.print(out);
            }
        } else {
            System.out.print(ch);
        }
    }
}

public void handler(File fFile) throws FileNotFoundException {
    Scanner scanner = new Scanner(new FileReader(fFile));
    int rot = 0;
    int count = 0;
    while (scanner.hasNextLine()) {
        if (count == 0) {
            rot = scanner.nextInt();
            scanner.nextLine();
        } else {
            String wordp = scanner.nextLine();
            process(wordp, rot);
            System.out.println();
        }
        count++;
    }
    scanner.close();

}

public static void main(String args[]) throws FileNotFoundException {
    if (args.length > 0) {
        File fFile = new File(args[0]); //Input file having the first line as the  key
        Fightsopa fsopa = new Fightsopa();
        fsopa.handler(fFile);
    }
}
}


texts:
The following code interweaves two linked lists together in three flavors: iterative, recursive top-down, and recursive bottom-up. My iterative solution feels like it can be optimized better and my bottom up recursive design skills are not necessarily the best (although this solution is a much smaller task than most recursive bottom up solutions e.g. pruning a binary search tree).

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

typedef struct list List;
struct list {
    int item;
    List* next;
};

//setup functions
List* generateList(int len);
void freeList(List* list);
void printList(List* list);
void showcase();
//zip functions
List* zipLists_iter(List* a, List* b);
List* zipLists_rec_top(List* a, List* b);
List* zipLists_rec_bot(List* a, List* b);
List* reverseList_rec(List* list);
List* reverseList_rec_imp(List* list, List* prev);

int main() {
    showcase();
    return EXIT_SUCCESS;
}

void showcase() {
    List* a = generateList(5);
    List* b = generateList(5);
    b = reverseList_rec(b);
    printList(a); //These are here for simplicity
    printList(b);

    puts("Testing zipLists_iter");
    a = zipLists_iter(a, b);
    printList(a);
    freeList(a);

    a = generateList(5);
    b = generateList(5);
    b = reverseList_rec(b);
    puts("Testing zipLists_rec_top");
    a = zipLists_rec_top(a, b);
    printList(a);
    freeList(a);

    a = generateList(5);
    b = generateList(5);
    b = reverseList_rec(b);
    puts("Testing zipLists_rec_bot");
    a = zipLists_rec_bot(a, b);
    printList(a);
    freeList(a);
}

void freeList(List* list) {
    while ( list ) {
        List* tmp = list;
        list = list->next;
        free(tmp);
    }
}

List* generateList(int len) {
    List* head = NULL;
    List* tail = NULL;
    int i;
    for (i = 0; i < len; i++) {
        List* node = malloc(sizeof(*node));
        node->item = i;
        node->next = NULL;
        if ( !head ) {
            head = node;
            tail = node;
        } else {
            tail->next = node;
            tail = node;
        }
    }
    return head;
}

void printList(List* list) {
    while ( list ) {
        printf("%d ", list->item);
        list = list->next;
    }
    printf("\n");
}

List* reverseList_rec(List* list) {
    return reverseList_rec_imp(list, NULL);
}

List* reverseList_rec_imp(List* list, List* prev) {
    if (!list) return NULL; //mirror NULL input

    if ( !list->next ) {
        list->next = prev;
        return list;
    } else {
        List* next = list->next;
        list->next = prev;
        return reverseList_rec_imp(next, list);
    }
}

List* zipLists_iter(List* a, List* b) {
    List* root = a;
    while ( a && b ) {
        List* oldNextA = a->next;
        List* oldNextB = b->next;
        a->next = b;
        b->next = oldNextA;
        a = oldNextA;
        b = oldNextB;
    }
    return root;
}

List* zipLists_rec_top(List* a, List* b) {
    List* oldNext = a->next;
    a->next = b;
    if ( b )
        zipLists_rec_top(b, oldNext);
    return a;
}

List* zipLists_rec_bot(List* a, List* b) {
    if ( !a ) {
        return b;
    } else if ( !b ) {
        return a;
    } else {
        a->next = zipLists_rec_bot(b, a->next);
        return a;
    }
}


texts: Clickable icon for expanding/collapsing content

texts:
The general idea of the code is that I have a + or - icon (".trigger") that is click-able and will expand or collapse the content (".cont") directly following it (there are many of there expand/collapse pairs).  I also have a span("#expandAll") that, when clicked, will expand or collapse every block.

Please review my first usage of jQuery and help me put my head into a more jQuery state.  Where can the code be improved?  Are there any problems with it?  Is there a better way to do it?

(To be perfectly honest, I have no idea what the $() function really does.)

var expandAll = function () {
    $(".cont").removeClass("hid");
    $("#expandAll").html("Colapse All");
    $("#expandAll").unbind("click", expandAll);
    $(".trigger").html("-");
    $("#expandAll").click(colapseAll);
}
var colapseAll = function () {
    $(".cont").addClass("hid");
    $("#expandAll").html("Expand All");
    $("#expandAll").unbind("click", colapseAll);
    $(".trigger").html("+");
    $("#expandAll").click(expandAll);
}
$(document).ready(function () {
    $(".trigger").click(function (event) {
        $this = $(this);
        $this.html($this.text() == '+' ? '-' : '+');
        $($this.nextAll(".cont").get(0)).toggleClass("hid");
    });
    $("#expandAll").click(expandAll);
});

Please let me know if you need more/less info.


texts: Issue a redirect, trying several string replacements for the domain

texts:
How could I improve this code?

var to = "http://forum.";

if (!RedirectPermanent("http://www.", to))
    if (!RedirectPermanent("http://blog.", to))
        if (!RedirectPermanent("http://forum.", to))
            if (!RedirectPermanent("http://tracker.", to))
                if (!RedirectPermanent("http://wiki.", to))
                    RedirectPermanent("http://", to);

This is the method:

private bool RedirectPermanent(string from,string to)
{
    if (Request.Url.AbsoluteUri.StartsWith(from))
    {
        var domain = Request.Url.GetLeftPart(UriPartial.Authority).Replace(from, to);
        Response.RedirectPermanent(string.Concat(domain, Request.RawUrl));
        return true;
    }

    return false;
}


texts:
I have an array (or string) to parse and I want to examine each element sequentially. This is a perfect case for the iterators / consumers that Rust offers.

The problem arises when I have to access previously parsed data during iteration. For example, I need to subtract the item that was 5 places before the current item.

The best way I know to achieve this using idiomatic Rust is a sliding window Vec that keeps track of the items previously seen, all of which happens inside a fold operation.

A working code extract looks like the following:

fn main() {
   let string = "111222023333"; // the string to parse
   let str_iter = string.trim_left().trim_right().chars();
   let mut last = 1 as usize;
   let mut digit = 0 as usize;
   let mut window: Vec<usize> = Vec::new();
   let target = 5;
   str_iter.fold(1, |mut val, c| {
      digit = c.to_digit(10).unwrap() as usize;
      window.push(digit);
      if window.len() > target
        {last = window.remove(0);}
      if digit == 0
        {val -= last;}
      val
   });
}

I don't really like this as I have to use a Vec to store the values of size target; I could just use indexes like I would in C/C++ but that again feels a bit wrong and not idiomatic at all.

Any ideas on how to idiomatic achieve this without using an additional Vec?


texts:
Could this code possibly be shortened, or even better be rewritten in the fewest lines of code possible?

import csv

import random
import math
import operator as op

name=input("What is your name: ")
print("Hello there",name,"Welcome to the math quiz, you will be asked 10 random questions on Addition, Multiplication and Subtraction")

choice = random.choice(['x','-','+'])
finish = False
questionnumber = 0
correctquestions = 0
Class = ""

while finish == False:
       choice = random.choice(['x','-','+'])
       if questionnumber < 10 | questionnumber >= 0:
           number1 = random.randrange(1,10)
           number2 = random.randrange(1,10)
           print((number1),(choice),(number2))
           answer=int(input("What is the answer?"))
           questionnumber = questionnumber + 1

        if choice==("+"):
            realanswer = number1+number2
            if answer==realanswer:
                print("Well done that's the correct answer")
                correctquestions = correctquestions + 1
            else:
                print("Unlucky wrong answer")

        if choice==("x"):
            realanswer = number1*number2
            if answer==realanswer:
                print("That's the correct answer")
                correctquestions = correctquestions + 1
            else:
                print("That was not correct")

        elif choice==("-"):
            realanswer = number1-number2
            if answer==realanswer:
                print("That's the correct answer")
                correctquestions = correctquestions + 1
            else:
                print("Unlucky not the corret")

    else:
        finish = True
        print("Well done You have completed the math quiz, Your score was " + str(correctquestions) + "/10 questions.")

while Class not in ("1" , "2" , "3"):
    Class = input("whish class are you in?")

ScoresList = []

if Class == "1":
    with open("class1.csv","r") as class1:
        reader = csv.reader(class1)
        for row in reader:
            ScoresList.append(row)
elif Class == "2":
    with open("class2.csv" , "r") as class2:
        reader = csv.reader(class2)
        for row in reader:
            ScoresList.append(row)

elif Class == "3":
    with open("class3.csv","r") as class3:
        reader = csv.reader(class3)
        for row in reader:
            ScoresList.append(row)
else:
    print("Please enter a valid class")

position = 0
match = 0

for row in ScoresList:

    if len(row) > 0 and row[0] == name:
        match = 1
        break
    else:
        position += 1

print(position , match)
if match == 0:
    ScoresList.append([name,str(correctquestions)])
else:

    row = ScoresList[position]
    if len(row) == 4:
        del row[1]
    row.append(str(correctquestions))

for row in ScoresList:
    print(row)

if Class == "1":
    with open ("class1.csv" , "w", newline='') as file:
        writer = csv.writer(file)
        for row in ScoresList:
            writer.writerow(row)

if Class == "2":
    with open ("class2.csv" , "w", newline='') as file:
        writer = csv.writer(file)
        for row in ScoresList:
            writer.writerow(row)

if Class == "3":
    with open ("class3.csv" , "w", newline='') as file:
        writer = csv.writer(file)
        for row in ScoresList:
            writer.writerow(row) `


texts: Area calculator for shapes as an OOP interview test

texts:
A while ago a tricky C++ interview question came across to me, and ever since I could not tell what I did wrong.

  Create a base class named “Shape” with a method to return the area of the shape. Create a class named “Triangle” derived from the base class “Shape”.

  Class “Triangle” must have two constructors. One receives the length of the (a) side of the triangle and the related (ma) height. The other receives the length of (a),(b),(c) sides of the triangle.
  In the second case, the constructor must validate the input by checking that the length of one side is smaller than the sum of the lengths of the other two sides. If the input is invalid, it should throw an exception. Implement the method (available in the base class) that calculates the area of the triangle on the basis of the available data.

  You can use two formulas. If the length of a side and height is given: T=(a*ma)/2. If the lengths of the three sides are given, you can use the Heron formula:
  sqrt(s*(s-a)*(s-b)*(s-c))
  where s=(a+b+c)/2

This should be obvious for any candidate. It clearly asks if you know what the base principles of OOP is, and if you can solve a bit complex problem with it. Before I could just jump into it, I found something odd. The assessment requires you to create some class that behaves differently as they've created. It asks you to use some trickery to solve this problem.

Well, I, who read a bit about what SOLID is, and familiar with design patterns were trivial that using polymorphism is the way to solve this the most elegant way. My approach was something like this:

Create the base class
Create the derived class
Use the derived class constructor as an abstract factory for a composite type, and make the implementation to act as a proxy toward the different implementations
Create two other classes which handles the actual data and takes care of the calculation
Take care of the exceptions using std::exception - these are tricky as well in C++
Take care of the implementation

In the end my solution looked like this:

#include <exception>
#include <string>
#include <cmath>

class Shape
{
public:
    virtual double Area() = 0;
};

class Exception : public std::exception
{
public:
    Exception(std::string const &message) throw() : m_msg(message) {}
    ~Exception() throw() {}
    virtual char const *what() const _NOEXCEPT { return m_msg.c_str(); }

private:
    std::string m_msg;
};

class Triangle : public Shape
{
    class TriangleSides;
    class TriangleBase;

public:
    Triangle(double base, double height);
    Triangle(double a, double b, double c);
    ~Triangle();
    double Area() override;

private:
    Shape *m_shape;

    class TriangleSides : public Shape
    {
    public:
        TriangleSides(double a, double b, double c);
        double Area() override;

    private:
        double m_a, m_b, m_c;
    };

    class TriangleBase : public Shape
    {
    public:
        TriangleBase(double base, double height);
        double Area() override;

    private:
        double m_base, m_height;
    };
};

Triangle::Triangle(double base, double height) : m_shape(nullptr)
{
    m_shape = new Triangle::TriangleBase(base, height);
}

Triangle::Triangle(double a, double b, double c) : m_shape(nullptr)
{
    if (a + b <= c || a + c <= b || b + c <= a)
        throw Exception("Any two sides of a triangle must be longer than one");
    m_shape = new Triangle::TriangleSides(a, b, c);
}

Triangle::~Triangle()
{
    delete m_shape;
}

double Triangle::Area()
{
    if (m_shape)
        return m_shape->Area();
    else
        return 0;
}

Triangle::TriangleSides::TriangleSides(double a, double b, double c) : m_a(a), m_b(b), m_c(c)
{
}

double Triangle::TriangleSides::Area()
{
    const double s = (m_a + m_b + m_c) * .5;
    return sqrt(s * (s - m_a) * (s - m_b) * (s - m_c));
}

Triangle::TriangleBase::TriangleBase(double base, double height) : m_base(base), m_height(height)
{
}

double Triangle::TriangleBase::Area()
{
    return .5 * (m_base * m_height);
}


texts:
I'm writing a game in C# Monogame, and I've decided to make my project as modular as possible.

GitHub

At first, I've had a single project with a folder that's separated inside to other folders which represent different systems in the game (Items, Abilities, Stats).

I've started by making a .dll project for everything that I've considered as a 'system', i.e - Items, Abilities, Stats, and others that I will soon add, like the player itself (that's just a class right now).

I'm designing the Abilities system based on the answer given on this post.

I'm asking for a code review about the Ability system module, and if you care, about the rest of the game (the MainModule is just remainder of what I've had before I refactored into modularizing everything, so for now there's not much need for whatever's there, unless you see something the could help).

I'd appreciate referencing stuff (or solutions to problems I have) to design patterns, as I'd rather use design patterns to solve problems.

The ability system code:

public interface IBehavior
{
    void ApplyBehavior(IUnit unit);
}

// ---------------------------------------------------- //

public abstract class ActivatableBehavior : IBehavior
{
    public abstract bool BehaviorImplentation(IUnit destinationPlayer);

    public void ApplyBehavior(IUnit unit)
    {
        BehaviorImplentation(unit);
    }
}

// ---------------------------------------------------- //

public abstract class LimitedTimeBehavior : IBehavior
{
    public Stopwatch Timer { get; }
    public abstract void ApplyBehavior(IUnit unit);
    public long Duration { get; }

    protected LimitedTimeBehavior(long durationOfBehavior)
    {
        Timer = new Stopwatch();
        Duration = durationOfBehavior;
    }
}

// ---------------------------------------------------- //

public abstract class TickBasedBehavior : LimitedTimeBehavior
{
    public long TickTime { get; }
    protected abstract void ApplyTick(IUnit unit);

    protected TickBasedBehavior(long durationOfBehavior, long timeBetweenTicks)
        : base(durationOfBehavior)
    {
        TickTime = timeBetweenTicks;
    }

    public override void ApplyBehavior(IUnit unit)
    {
        Thread trd = new Thread(() => ThreadMethod(unit));
        trd.Start();
    }

    private void ThreadMethod(IUnit unit)
    {
        Timer.Start();

        while (Timer.ElapsedMilliseconds < Duration)
        {
            if (Timer.Elapsed.TotalMilliseconds % TickTime == 0)
                ApplyTick(unit);
        }

        Timer.Stop();
    }
}

// ---------------------------------------------------- //

public abstract class DurationBehavior : LimitedTimeBehavior
{
    protected abstract void Activate(IUnit unit);
    protected abstract void Deactivate(IUnit unit);

    private bool IsActivated { get; set; }

    protected DurationBehavior(long durationOfBehavior)
        : base(durationOfBehavior)
    {
        IsActivated = false;
    }

    public override void ApplyBehavior(IUnit unit)
    {
        if (IsActivated) return;
        Thread trd = new Thread(() => ThreadMethod(unit));
        trd.Start();
        IsActivated = true;
    }

    private void ThreadMethod(IUnit unit)
    {
        Timer.Start();
        Activate(unit);
        while (Timer.Elapsed.TotalMilliseconds < Duration) { }
        Timer.Reset();
        Deactivate(unit);
        IsActivated = false;
    }
}


texts:
I have a linearized 2D array u (block_height * block_width) containing the values of a physical quantity over a regular 2D mesh. I need to downsample boundaries (top, bottom, left, right) of this array for communication with another process. I've refactored some code that does this, and I'd like people's thoughts on whether the new code is actually an improvement.

Old code:

if (dir == LEFT)
    for(int j = 1; j <= block_height; j += 2)
        left_edge[j/2] = (u[index(1,j)]   + u[index(2,j)] +
                          u[index(1,j+1)] + u[index(2,j+1)]) / 4;
else if (dir == RIGHT)
    for(int j = 1; j <= block_height; j += 2)
        right_edge[j/2] = (u[index(block_width-1, j)]   + u[index(block_width,j)] +
                           u[index(block_width-1, j+1)] + u[index(block_width, j+1)]) / 4;
else if (dir == UP)
    for(int i = 1; i <= block_width; i += 2)
        top_edge[i/2] = (u[index(i,1)]   + u[index(i,2)] +
                         u[index(i+1,1)] + u[index(i+1,2)]) / 4;
else if (dir == DOWN)
    for(int i = 1; i <= block_width; i += 2)
        bottom_edge[i/2] = (u[index(i,block_height-1)]   + u[index(i,block_height)] +
                            u[index(i+1,block_height-1)] + u[index(i+1,block_height)]) / 4;

New code:

double *boundary;
int k, fixed_dim;
int *x, *y;
switch (dir) {
case LEFT: case RIGHT: count = block_height; x = &fixed_dim; y = &k; break;
case UP:   case DOWN:  count = block_width;  y = &fixed_dim; x = &k; break;
switch (dir) {
case LEFT:  boundary = left_edge;   fixed_dim = 1;                break;
case RIGHT: boundary = right_edge;  fixed_dim = block_width - 1;  break;
case UP:    boundary = top_edge;    fixed_dim = 1;                break;
case DOWN:  boundary = bottom_edge; fixed_dim = block_height - 1; break;
}
for (k = 1; k <= count; k += 2)
  boundary[k/2] = (u[index(*x, *y)]   + u[index(*x+1, *y)] +
                   u[index(*x, *y+1)] + u[index(*x+1, *y+1)] )/ 4;

So, I've factored out the repeated for loop and made the logic more declarative, at the expense of introducing some additional indirection (including over which direction the loop iterates through memory!) and the variables to support it.

One obvious direction of future change for this code is increasing from 2 dimensions to 3 (and possible even more). I know which one I'd prefer to do that to, but if the old code is overwhelmingly clearer to people reading it, then the repetition may be worth retaining.


texts: Watch for CRUD state changes and make sure only one is active at once

texts:
I'm using AngularJS and I have a watch task in my controller that needs to be dried up if possible.

Basically it watches for state changes in my front end. I have 3 buttons: add, edit, and delete which will toggle these states. I only want one to be active at once.

My buttons:

<button ng-click="actions.add === false ? actions.add = true : actions.add = false">Add</button>
<button ng-click="actions.edit === false ? actions.edit = true : actions.edit = false">Edit</button>
<button ng-click="actions.delete === false ? actions.delete = true : actions.delete = false">Delete</button>

Snippet from my controller:

$scope.actions = {
  add: false,
  edit: false,
  delete: false
}

$scope.$watch('actions', function() {

  if ($scope.actions.add === true) {
    $scope.actions.edit = false;
    $scope.actions.delete = false;
  }
  else if ($scope.actions.edit === true) {
    $scope.actions.add = false;
    $scope.actions.delete = false;
  }
  else if ($scope.actions.delete === true) {
    $scope.actions.add = false;
    $scope.actions.edit = false;
  }
});


texts:
I'm newly working with CodeIgniter and PHP. I wrote a category structured 'pages' code with listing pages as multilevel list or indented select box.

page                                        page_lang
-------------------------------------       ----------------------------
id_page | id_menu | id_parent | level       id_page |  title     | etc..
-------------------------------------       ----------------------------
   1    |    1    |     0     |   0            1    | Name 1     | etc..
   2    |    1    |     1     |   1            2    | Name 1.1   | etc..
   3    |    1    |     2     |   2            3    | Name 1.1.1 | etc..
   4    |    1    |     2     |   1            4    | Name 1.2   | etc.

My controller:

function get_menu_content($id_menu, $id_parent = 0, $level = 0)
{
  echo '<select>';
  $dropdown = $this->my_model->get_menu($id_menu,'dropdown');
  echo $dropdown;
  echo '</select>';  //echo in controller for quick test purpose
}

My_model has three functions: the first is getting result array, the other two is rendering as list and options.

class My_model extends CI_Model
{

  public $model_result;

  function __construct()
  {
     parent::__construct();
  }

function get_menu($id_menu = '1',$type = 'list')
{
  $sql = "
  SELECT a.id_parent, b.id_page, a.level, b.title
  FROM page a
  INNER JOIN page_lang b ON a.id_page = b.id_page
  WHERE
    a.id_menu = $id_menu";
  $query = $this->db->query($sql);

  if($query->num_rows() > 0)
  {
    $res = $query->result_array();
    foreach($res as $row):
      $items[$row['id_parent']][] = $row;
    endforeach;
    if($type =='list') $this->_menu_list($items); //renders ul tags
    if($type =='dropdown') $this->_menu_dropdown($items); //renders option tag
    return $this->model_result;
  }
}

function _menu_list($items, $parent = null)
{
  $index = $parent == null ? '0' : $parent;
  if (isset($items[$index]))
  {
    $this->model_result .= '
model_result .= $parent == null ? ' id="category" ' : '';
    $this->model_result .= '>';
    foreach ($items[$index] as $child)
    {
      $this->model_result .= '
'.$child['title'];
      $this->_menu_list($items, $child['id_page']);
      $this->model_result .= '
';
    }
    $this->model_result .= '
';
  }
}

function _menu_dropdown($items, $parent = null, $level = '0')
{
  $index = $parent == null ? '0' : $parent;
  $space = str_repeat(' &nbsp &nbsp ', $level);
  if (isset($items[$index]))
  {
    foreach ($items[$index] as $child)
    {
      $this->model_result .= '<option value="'.$child['id_page'].'">'.$space.$child['title'].'</option>' . "\n";
      $this->_menu_dropdown($items, $child['id_page'],$level+1);
    }
  }
}

It works a bit slowly. I need a cleaner code I guess. I will appreciate any improvement on the code based on my database structure.


texts: Individual collapsible areas with accessibility in mind

texts:
I've been learning Javascript by creating reusable individually collapsible areas (not using jQuery) and I was wondering if someone could review it and let me know if there is anything they would do differently?

Also it would be good if it was usable for screen readers so any usability feedback would be appreciated. If this requires using more CSS and less JS then examples would be helpful.

https://codepen.io/mandrewnz/pen/QgKyjq

HTML

Title

Content goes here

        <button class="js-collapsible-btn">Click to show some text</button>

Suprise

JS

/* adding classlist.js polyfill separately */

var btn = document.getElementsByClassName('js-collapsible-btn');

function findAncestor (el, cls) {
    while ((el = el.parentElement) && !el.classList.contains(cls));
    return el;
}

var openHolder = function(e) {
    var region = findAncestor(this, 'js-collapsible-region'),
        hiddenText = this.childNodes[1];

    // set text to reflect collapsible holder status
    hiddenText.textContent == "(collapsed)" ? hiddenText.textContent = "(expanded)" : hiddenText.textContent = "(collapsed)";

    if (region.classList.contains('closed')) {
        region.classList.remove('closed');
        region.classList.add('open');
    } else {
        region.classList.remove('open');
        region.classList.add('closed');
    }
};

// Create visually hidden text in each link to indicate state
for (var i = 0; i < btn.length; i++) {
    var span = document.createElement('span');
    var currentBtn = btn[i];

    span.classList.add('visuallyhidden');

    span.innerHTML = '(collapsed)';
    currentBtn.appendChild(span);

    // add click event to open holder
    btn[i].addEventListener('click', openHolder, false);
}


texts: Two methods for finding a sprite in sprite sheet C++, which is better?

texts:
I have two snippets of code that I would like you to look at. I can't figure out which of the two is most efficient (or better practice, if applicable). I'm currently finding the row and column of a sprite in a sprite sheet in order to render it to the screen; which works find and dandy. However, I now have two algorithms:

const double Testvalue = 155.0f; //This values changes, could be any natural number.
const double imageWidth = 614.0f;
const double SpriteAverageSize = 34.0f; //floor(value / spriteAverageSize) gives us max rows (which is this case is 18).

double numRows = floor(imageWidth / SpriteAverageSize);
double RowValue = ceil(Testvalue / numRows);
double ColumnValue = numRows - ((numRows  * RowValue) - Testvalue);

//This will do the following operation:
//numRows = floor(614.0/ 34.0) -> floor(18.05..) -> 18.0.
//RowValue = ceil(155.0/ 18.0) -> ceil(8.611..) -> 9.0.
//ColumnValue = 18.0 - ((18.0 * 9.0) - 155.0) -> 18.0 - (162.0 - 155.0) -> 18.0 - 7.0 -> 11.0.

//Row: 9 ; Column: 11.

or

const double Testvalue = 155.0f;
const double imageWidth = 614.0f;
const double SpriteAverageSize = 34.0f;

double RowValue = ceil(Testvalue / floor(imageWidth / SpriteAverageSize));
double ColumnValue = floor(imageWidth / SpriteAverageSize) - ((floor(imageWidth / SpriteAverageSize) * RowValue) - Testvalue);

//This will do the following operation:
//RowValue = ceil(155.0 / floor(614.0 / 34.0)) -> ceil(155.0 / floor(18.05..)) -> ceil(155.0 / 18.0) -> ceil(8,61..) -> 9.0.
//ColumnValue = floor(614.0 / 34.0) - ((floor(614.0 / 34.0) * 9.0) - 155.0) -> floor(18.05..) - ((floor(18.05..) * 9.0) - 155.0) -> 18.0 - ((18.0 * 9.0) - 155.0) -> 18.0 - 7.0 -> 11.0.

//Row: 9 ; Column: 11

To clarify, these two work perfectly (I have also implemented it as a method in my class to do the operation as I get the data from an XML file), I get the right row and column value as I've tested several times and implementing it works too. I would just like some tips on which of the two algorithms you'd prefer in a block of code and which of the two is more efficient?


texts:
https://leetcode.com/problems/flood-fill/

  An image is represented by a 2-D array of integers, each integer
  representing the pixel value of the image (from 0 to 65535).

  Given a coordinate (sr, sc) representing the starting pixel (row and
  column) of the flood fill, and a pixel value newColor, "flood fill"
  the image.

  To perform a "flood fill", consider the starting pixel, plus any
  pixels connected 4-directionally to the starting pixel of the same
  color as the starting pixel, plus any pixels connected 4-directionally
  to those pixels (also with the same color as the starting pixel), and
  so on. Replace the color of all of the aforementioned pixels with the
  newColor.

  At the end, return the modified image.

Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
Note:

The length of image and image[0] will be in the range [1, 50].
The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
The value of each color in image[i][j] and newColor will be an integer in [0, 65535].

Please review for performance and coding style.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/flood-fill/
    /// </summary>
    [TestClass]
    public class FloodFillTest
    {
        [TestMethod]
        public void ExampleTest()
        {
            int[][] image = { new[] { 1, 1, 1 }, new[] { 1, 1, 0 }, new[] { 1, 0, 1 } };
            int sr = 1;
            int sc = 1;
            int newColor = 2;
            int[][] expected = { new[] { 2, 2, 2 }, new[] { 2, 2, 0 }, new[] { 2, 0, 1 } };
            FloodFillDFS dfs = new FloodFillDFS();
            dfs.FloodFill(image, sr, sc, newColor);
            for (int i = 0; i < 3; i++)
            {
                CollectionAssert.AreEqual(expected[i],image[i] );
            }

        }
    }

    public class FloodFillDFS
    {
        public int[][] FloodFill(int[][] image, int sr, int sc, int newColor)
        {
            int oldColor = image[sr][sc];
            DFS(image, sr, sc, newColor, oldColor);
            return image;
        }

        //make sure to check first the corner cases
        private void DFS(int[][] image, int sr, int sc, int newColor, int oldColor)
        {
            if (sr < 0 || sc < 0 || sr >= image.Length || sc >= image[0].Length || image[sr][sc] == newColor || image[sr][sc] != oldColor)
            {
                return;
            }

            image[sr][sc] = newColor;
            DFS(image, sr - 1, sc, newColor, oldColor);
            DFS(image, sr + 1, sc, newColor, oldColor);
            DFS(image, sr, sc - 1, newColor, oldColor);
            DFS(image, sr, sc + 1, newColor, oldColor);
        }
    }
}


texts: Mongoose virtual field declaration in Typescript interfaces

texts:
I'm recently started learning Node.js and I'm trying to write a simple Todo app using Mongoose. Since I'm also try to learn Typescript I wanted to combine my basic knowledge on both topics and I encountered a problem with defining interfaces for data models.
I have a simple Todo model:
export interface Todo {
    title: string;
    date?: Date;
    completed: boolean,
    owner: Types.ObjectId
};

export interface TodoDocument extends Todo, Document {
};

interface TodoModel extends Model<TodoDocument> {
};

const TodoSchema = new Schema <TodoDocument, TodoModel>({
    title: {
        type: String,
        required: true
    },
    date: {
        type: Date
    },
    completed: {
        type: Boolean,
        required: true
    },
    owner: {
        type: Types.ObjectId,
        required: true,
        ref: 'User'
    }
});

export default model<TodoDocument, TodoModel>('Todo', TodoSchema);

What I'm trying to achieve is virtual field in User model that could be populated with tasks. Here it is how it looks right now:
export interface User {
    email: string;
    password: string;
};

export interface UserDocument extends User, Document {
    tokens: Array<string>;
    todos: Types.Array<TodoDocument> | undefined;
    // Some methods
};

interface UserModel extends Model<UserDocument> {
    // Some methods
};

const UserSchema = new Schema<UserDocument, UserModel>({
    email: {
        type: String,
        required: true,
        unique: true,
        trim: true,
        validate(value: string) {
            // Some validation
        }
    },
    password: {
        type: String,
        required: true,
        validate(this: UserDocument, value: string) {
            // Some validation
        }
    },
    tokens: [{
        type: String,
        required: true
    }]
});

UserSchema.virtual('todos', {
    ref: 'Todo',
    localField: '_id',
    foreignField: 'owner'
});

It works fine but what I want to know something. Is todos field of UserDocument interface declared correctly? Or should I use TodoModel instead of TodoDocument? Also is undefined there a good practice since todos field doesn't exist till I execute populate on user instance?