Rust Book Ch 13 Closures with Generic Parameters and HashMap for memoization I have been reading through the rust book. I have made it to chapter 13, at the end of the section called (Storing Closures Using Generic Parameters and the Fn Traits) a couple of improvements are described and left as kind of an exercise.
The task at hand is to change the cache implementation to support not only u32 but any data type and also allow the results to be stored in a hashmap thus allowing us to memoize multiple queries.
I went the route of the everything is copied (since I tried to avoid lifetimes for my first implementation) and I just wanted the feedback from more experienced people on how they would tackle and what pitfall does this version I wrote have.
use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;

struct Cacher<I, O, T>
where
    T: Fn(I) -> O,
{
    calc: T,
    cache: HashMap<I, O>
}

impl<I: Eq + Hash + Copy, O, T> Cacher<I, O, T>
where
    T: Fn(I) -> O
{
    fn new(calc: T) -> Cacher<I, O, T> {
        Cacher {
            calc,
            cache: HashMap::new()
        }
    }

    fn get(&mut self, n: &I) -> &O {
        self.cache.entry(*n).or_insert((self.calc)(*n))
    }
}

fn main() {
    let mut workout = Cacher::new(|x| x + 1);
    println!("{}", workout.get(&4));
    println!("{}", workout.get(&5));
    println!("{}", workout.get(&3));
    println!("{}", workout.get(&4));
}

Another question is where trait are necessary in this case, I realized the compiler doesn't complain if I only put them in the implementation block (but wondered why doesn't it think they are required at the level of the struct since Generic type I has to be both Hashable and Comparable when creating the hashmap right ?)

Even though I'm relatively new to Rust myself, I'll give this a shot since no one else has responded so far.
Is Cacher caching?
Let's test that Cacher is working as intended (wouldn't call calc on the same value twice) by adding a log:
// --snip--
let mut workout = Cacher::new(|x| {
    println!("calc {}", x);
    x + 1
});
// --snip--

The output is:
calc 4
5
calc 5
6
calc 3
4
calc 4
5

Why is calc called twice on 4? Let's check the implementation of Cacher::get:
fn get(&mut self, n: &I) -> &O {
    self.cache.entry(*n).or_insert((self.calc)(*n))
}

The problem is that the expression (self.calc)(*n) is evaluated and the result value given to or_insert whenever Cacher::get is called, even though the result is discarded if the key *n already exists in the hashmap. This can be fixed by using or_insert_with:
fn get(&mut self, n: &I) -> &O {
    let calc = &self.calc;
    self.cache.entry(*n).or_insert_with(|| calc(*n))
}

Now the output is as expected:
calc 4
5
calc 5
6
calc 3
4
5

NB: The borrow checker wouldn't let us simply write || (self.calc)(*n). The reason is self.cache is borrowed mutably within Cacher::get, and the whole self (implying self.cache) would be borrowed within the closure. That would violate the rule that a mutable borrow is exclusive. We circumvent this by explicitly splitting the borrow outside of the closure. The closure then captures only calc.
Some links to read up on this:

https://doc.rust-lang.org/nomicon/borrow-splitting.html
https://stackoverflow.com/questions/61699010/rust-not-allowing-mutable-borrow-when-splitting-properly
https://www.reddit.com/r/rust/comments/cufiq7/rust_mutably_borrows_the_whole_struct_even_though/

Trait Bounds
Let's get to your question on trait bounds. First off, it does make a real difference where we put them:

When the trait bounds are on the struct, then the compiler will not let us instantiate the generic without satisfying the trait bounds, at all.

When the trait bounds are on the impl block, then we are allowed to instantiate the generic with types that do not satisfy the trait bounds, but the methods defined in the impl block will be available only to instances where the trait bounds are satisfied.

In fact, if you have a look at the implementation of HashMap, you'll notice that HashMap has trait bounds only on impl blocks for particular sets of methods that require the respective traits. Thus we may create, but not insert into, a HashMap whose key type doesn't satisfy Eq + Hash:
// This is alright:
struct X {}
let mut map = HashMap::<X, u32>::new();

// This won't compile:
map.insert(X {}, 1);

This being a factual difference, what should we do here? A question on StackOverflow has some interesting answers discussing this question: https://stackoverflow.com/questions/49229332/should-trait-bounds-be-duplicated-in-struct-and-impl. In this case, I'd probably stick with HashMap's approach and be as specific as possible (see code below).
A Note on Tooling
Rust's ecosystem brings some nice tools. Clippy is a linter that does, in fact, hint at the aforementioned bug:
$ cargo clippy
warning: use of `or_insert` followed by a function call
  --> src/main.rs:26:30
   |
26 |         self.cache.entry(*n).or_insert((self.calc)(*n))
   |                              ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_insert_with(|| (self.calc)(*n))`
   |
   = note: `#[warn(clippy::or_fun_call)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call

Also, there's cargo fmt to enforce a standard code style. In this case, it sorts the imports, adds a trailing comma in the struct and removes a duplicated blank line.
Final Code
Here's the code I ended up with, including some further remarks:
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::Hash;

// We may even leave out the trait bound for `T`
// (Example: Perhaps at some point you want to add another implementation
//           where calculation isn't done via a closure/function,
//           but via some special object. This is general enough to allow that.)
struct Cacher<I, O, T> {
    calc: T,
    cache: HashMap<I, O>,
}

// Here I'm splitting into two `impl` blocks.
// A `Cacher` may be created without knowing anything about the types.
impl<I, O, T> Cacher<I, O, T> {
    fn new(calc: T) -> Cacher<I, O, T> {
        Cacher {
            calc,
            cache: HashMap::new(),
        }
    }
}

// Now that the hashmap is used, and `calc` is used,
// the trait bounds are indeed required
impl<I, O, T> Cacher<I, O, T>
where
    // For clarity and consistency, I put all trait bounds into the where block
    I: Eq + Hash + Copy,
    T: Fn(I) -> O,
{
    fn get(&mut self, n: &I) -> &O {
        let calc = &self.calc;
        self.cache.entry(*n).or_insert_with(|| calc(*n))
    }
}

fn main() {
    let mut workout = Cacher::new(|x| x + 1);
    println!("{}", workout.get(&4));
    println!("{}", workout.get(&5));
    println!("{}", workout.get(&3));
    println!("{}", workout.get(&4));
}


Reusable VBA macro to prevent Excel from destroying the data (+ backup capacity) My goal is to prepare the Excel file (see the download link at the end) I would share with my non-technical colleagues, so that they enter some data into it and then I was able to automatically generate CSV without having to manually change format of dates, leading zeros and in other special cases (this CSV I will later use to test another app).

This is my first program in VBA. I understand I did a lot of stupid things, and I would love to be humiliated... But with reasons, so I can improve. I am happy that this implementation allows me to achieve my goal so far, but I think it might be unstable in case if my colleagues try harder (unconsciously) to break it.

In the code below I am trying to change all cells to text format, keeping their values as they are displayed and replacing all the empty cell values by - character "-". Also, I try to remove the duplicated double quotes which might appear.

Please, tell me, how would you improve it to preserve the behavior and make it more transparent? Would you use such tool and why?

Sub PrepareForCSV()

Call CreateBackup
Dim cell1 As Range
Set cell1 = ActiveWorkbook.ActiveSheet.UsedRange
'PART 1:
'Goal: to accomplish setup described here - https://stackoverflow.com/questions/165042/stop-excel-from-automatically-converting-certain-text-values-to-dates

For Each cell1 In cell1
'The check below would help, but it does not work because of Excel internal behaviour
' If (InStr(1, cell1.Value, "=") = 0) Then
'    'cell1.Value = "=" & cell1.Value
'    cell1.NumberFormat = "@"
'inserting - sign to avoid blank cells within UsedRange
'if the cell is empty and format is not text
If cell1.Value = "" And cell1.NumberFormat <> "@" Then
    cell1.Value = "=" & """" & "-" & """"
    cell1.NumberFormat = "@"
'if the cell is empty and format is text
ElseIf cell1.Value = "" And cell1.NumberFormat = "@" Then
    cell1.Value = "-"
    cell1.NumberFormat = "@"
'if the cell starts with double quote followed by = sign and format is not text
 ElseIf (InStr(1, cell1.Value, """=") = 0 And cell1.NumberFormat <> "@") Then
    cell1.Value = "=" & """" & cell1.Value & """"
    cell1.NumberFormat = "@"
'if the cell starts with double quote and format is not text
 ElseIf (InStr(1, cell1.Value, """") = 0 And cell1.NumberFormat <> "@") Then
    cell1.Value = "=" & """" & cell1.Value & """"
    cell1.NumberFormat = "@"
 Else
'probably the code bellow is not needed:
'    If cell1.Value <> "" Then
''        cell1.Value = "=" & """" & cell1.Value & """"
''        cell1.NumberFormat = "@"
'    Else
'        cell1.Value = "=" & """" & "-" & """"
'        cell1.NumberFormat = "@"
'    End If
 End If
Next

'PART 2: replace all unwanted characters
Dim fnd As Variant
Dim rplc As Variant
'replace characters which may cause errors when csv is imported
fnd = ":"
rplc = "!"
  ActiveWorkbook.ActiveSheet.Cells.Replace What:=fnd, Replacement:=rplc, _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
 'replace duplicated double quotes
  ActiveWorkbook.ActiveSheet.Cells.Replace What:="""""", Replacement:="""", _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
  'replace duplicated double quotes for the second time, in case if they are still there
  ActiveWorkbook.ActiveSheet.Cells.Replace What:="""""", Replacement:="""", _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
End Sub

The entire package for review and testing (I separated macros from XLSX for security reasons - you can merge them on your machine) - workbook with supporting macros, mainly backup-restore sheet capacity which allows to play with PrepareForCSV with ease leveraging the backup capacity - with all the credit to @aevanko for his answer https://stackoverflow.com/a/6993228/4778011

Overall, your first program in VBA looks pretty good. I've made some modifications below to illustrate a few points that may help you in the future.

Using Call to call the CreateBackup sub is not necessary and is generally not used much anymore. (However, on a single line like this, I've seen it used to more clearly show that another sub is performing work.)
Indenting your code may have gotten messed up when you posted here to SO, but the code below has each logical level indented to highlight where the different logic paths go.
You re-used cell1 for both the UsedRange and the individual cell value within your loop. That's a big no-no. Use specific names to clearly note what each variable refers, such as thisCell and allCells.
Nearly all the references within your first loop are to thisCell. In this situation, encapsulate the code in a With block. This compiles to a common variable reference without having to reevaluate the fully specified name each time. It also gives you somewhat faster executing code.
Separate your logic into levels to make it easier to follow. In your case, when the cell value is empty and when it's not. Then again when the NumberFormat is not text. It's easy to get lost in a single If statement that has many different parts.
Finally, you're making multiple character replacements at the end and you might encounter other character-pairs that need replacing too. To make your code more easily expandable, the find and replace characters can be added to arrays and accessed in a loop. Only the array assignment would change then.

Option Explicit

Sub PrepareForCSV()
    CreateBackup
    Dim thisCell As Range
    Dim allCells As Range
    Set allCells = ActiveWorkbook.ActiveSheet.UsedRange
    '--- PART 1:
    '    Goal: to accomplish setup described here
    '          http://stackoverflow.com/questions/165042/stop-excel-from-automatically-converting-certain-text-values-to-dates

    For Each thisCell In allCells
        With thisCell
            '--- inserting - sign to avoid blank cells within UsedRange
            '    if the cell is empty...
            If IsEmpty(.Value) Then
                If .NumberFormat <> "@" Then
                    '--- if the format is not text
                    .Value = "=" & """" & "-" & """"
                    .NumberFormat = "@"
                Else
                    '--- if the format is text
                    .Value = "-"
                    .NumberFormat = "@"
                End If

            ElseIf .NumberFormat <> "@" Then
                '--- if the cell isn't empty and not formatted as text
                If InStr(1, .Value, """=") = 0 Then
                    '--- starts with "=
                    .Value = "=" & """" & cell1.Value & """"
                    .NumberFormat = "@"

                ElseIf InStr(1, .Value, """") = 0 Then
                    '--- starts with "
                    .Value = "=" & """" & cell1.Value & """"
                    .NumberFormat = "@"
                Else
                    '--- do nothing?
                End If
            Else
                '--- do nothing?
            End If
        End With
    Next

    '--- PART 2: replace all unwanted characters
    Dim fnd() As Variant
    Dim rplc() As Variant
    Dim i As Integer

    '--- replace characters which may cause errors when csv is imported
    fnd = Array(":", """""", """""")
    rplc = Array("!", """", """")

    For i = 1 To UBound(fnd, 1)
        ActiveWorkbook.ActiveSheet.Cells.Replace What:=fnd(i), Replacement:=rplc(i), _
                                                 LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
                                                 SearchFormat:=False, ReplaceFormat:=False
    Next i
End Sub


Optimizing code from spectral subtraction algorithm This is part of the code from a spectral subtraction algorithm.  I'm trying to optimize it for Android.

Matlab code:

function Seg=segment(signal,W,SP,Window)

% SEGMENT chops a signal to overlapping windowed segments
% A= SEGMENT(X,W,SP,WIN) returns a matrix which its columns are segmented
% and windowed frames of the input one dimentional signal, X. W is the
% number of samples per window, default value W=256. SP is the shift
% percentage, default value SP=0.4. WIN is the window that is multiplied by
% each segment and its length should be W. the default window is hamming
% window.
% 06-Sep-04
% Esfandiar Zavarehei

if nargin<3
    SP=.4;
end
if nargin<2
    W=256;
end
if nargin<4
    Window=hamming(W);
end
Window=Window(:); %make it a column vector

L=length(signal);
SP=fix(W.*SP);
N=fix((L-W)/SP +1); %number of segments

Index=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))';
hw=repmat(Window,1,N);
Seg=signal(Index).*hw;

Java code:

public class MatrixAndSegments
{
    public int numberOfSegments;
    public double[][] res;

    public MatrixAndSegments(int numberOfSegments,double[][] res)
    {
        this.numberOfSegments = numberOfSegments;
        this.res = res;
    }
}

public MatrixAndSegments segment (double[] signal_in,int samplesPerWindow, double        shiftPercentage, double[] window)
{
    //default shiftPercentage = 0.4
    //default samplesPerWindow = 256  //W
    //default window = hanning

    int L = signal_in.length;
    shiftPercentage = fix(samplesPerWindow * shiftPercentage); //SP
    int numberOfSegments = fix ( (L - samplesPerWindow)/ shiftPercentage + 1); //N

    double[][] reprowMatrix =  reprowtrans(samplesPerWindow,numberOfSegments);
    double[][] repcolMatrix = repcoltrans(numberOfSegments, shiftPercentage,samplesPerWindow );

    //Index=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))';
    double[][] index = new double[samplesPerWindow+1][numberOfSegments+1];

    for (int x = 1;  x < samplesPerWindow+1; x++ )
    {
        for (int y = 1 ; y < numberOfSegments + 1; y++) //numberOfSegments was 3
        {
             index[x][y] = reprowMatrix[x][y] + repcolMatrix[x][y];
        }
    }

    //hamming window
    double[] hammingWindow = this.HammingWindow(samplesPerWindow);
    double[][] HW = repvector(hammingWindow, numberOfSegments);

    double[][] seg = new double[samplesPerWindow][numberOfSegments];
    for (int y = 1 ; y < numberOfSegments + 1; y++)
    {
        for (int x = 1; x < samplesPerWindow+1; x++)
        {
            seg[x-1][y-1] = signal_in[ (int)index[x][y]-1 ] * HW[x-1][y-1];
        }
    }
    MatrixAndSegments Matrixseg = new MatrixAndSegments(numberOfSegments,seg);
    return Matrixseg;

}

public int fix(double val) {
    if (val < 0) {
        return (int) Math.ceil(val);
    }
    return (int) Math.floor(val);
}

public double[][] repvector(double[] vec, int replications)
{
    double[][] result = new double[vec.length][replications];

    for (int x = 0; x < vec.length; x++) {
        for (int y = 0; y < replications; y++) {
            result[x][y] = vec[x];
        }
    }

    return result;
}

public double[][] reprowtrans(int end, int replications)
{
    double[][] result = new double[end +1][replications+1];

    for (int x = 1; x <= end; x++) {
        for (int y = 1; y <= replications; y++) {
            result[x][y] = x ;
        }
    }

    return result;
}

 public double[][] repcoltrans(int end, double multiplier, int replications)
{
    double[][] result = new double[replications+1][end+1];

    for (int x = 1; x <= replications; x++) {
        for (int y = 1; y <= end ; y++) {
            result[x][y] = (y-1)*multiplier;
        }
    }

    return result;
}

 public double[] HammingWindow(int size)
{
    double[] window = new double[size];
    for (int i = 0; i < size; i++)
    {

        window[i] =  0.54-0.46 * (Math.cos(2.0 * Math.PI * i / (size-1)));
    }
    return window;
}

I don't have a clue about spectral subtraction, so just some minor, general notes about code:

public int fix(double val) {
    if (val < 0) {
        return (int) Math.ceil(val);
    }
    return (int) Math.floor(val);
}

It should be called truncate.
A few variables could be renamed to follow the Java code conventions.

Variables, parameters:

signal_in to inputSignal or signal
HW to hw
seg maybe to segments or segment (?)
Matrixseg to matrixSeg

Methods:

HammingWindow to calculateHammingWindow

(Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions and The Java Language Specification, Java SE 7 Edition, 6.1 Declarations).
This comments looks unnecessary:

// hamming window
double[] hammingWindow = this.HammingWindow(samplesPerWindow);

(Clean Code by Robert C. Martin: Chapter 4: Comments, Noise Comments)

The this. prefix also unnecessary.


Reducing golfed redundancy For the "First they came" golfing challenge, I wrote the following:

(defn ftc []
  ; Loop over the lines numbers for reference
  (doseq [i (range 4)
          :let [; Added a dummy last "class" since "me-" wasn't necessary,
                ;  and only having 3 elements was causing OOB errors.
                classes ["Socialist" "Trade Unionist" "Jew" ""]

                ; A helper function that executes either its first or second argument
                ;  depending on if the current line is one of the first 3 lines.
                if-first-three-lines #(if (< i 3) % %2)]]

    ; An implicit space is inserted between each of the args to println
    (println
      ; Decide on the opener
      (if (= i 0) "First" "Then")

      "they came for"

      ; Start string concatenation because the implicit space
      ;  begins complicating things.
      (str
        ; Decide which "class" the line belongs to
        (if-first-three-lines
          (str "the " (classes i) "s, ")
          "me-")

        ; Decide on the line ending
        (if-first-three-lines
          "and I did not speak out-\n"
          "and there was no one left to speak for me.")

        ; Then pick the trailer
        (if-first-three-lines
          (str "Because I was not a " (classes i) ".\n")
          "")))))

I generally like how it turned out, but I have a problem with it: the redundancy of the use of the if-first-three-lines function. I've racked my brain to think of a way to simplify it, but haven't been able to figure out a way that doesn't add to the byte count. I call the same function 3 times in a row inside an argument list, just with different arguments. I thought of juxtaposing a application of the arguments, but it was still too long.

The code generally turned out well, but I'm open to any recommendations; whether related to golfing or not.

Keep in mind I minimized the code before submitting. I'm looking for language-specific related golfing tips.

I agree with you that the if-first-three-lines predicate is not needed. I like Massa's solution, https://codegolf.stackexchange.com/questions/139900/first-they-came/140247#140204 :

print(' they came for '.join(
    ["First"]
    + [f"the {i}s, and I did not speak out-\nBecause I was not a {i}.\n\nThen"
       for i in ['Socialist', 'Trade Unionist', 'Jew']]
    + ['me-and there was no one left to speak for me.']))

It says everything additively, without subtracting any special cases. Perhaps you'd like to port that approach.


Heaping up with the inqueries Challenge:

  Given three query types simulate heap operations.

Specifications:

  1. "1 v" - Add an element v to the heap.
    2. "2 v" - Delete the element v from the heap.
    3. Print the minimum of all the elements in the
      heap.

  It is guaranteed that the element to be deleted will exist in the heap.
  Only distinct elements will be in the heap.

  The first line contains the number of queries, Q.
  Each of the next Q lines contains a single query of any one of the 3 above mentioned types.

Implementation:

import java.util.Set;

public class QHeap1 {
    int minimum = Integer.MAX_VALUE;
    Set<Integer> set = new HashSet<>();

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

        for (int i = Integer.parseInt(input.nextLine()); i > 0; i--) {
            String query = input.nextLine();
            if (query.startsWith("1")) {
                qHeap.add(Integer.valueOf(query.split("\\s")[1]));
            } else if (query.startsWith("2")) {
                qHeap.remove(Integer.valueOf(query.split("\\s")[1]));
            } else {
                System.out.println(qHeap.minimum);
            }
        }
    }

    private void add(Integer value) {
        set.add(value);
        if (value < minimum) {
            minimum = value;
        }
    }

    private void remove(Integer value) {
        set.remove(value);
        if (minimum == value) {
            minimum = Integer.MAX_VALUE;
            for (Integer newMin : set) {
                if (newMin < minimum) {
                    minimum = newMin;
                }
            }
        }
    }
}

This is a challenge found on Hacker Rank. I passed all test cases, but I'm wondering if there's a way to further increase the performance of this algorithm. Especially concerning the minimum tracking. Interestingly, SortedSet implementations timeout hence the current strategy.

I considered also tracking the second minimum, but that seems a slippery slope to also tracking the second or third, but it could conceivably eliminated having to find the minimum, I'm unsure if it makes sense, generally. What do you think?

I had no problems using a SortedSet, which is both more clear and more efficient than your implementation. You should use Scanner#nextInt() instead of parsing strings yourself.

I'm currently on a Java 6 machine. Other changes I'd suggest in Java 7+:
You should also close your scanner (use a try-with-resources block). You should prefer a PriorityQueue to a TreeSet, because as @JerryCoffin++ has already pointed out, a heap is probably the correct data structure to be using (depending on the implementation details and frequency of removes, in some cases the TreeSet may perform better).

import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;

public class QHeap1 {

    public static void main(final String[] args) {
        final Scanner input = new Scanner(System.in);
        final int numberOfCommands = input.nextInt();
        final SortedSet<Integer> set = new TreeSet<Integer>();

        for (int i = 0; i < numberOfCommands; i++) {
            final int command = input.nextInt();
            switch (command) {
            case 1:
                set.add(input.nextInt());
                break;
            case 2:
                set.remove(input.nextInt());
                break;
            case 3:
                System.out.println(set.first());
                break;
            default:
                throw new IllegalStateException();
            }
        }
    }
}


Group chars in an array if they have the same start and end elements I am trying to work through this challenge, I have come up with a solution but however I look at the problem statement and the examples provided I cant help but come to the conclusion that the "example 3" and "test case 2" as explained in the problem statement are wrong.

I would appreciate it if someone could review my solution and the problem statement and provide any feedback.

  problem statement:

  You are working on developing a movie with Amazon Video that consists
  of a series of shots: short pieces of video from a particular camera
  angle. You want to devise an application to easily group identical
  shots in a video into scenes (a sequence of shots). Shots are
  identical when they are labeled with the same letter, and everything
  in between identical shots is considered part of same scene. There is
  already an algorithm that breaks the video up into shots and labels
  them.

  Write a function which will partition a sequence of shot labels into
  minimal subsequences so that a shot label only appears in a single
  subsequence. The output should be the length of each subsequence.

  Input The input to the function/method consists of an argument -
  inputList, a list of characters representing the sequence of shots.

  Output Return a list of integers representing the length of each
  scene, in the order in which it appears in the given sequence of
  shots.

  Examples Example 1: Input inputList = [a, b, c]

  Output [1, 1, 1]

  Explanation: Because there are no recurring shots, all shots can be in
  the minimal length 1 subsequence.

  Example 2: Input inputList = [a, b, c, a]

  Output [4]

  Explanation: Because ‘a’ appears more than once, everything between
  the first and last appearance of ‘a’ must be in the same list.

  Example 3: Input: inputList = [a, b, a, b, c, b, a, c, a, d, e, f, e,
  g, d, e, h, i, j, h, k, l, i, j]

  Output: [9, 7, 8]

  Testcase 1: Input: [a, b, c, d, a, e, f, g, h, i, j, e]

  Expected Return Value: 5 7

  Testcase 2: Input: [z, z, c, b, z, c, h, f, i, h, i]

  Expected Return Value: 6 5

my solution and test cases:

using System.Collections.Generic;
using Xunit;

namespace LengthEachSceneChallenge
{
  public class Task
  {
    public List<int> lengthEachScene(List<char> inputList)
    {
        var counts = new List<int>();
        for (int i = 0; i < inputList.Count; i++)
        {
            var item = inputList[i];
            var lastIndex = inputList.LastIndexOf(item);

            if (i == lastIndex)
            {
                counts.Add(1);
            }
            else
            {
                counts.Add(i == 0 ? lastIndex + 1 : lastIndex - i + 1);
                i = lastIndex;
            }
        }
        return counts;
    }

    [Fact]
    public void Example1()
    {
        var data = new List<char>() { 'a', 'b', 'c' };

        Assert.Equal(new List<int>() { 1, 1, 1 }, lengthEachScene(data));
    }

    [Fact]
    public void Example2()
    {
        var data = new List<char>() { 'a', 'b', 'c', 'a' };

        Assert.Equal(new List<int>() { 4 }, lengthEachScene(data));
    }

    [Fact]
    public void Example3()
    {
        var data = new List<char>() { 'a', 'b', 'a', 'b', 'c', 'b', 'a', 'c', 'a', 'd', 'e', 'f', 'e', 'g', 'd', 'e', 'h', 'i', 'j', 'h', 'k', 'l', 'i', 'j' };

        Assert.Equal(new List<int>() { 9, 7, 8 }, lengthEachScene(data));
    }

    [Fact]
    public void TestCase1()
    {
        var data = new List<char>() { 'a', 'b', 'c', 'd', 'a', 'e', 'f', 'g', 'h', 'i', 'j', 'e' };

        Assert.Equal(new List<int>() { 5, 7 }, lengthEachScene(data));
    }

    [Fact]
    public void TestCase2()
    {
        var data = new List<char>() { 'z', 'z', 'c', 'b', 'z', 'c', 'h', 'f', 'i', 'h', 'i' };

        Assert.Equal(new List<int>() { 6, 5 }, lengthEachScene(data));
    }
}

}

count Length of each sequence of chars according to start and end characters

I agree that the question takes a little time to understand. Once I understood it, I felt compelled to code a solution, which is below.

The solution you built gets the length between each letter, but the question is more nuanced.  The formal logic is in the code, but in plain English: A scene only ends when all of the shots it contains are done.

On a related note, I would consider your solution to be a "procedural" approach to solving the problem.

As an object-oriented language, C# lends itself to the "object-oriented" approach, which to me means modeling the domain with classes. In this case, a Movie class and a Scene class. I initially thought there would be a Shot class, but in this example shots are reduced to character labels, so it was unnecessary.

Of course a real solution would definitely contain a Shot class, perhaps with additional properties like Camera, Lighting, and Description.

Here is the output:

Here is the sample code:

using System;
using System.Collections.Generic;
using System.Linq;

public class App_MovieScenes
{
    public void Run()
    {
        var shotList = new char[] { 'a', 'b', 'a', 'b', 'c', 'b', 'a', 'c', 'a', 'd', 'e', 'f', 'e', 'g', 'd', 'e', 'h', 'i', 'j', 'h', 'k', 'l', 'i', 'j' };
        var movie = new Movie(shotList);
        movie.ToScenes();
        movie.Output();
    }
}

public class Movie
{
    private char[] shotList;

    public List<Scene> Scenes { get; private set; }

    public Movie(char[] shotList) => this.shotList = shotList ?? new char[1];

    public void ToScenes()
    {
        var all = new string(shotList);
        var groups = new List<List<char>>();
        var group = new List<char>();
        var index = 0;

        all.ToList().ForEach(c =>
        {
            var remaining = all.Substring(index++);
            var groupIsEmpty = !group.Any();
            var anyInGroupHasMore = group.Any(g => remaining.Contains(g));

            if (groupIsEmpty || !anyInGroupHasMore)
            {
                ///start a new group
                group = new List<char>();
                group.Add(c);
                groups.Add(group);
            }
            else
            {
                ///add to current group
                group.Add(c);
            }
        });

        Scenes = groups.Select(g => new Scene(g)).ToList();
    }

    public void Output() => Console.WriteLine(ToString());

    public override string ToString() => string.Join("\n", Scenes.Select(s => s.ToShotList()));
}

public class Scene
{
    public List<char> Shots { get; private set; }
    public int Length => Shots.Count;

    public Scene(List<char> shots) => Shots = shots;

    public string ToShotList() => $"{Length}\t{string.Join(", ", Shots)}";
}


Telling the length of the highest common substring between 2 words This takes two strings and returns the length of the largest common substring.

Example:

contando_sstring_igual("abcdef", "cdofhij")
# 2

Because the longest common substring = "cd", so it returns the length of it (2).

Here is the code:

def contando_sstring_igual(string1, string2):
    resposta = ""
    tamanho1 = len(string1)
    tamanho2 = len(string2)
    for i in range(tamanho1):
        for j in range(tamanho2):
            lcs_temp = 0
            igual = ''
            while i + lcs_temp < tamanho1 and j + lcs_temp < tamanho2 and string1[i + lcs_temp] == string2[j + lcs_temp]:
                igual += string2[j+lcs_temp]
                lcs_temp += 1
            if len(igual) > len(resposta):
                resposta = igual
    return len(resposta)

while True:
    a = input()
    b = input()
    if a is None or b is None:
        break
    else:
        print(contando_sstring_igual(a, b))

I need to make my code work significantly faster. It does the job right, but not fast enough. I need to avoid the timeout error I'm getting on the exercise and I'm not even close to figuring out how to do it, without the loop.

English please!

Identifiers and comments reallly really should be in English for all code you write.  Otherwise it will be hard to impossible to take part in the completely globalized IT world we're living in.

Break long lines

Your lines shouldn't be longer than 79 characters.  Break them before binary operators:

while i + lcs_temp < tamanho1 \
      and j + lcs_temp < tamanho2 \
      and string1[i + lcs_temp] == string2[j + lcs_temp]:

performance related comments still under construction ;)

Ok, I got a bit hooked up here, and I think I've got something usable out of it.  I'm though not yet posting the code as it's late here and currently really a mess, so I'll tidy up tomorrow and post it then.

Teaser (ignore the x-axis label):

Code for measurement, though killed after size 100 due to long runtime:

for size in chain(range(10, 100, 10), range(100, 1000, 100)):
    times = map(lambda v: timeit('lcsl_{}("abcdef" * {}, "cdofhij" * {})'.format(v, size, size),
                                 globals=globals(),
                                 setup='gc.collect(); gc.enable()',
                                 number=10),
                ('danieljour', 'mateus', 'aries', 'reti'))
    print(size, '\t', '\t'.join(map(str, times)))


Find combination of sets which sum up to a specified result Example input :

  A) 1, 2

  B) 2, 8

  C) 7, 8

  Required Result : 8, 10

The output from the program with this input should be A + C.

Few notes :

We can only combine 2 sets.
There must always be exactly one pair (or a single set) which sums up to the specified result.
Input will always be in this format x,y.

Set

internal class Set
{
    protected bool Equals(Set other)
    {
        return Number01 == other.Number01 && Number02 == other.Number02;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Set) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return (Number01*397) ^ Number02;
        }
    }

    public int Number01 { get; }
    public int Number02 { get; }

    public Set(int number01, int number02)
    {
        Number01 = number01;
        Number02 = number02;
    }

    public static Set operator +(Set set1, Set set2)
    {
        return new Set(set1.Number01 + set2.Number01, set1.Number02 + set2.Number02);
    }
}

Static void Main

    static void Main(string[] args)
    {
        Console.Write("Length : ");
        int inputLength = int.Parse(Console.ReadLine());
        string[] inputSets = new string[inputLength];
        Set[] sets = new Set[inputLength];

        for (int i = 0; i < inputLength; i++)
        {
            Console.Write($"Enter set #{i + 1} : ");
            inputSets[i] = Console.ReadLine();
        }

        Console.Write("Enter the expected result : ");
        string[] answer = Console.ReadLine().Split(',');
        Set requiredResult = new Set(int.Parse(answer[0]), int.Parse(answer[1]));

        for (int i = 0; i < inputSets.Length; i++)
        {
            string[] numbersFromSet = inputSets[i].Split(',');
            sets[i] = new Set(int.Parse(numbersFromSet[0]), int.Parse(numbersFromSet[1]));
        }

        foreach (Set set in sets)
        {
            if (Equals(set, requiredResult))
            {
                Console.WriteLine("First set : " + set.Number01 + " " + set.Number02);
                Console.WriteLine("Result : " + requiredResult.Number01 + " " + requiredResult.Number02);
                Console.ReadKey();
                return;
            }
        }

        for (int i = 0; i < sets.Length; i++)
        {
            for (int j = i + 1; j < sets.Length; j++)
            {
                if (Equals(sets[i] + sets[j], requiredResult))
                {
                    Console.WriteLine("First set : " + sets[i].Number01 + " " + sets[i].Number02);
                    Console.WriteLine("Second set : " + sets[j].Number01 + " " + sets[j].Number02);
                    Console.WriteLine("Result : " + requiredResult.Number01 + " " + requiredResult.Number02);
                    Console.ReadKey();
                    return;
                }
            }
        }
        Console.ReadKey();
    }

I usually don't like the Tuple but in this case it looks like a perfect example where I think you'd be much better off if you used one instead of the Set (that I'd name Pair).

The Tuple already can do all the equality stuff so you don't need to write it yourself or you can derive your class from the Tuple so that is supports the + operator.

class Pair : Tuple<int, int>
{
    public Pair(int item1, int item2) : base(item1, item2) {}

    public static Pair operator +(Pair left, Pair right)
    {
        return new Pair(left.Item1 + right.Item1, left.Item2 + right.Item2);
    }
}

Example:

var pair1 = new Pair(1, 2);
var pair2 = new Pair(1, 2);
var pair3 = new Pair(1, 3);

(pair1.Equals(pair2)).Dump(); // True
(pair1.Equals(pair3)).Dump(); // False


Retrieving the Currently Logged in User's Department I hope this is the right place for this. I basically wrote the below script for a SharePoint 2013 where I needed to get the department of the currently logged in user.

I was finally able to get it working, but I am not happy with the structure at all:

    // globals
    var currentUser;
    var currentUserName;
    var property = "Department";
    // ctx
    var clientContext = new SP.ClientContext.get_current();
    var oWeb = clientContext.get_web();
    currentUser = oWeb.get_currentUser();
    clientContext.load(currentUser);

    GetCurrentUserProperty();

    // This function first gets the current user's firstname.lastname username (e.g. Joe.Bloggs).
    // If this is successful, it calls the LoadPropertyForUser function, which will retrieve the user's
    // property which was defined in the global "property" variable.
    function GetCurrentUserProperty(){
        clientContext.executeQueryAsync(onQueryUserSuccess, onQueryUserFail);
    }
    function onQueryUserSuccess() {
        // If the query is successful, extract the first.last username and then call LoadPropertyForUser
        window.currentUserName= currentUser.get_loginName().split("\\")[1];
        LoadPropertyForUser(window.currentUserName);
    }
    function onQueryUserFail(sender, args) {
        alert('Failed to retrieve user name');
    }

    function LoadPropertyForUser(userName){
        //Get Instance of People Manager Class
        var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
        //If you are on On-Premise:
        var targetUser = "DOMAIN1\\" + userName;
        //Create new instance of UserProfileProperty
        departmentProperty = peopleManager.getUserProfilePropertyFor(targetUser, window.property)

        //Execute the Query. (No load method necessary)
        clientContext.executeQueryAsync(onPropertyLoadSuccess, onPropertyLoadFail);
    }
    function onPropertyLoadSuccess() {
        var messageText = window.property + " is " + departmentProperty .get_value();
        alert(messageText);
    }
    function onPropertyLoadFail(sender, args) {
        alert("Error: " + args.get_message());
    }

</script>

As you can see, the GetCurretUserProperty method actually continues on in the onQueryUserSuccess function by calling LoadPropertyForUser. While this does work, I felt that this sort of layout would make a lot more sense :

function Main (property) {
    var property = "Department"
    var username = GetCurrentUserName();
    LoadPropertyForUser(username, property);
}

But I was having trouble with this because whenever I started passing variables from GetCurrentUserProperty to it's success method, I would get errors about loginName not being properly loaded.

If anyone could give me some insight as to how this would be structured I will be very grateful. I also welcome and other feedback people may have - thank you!

Overall, your code's fine. The only thing that really jumps out to me is that it clutters the global namespace with some variables; I'm not sure if that was intentional (such as if other code is then referencing those variables), but I'd try to avoid that if you can.

I understand your unease with the way the code is written, so I'm going to use the rest of this answer to (hopefully) address that concern, and then I'm going to offer some suggestions for making your code more concise and arguably more readable ...but that's admittedly a matter of personal preference.

Patterns for Asynchronous JavaScript

After working with any programming language for a while you'll start to recognize certain patterns for the "right" way to accomplish something. This is especially true of asynchronous JavaScript, which doesn't immediately mesh with the single-threaded synchronous coding mindset we programmers usually start with.

The biggest eye opener for me was to recognize that as soon as you've made your code dependent on the execution of an asynchronous function call, you should stop adding code to the current function, because when the asynchronous function actually executes, the current function will no longer be within the execution context.

// Anti-pattern: What NOT to do
function doSomething(){
    doSomethingAsync();
    doSomethingElse(); // Usually a logic error; doSomethingAsync() hasn't finished
}

Note that this also explains why you can't get a return value from an asynchronous function call.

// Another Anti-pattern
function doSomething(){
    var result = doSomethingAsync();
    doSomethingElse(result); // This is an even worse logic error!
}

The pattern for dealing with asynchronous dependencies is to move your dependent logic forward into the execution chain. This usually means passing callback functions to your asynchronous functions.

You're handing off the responsibility of executing the callback function to the new function ("Hey, you're in charge now; do this other thing once you're done.")

function doSomething(){
    doSomethingAsync(doSomethingElse);
}

Of course, to make the code more readable, you could mess with the structure of the parameters, such as by using objects with named properties...

function doSomething(){
    doSomethingAsync({whenDone: doSomethingElse});
}

function doSomethingAsync(options){
     // insert JSOM code here
     // ...
     clientContext.executeQueryAsync(
         function(){ // on success
             options.whenDone(); // if doSomethingElse wants parameters, could provide them here
         },
         function(){ // on error
         }
     );
}

Using Function Expressions

Now with all that being said, sometimes having to define multiple functions just to insert logic farther down the execution chain actually hinders readability.

A function that's only ever referenced once, and only because you need to pass it as a callback, isn't doing anything to keep your code DRY (Don't Repeat Yourself), and can make it more tedious to debug or map out the chain of execution events. For these reasons I'll often use inline function expressions instead of defined functions for callbacks.

Inline function expressions can replace your globally defined callback functions, such as onQueryUserSuccess, and onLoadPropertyFail.

I mentioned at the beginning of this answer that I dislike polluting the global namespace with variables. Using function expressions, I can refer to variables defined in the containing function without needing to attach them to the window object. (Read about closures in JavaScript to understand how this works.)

This is definitely a matter of personal preference, but I prefer the code reformatted into a single function with nested function expressions for the executeQueryAsync callbacks, like so:

function loadUserDepartment(){
    var property = "Department";
    var clientContext = new SP.ClientContext.get_current();
    var currentUser = clientContext.get_web().get_currentUser();
    clientContext.load(currentUser);
    clientContext.executeQueryAsync(
        function(){ // successfully retrieved current user
            var currentUserName = currentUser.get_loginName().split("\\")[1];
            var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
            // retrieve UserProfileProperty...
            var targetUser = "DOMAIN1\\" + userName;
            var departmentProperty = peopleManager.getUserProfilePropertyFor(targetUser, property)
            clientContext.executeQueryAsync(
                function() { // successfully retrieved property
                    alert(property + " is " + departmentProperty.get_value());
                },function()(sender, args) { alert("Error: " + args.get_message()); }
            );
        },
        function(sender,args){ alert('Failed to retrieve user name.'); }
     );
}

Now I can understand why the above code might give you heartburn. It's essentially a nested decision tree instead of a sequence of straightforward (and readable) function calls. But it's much easier for me to trace the execution chain and understand what the code is doing at a glance, and there are no variables attached to the window object (...well, except for the containing loadUserDepartment function, but you could avoid even that by converting it to an immediately executing function expression (IEFE)).

Notice that within the scope of their containing functions, the calls to clientContext.executeQueryAsync are always the last lines of code to be executed, reflecting the pattern I discussed way back at the beginning of this post.


Extremely simple stack implementation using a vector Please review my simple Stack:

template<class T>
class Stack {
public:
    Stack() = default;
    Stack(std::initializer_list<T> i) :n{} {
        for (auto& x : i) {
            elem.push_back(x);
            ++n;
        }
    }
    Stack(const Stack<T>&) = default;
    Stack(Stack<T>&&) = default;
    Stack& operator=(const Stack&) = default;
    Stack& operator=(Stack&&) = default;
    ~Stack() = default;
    int size() const {
        return n;
    }
    bool isEmpty() const {
        return (n == 0);
    }
    void push(T);
    T pop();
    T& peek();

private:
    std::vector<T> elem;
    int n;
};

template<class T>
void Stack<T>::push(T t) {
    elem.push_back(t);
    ++n;
}

template<class T>
T Stack<T>::pop() {
    if (isEmpty()) {
        throw std::out_of_range("underflow");
    }
    T t = *elem.erase(elem.end()-1);
    --n;
    return t;
}

template<class T>
T& Stack<T>::peek() {
    if (isEmpty()) {
        throw std::out_of_range("underflow");
    }
    return elem[n-1];
}

How can I make this code better and build more complicated data structures based on stacks?

Remove int n;from member variable.
Underlying container std::vector holds the size information of the stack class. It increases the size of stack class object by sizeof(int).

Remove various default definition methods from your class. Compiler would generate it for such classes. Due to these definition your class looks more verbose.

Implement all your member functions using the underlying container classes.

Prefer the standard name of your method instead of other. This way any program would easily use your custom class instead of std::stack. Change the isEmpty() to empty()

Your implementation can be simplified as below.

template<class T>
class Stack {
public:
    Stack(const std::initializer_list<T>& i):elem(i) {}
    int size() const { return elem.size(); }
    bool empty() const { return elem.empty();}
    void push(const T&);
    T pop();
    T peek();
private:
    std::vector<T> elem;
};

template<class T>
void Stack<T>::push(const T& t) {
    elem.push_back(t);
}

template<class T>
T Stack<T>::pop() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    auto x = elem.back();
    elem.pop_back();
    return x;
}

template<class T>
T Stack<T>::peek() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    return elem.back();
}


Combining RAC signals and updating UI I'm using Swift 2.1 and ReactiveCocoa 4.0.4 alpha 1. I'm combining multiple signals to enable a button based on if they have valid inputs. The following code works correctly, but I'm wondering if there is a more elegant and efficient way of accomplishing this with the ReactiveCocoa APIs, as well as if this is the proper way to be using the API in Swift.

    let sig0 = firstTextField.rac_textSignal()
        .max(self.firstTextField, max: maxLength)
        .map{ next in
            if let str = next as? String {
                return str.characters.count > 0
            } else {
                return false
            }
    }

    let sig1 = secondTextField.rac_textSignal()
        .max(self.secondTextField, max: maxLength)
        .map{ next in
            if let str = next as? String {
                return str.characters.count > 0
            } else {
                return false
            }
    }

    let combined = RACSignal.combineLatest([sig0, sig1])
    combined.subscribeNext { (obj: AnyObject!) -> Void in
        let tup = obj as! RACTuple
        let valid = (tup.first as! Bool) && (tup.second as! Bool)
        self.button.enabled = valid
    }

I'm familiar with RxSwift, not RAC. :-( That said, I think I can say something constructive about this code...

sig0 and sig1 need more descriptive names.

I would be inclined to break up the combined.subscribeNext function. Something more like:

let buttonEnabled = RACSignal.combineLatest([sig0, sig1])
    .map { obj in
        let tup = obj as! RACTuple // Wow RAC doesn't return type safe values?
        return (tup.first as! Bool) && (tup.second as! Bool)
    }

buttonEnabled.subscribeNext { obj in
    let valid = obj as! Bool
    self.button.enabled = valid
}

I strongly suspect that there is a function for mapping the buttonEnabled signal directly to the button though, maybe with an Action? You should look into that.


Is there a better way to flatten out a multidimensional list? def alist(x):
    if x == 1:
        return 1
    return [alist(x - 1), x, alist(x - 1)]
l = '%r' % alist(int(raw_input('Maximum Number Of Asterisks: ')))
f = l.replace("[", "").replace("]", "").replace(",", "").replace(" ", "")
for i in f:
    print "*" * int(i)

So, basically, I just formatted the list into a string, removed all unwanted characters (left bracket, right brakcer, comma, and space), and for every number in that string, printed the appropriate amount of asterisks. If there is anything you don't understand, sorry because I had to type this up in under 2 minutes, so please just post a comment and I'll try to answer as soon as I can.

Without many details, maybe the following can help you:

>>> import itertools
>>> list_of_lists = [['item_1'], ['item_2', 'item_3'], ['item_4', 'item_5', 'item_6']]
>>> chain = list(itertools.chain(*list_of_lists))
>>> print chain
['item_1', 'item_2', 'item_3', 'item_4', 'item_5', 'item_6']

Take a look at this question, there are some answers that might help you.


Parent implementation different to child implementation I have the following interface:

struct IFilter
{
    virtual enterClass(ClassData&, int recursiveLevel) = 0;
    virtual enterStructure(ClassData&, int recursiveLevel) = 0;
    virtual enterVariable(ClassData&, int recursiveLevel) = 0;
    virtual enterFunction(ClassData&, int recursiveLevel) = 0;
};

And here is an example of an implementation:

struct ReadOnlyFilter: public IFilter
{
    virtual enterClass(ClassData& classData, int recursiveLevel)
    {
        if(recursiveLevel==0 || classData->isReadondOnly())
        {
            this.out << "Class " << classData->name() << "\n{";
        }
    }

So items can contain classes, structs, variables and functions. A class or struct can contain items as children and grandchildren and so on. The class ReadOnlyFilter is used by a function which will loop recursively over all of the children and grandchildren etc of an item. The recursiveLevel is incremented as we go deeper and deeper, like this:

Class c (recursiveLevel=0)
{
    Variable v1 (recursiveLevel=1)
    Class cChild (recursiveLevel=1)
    {
       Class cGrandChild (recursiveLevel=2)

All my implementations have one thing in common: they should always write to this.out if the recursiveLevel is zero. This is why I have if(recursiveLevel==0 || in my code. This results in ifs everywhere in my code.

To solve this, I was thinking of doing something like this instead and was wondering if you think this is a good solution:

(I'm using C++98 and Boost)

struct IFilter
{
    virtual enterClass(ClassData&, int recursiveLevel) = 0;
    virtual enterStructure(ClassData&, int recursiveLevel) = 0;
    virtual enterVariable(ClassData&, int recursiveLevel) = 0;
    virtual enterFunction(ClassData&, int recursiveLevel) = 0;

    virtual enterChildClass(ClassData&, int recursiveLevel) = 0;
    virtual enterChildStructure(ClassData&, int recursiveLevel) = 0;
    virtual enterChildVariable(ClassData&, int recursiveLevel) = 0;
    virtual enterChildFunction(ClassData&, int recursiveLevel) = 0;
};

struct BaseFilter: public IStyler
{
    virtual enterClass(ClassData& classData, int recursiveLevel)
    {
        out << "Class " << classData->name() << "\n{";
    }

struct ReadOnlyFilter: public BaseFilter
{
    virtual enterChildClass(ClassData& classData, int recursiveLevel)
    {
        if(classData->isReadondOnly())
        {
            enterClass(classData, recursiveLevel);
        }
    }

I'm not sure what your question is about recursiveLevel, but printing only when recursiveLevel == 0 seems like pretty weird behaviour to me.  If you only care about the outermost level of your data structure, then why even bother recursing?

I'm also puzzled by what you are trying to accomplish by introducing the enterChild...() methods.  What does "child" mean — that the method should only be called when recursiveLevel > 0?

Or perhaps you mean to have ReadOnlyFilter::enterClass() chain to the superclass implementation?

struct ReadOnlyFilter: public BaseFilter {
    virtual enterClass(ClassData& classData, int recursiveLevel) {
        if (classData->isReadOnly()) {  // isReadondOnly() in original code
            BaseFilter::enterClass(classData, recursiveLevel);
        }
    }
    // etc.
}


Basic console video game This is my code for a very basic video game I created today. I did not create this to be a fun game to play. I created this to test my skills on conditional coding, etc. Please critique this.

// Created by Andrew Tew
// My Test Studio

#include <iostream>
#include <string>
using namespace std;

int main ()
{
string yay;
string actyay = "yes";
string nactyay = "no";
string EastEgg = "maybe";
string replay = "replay";
bool Chest_Unlocked;
bool Have_Knife;
bool Dead = !true;
Start:
system ("cls");
cout << "Do you pick up the knife?\n";
cin >> yay;
if (yay == actyay){
    Have_Knife = true;
}if (yay == nactyay){
    Have_Knife = false;
}if (yay == EastEgg){
    goto EasterEgg;
}

system ("cls");

cout << "Did you unlock the chest?\n";
cin >> yay;
if (yay == actyay){
    Chest_Unlocked = true;
}if (yay == nactyay){
    Chest_Unlocked = false;
}
if (Chest_Unlocked == true){
    system ("cls");
    cout << "Inside the chest is a big fat snake :O\n";
    system ("pause");
}else {

    system ("cls");
    cout << "You Lose\n";
    Dead = true;
    goto DEAD;
    system ("pause");
}
if (Have_Knife == true){
    system ("cls");
    cout << "Since you have dat handy knife you kill dat snakey\n";
    system ("pause");
}else{
    system ("cls");
    cout << "YOU DIE HAHAHAHAHAHAHA\n";
    Dead = true;
    goto DEAD;
    system ("pause");
}
if (Dead == false){
    goto EasterEgg;
}else goto DEAD;
DEAD:
if (Dead == true){
    cout << "You arise to heaven and meet God the Almighty\n";
    cout << "God says unto you...\n";
    cout << "     Thou hast lost the game of life and death";
    cout << "because of this you have come back unto my realm.";
    cout << "I give you a choice that will only come once in a lifetime.\n";
    cout << "Would you like to replay dat crappy little game or have\n";
    cout << "Fun in Heaven?\n";
    cin >> yay;
    if (yay == replay){
        goto Start;
}else {
    goto EasterEgg;
    }}

EasterEgg:
system ("cls");
cout << "You Win!";

system ("pause");
return 0;
}

Firstly you need to look at the way your code is formatted, you
should increase the indent after every opening brace.
You have a number variables that are declared and not initialised.
System ("pause") could be replaced with printf ("Press enter to continue\n"); fgetc(stdin);
GOTO there is almost never an excuse for using GOTO statements.
Try using functions to breakdown your code and eliminate repeated code, functions should be up to 20 lines long ideally, may be a hundred lines in exception circumstances.
Personally I don't like you Java style brace use.  IMO each brace should be on a separate line.
Namespaces are there to provide a way of resolving ambiguity, the using namespace std; line takes this function away. Personally I think that line should be removed and you should always prefix the calls with the namespace. In this case it will make no difference, but as you progress you might find your self calling a function in the wrong namespace because of this shortcut. Again it's just my opinion and I know people will disagree.

Try recoding it and post it again and see what I can find wrong with it next time :)


Sequence program (FizzBuzz-like) I have wrote a program which prints sequence of numbers. But if number is divisible by 4 it prints x if divisible by 7 it prints y, if divisible by both 4 & 7 it prints xy otherwise it prints number.

var sequence_function = function () {
    var result_array = [],
        start = 1,
        limit = 10;

    for(i = start; i <= limit; i ++) {
        switch (true) {
            case (i % 4 === 0 && i % 7 === 0):
                result_array.push('xy');
                break;
            case (i % 4 === 0):
                result_array.push('x');
                break;
            case (i % 7 === 0):
                result_array.push('y');
                break;
            default:
                result_array.push(i);
                break;
        }
    }

    console.log(result_array.join(','));
};

So for limit 10 it gives output:

1,2,3,x,5,6,y,x,9,10

My question if how can i optimise this code? What is best thing to use here if else, switch, ternary operator or any other? Any suggestion will be helpful.

Naming
sequence_function is not a very good name for this function. For one, we already know it's a function, no need to name as such (you don't name your variables foo_variable right?). Likewise, result_array can just be results.
Second, what does "sequence" mean in context? When you look at the code that uses this function again in 6 months, will you be able to understand what this sequence_function is for without having to go back and read the code of the function? Good naming is one of the most important aspects of maintainable code.
Let's name it multipleOf4Or7 for now. Note that camelCase naming is usually used for JS, rather than snake_case.

Conditionals
Your conditionals would read better using plain if/else if/else in my opinion. If you're using something like switch(true) it's probably a sign that it's not the best structure. Using regular conditionals, you can also reduce one conditional branch, and the code is a lot shorter.
So far...
function multipleOf4Or7() {
    var results = [],
        start = 1,
        limit = 10;

    for(i = start; i <= limit; i ++) {
        if (i % 4 === 0) {
            if (i % 7 === 0) {
                results.push('xy');
            } else {
                results.push('x');
            }
        } else if (i % 7 === 0) {
            results.push('y');
        } else {
            results.push(i);
        }
    }
    console.log(results.join(','));
};

Return from function
You ought to return the results array from the function, instead of making the function print it. The advantage of that is if you need to do something else with the result, you can just let the caller handle it and not have to modify the function. Just replace console.log(results.join(',')); with return results, then just call like this:
console.log(multipleOf4Or7().join(','));

Hard-coded values vs. Default values
Right now your function is not very flexible, because all the values are hard-coded into the function.

What if you wanted to run it for 30 instead of 10?

What if you wanted to use 3 and 5, instead of 4 and 7?

What if you wanted to use values other than x and y?

Right now, you can't do any of that without changing or copying the function. JavaScript functions can have default parameters which would make it to where regular function calls with no arguments will return the exact same results, but you do have the option to call it with different arguments.
To do that, let's move all the hard-coded values into named parameters in the function signature of a new function, and replace the hard coded values:
function multipleOfOneOrBoth(num1 = 4, num2 = 7,
                             val1 = 'x', val2 = 'y',
                             start = 1, limit = 10) {
    var results = [];
    for(i = start; i <= limit; i ++) {
        if (i % num1 === 0) {
            if (i % num2 === 0) {
                results.push(val2);
            } else {
                results.push(val1);
            }
        } else if (i % num2 === 0) {
            results.push(val2);
        } else {
            results.push(i);
        }
    }
    return results;
}

Then simply replace the existing function's body like this:
function multipleOf4Or7() {
    return multipleOfOneOrBoth();
}

You could also, instead of using default arguments, just write
function multipleOf4Or7(start = 1, limit = 10) {
    return multipleOfOneOrBoth(4, 7, 'x', 'y', start, limit);
}

With this you can easily use it for other things, for example a FizzBuzz :
console.log(multipleOfOneOrBoth(3,5,"Fizz","Buzz",1,30).join("\n"));


Suggestions for a Profiler class in Python Here's what I've right now:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import functools
import math
import time

class Timer(object):
    def __init__(self):
        self.__values = []

    def start(self):
        self.__start = time.time()

        return self

    def stop(self):
        self.__values.append(int(round((time.time() - self.__start) * 1000)))
        self.__start = None

        return self

    @property
    def average(self):
        return sum(self.__values) / len(self.__values)

    @property
    def deviation(self):
        if self.average:
            return math.sqrt(sum((v - self.average) ** 2 for v in self.__values) / self.runs)

        return 0

    @property
    def elapsed(self):
        return sum(self.__values)

    @property
    def runs(self):
        return len(self.__values)

class Profiler(object):
    __timers = {}

    @staticmethod
    def info(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        return Profiler.__timers[timer_id]

    @staticmethod
    def profile(f):
        @functools.wraps(f)
        def wrap(self=None, *args, **kwargs):
            method = self.__class__.__name__ + '.' + f.func_name if self \
                     else f.func_name

            Profiler.start(method)
            r = f(self, *args, **kwargs) if self else f(*args, **kwargs)
            Profiler.stop(method)

            return r

        return wrap

    @staticmethod
    def reset(timer_id):
        Profiler.__timers[timer_id] = Timer()

    @staticmethod
    def start(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            Profiler.reset(timer_id)

        Profiler.__timers[timer_id].start()

    @staticmethod
    def stop(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        Profiler.__timers[timer_id].stop()

if __name__ == '__main__':
    class Test(object):
        def isPrime(self, n):
            if n < 2 or (n % 2) == 0:
                return n == 2

            f = 3

            while (f * f) <= n:
                if (n % f) == 0:
                    return False

                f += 2

            return True

        @Profiler.profile
        def run(self):
            return filter(self.isPrime, range(1, 1000001))

    test = Test()

    for x in range(5):
        test.run()

    p = Profiler.info('Test.run')
    print 'runs = %d' % p.runs
    print 'elapsed = %d ms' % p.elapsed
    print 'average = %d ms' % p.average
    print 'deviation = %d ms' % p.deviation

I'm looking for suggestions to improve it and you're welcome to suggest. :)

The Profiler.profile decorator supports both functions and class methods. I've written a small test to demonstrate my profiler.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import functools
import math
import time

class Timer(object):
    def __init__(self):
        self.__values = []

You are using prefix __ to denote private attributess. This is perfectly valid and has special support within python. Having said that, I'm not a fan of it. Its designed for use when you are subclassing objects to prevent accidents. I think that if you are not designing your object to be subclassed, you should stick with single underscores.

    def start(self):
        self.__start = time.time()

        return self

Some frameworks do make use of this return self paradigm. However, its kinda unusual and will lead to code being confusing if you are not used to it. As it is you don't seem to be making use of this. I'd just get rid of return self. This doesn't seem to be the type of object which works well with the pattern anyways.

    def stop(self):
        self.__values.append(int(round((time.time() - self.__start) * 1000)))

The operations being performed here are just long enough to come across as awkward, I'd write it as

seconds_elapsed = time.time() - self.__start
milliseconds_elapsed = int(round(seconds_elapsed*1000))
self.__values.append(milliseconds_elapsed)

As another note, don't be afraid of floats. You'd probably be better off storing a list of floating point seconds rather then integer milliseconds. The code would be clearer and there is probably no noticeable difference in efficiency.

        self.__start = None

        return self

    @property
    def average(self):
        return sum(self.__values) / len(self.__values)

    @property
    def deviation(self):
        if self.average:
            return math.sqrt(sum((v - self.average) ** 2 for v in self.__values) / self.runs)

        return 0

I recommend using the numpy library which has functions to calculate average/stdev/pretty much everything. The math done in numpy will be much more efficient then your python versions.

    @property
    def elapsed(self):
        return sum(self.__values)

    @property
    def runs(self):
        return len(self.__values)

I don't like the name Timer for the class because it spends most of its effort keeping track of values not measuring time.

class Profiler(object):
    __timers = {}

    @staticmethod
    def info(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        return Profiler.__timers[timer_id]

If you are going to store state on your class object, use classmethod like so:

    @classmethod
    def info(cls, timer_id):
        if not cls.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        return cls.__timers[timer_id]

There also does not appear to be a good reason to be storing this state statically. I suggest that you really should implement this as a normal object. There are few cases where storing state on a static object is justified.

    def info(self, timer_id):
        if not self.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        return self.__timers[timer_id]

Additionally, don't be afraid of exceptions. In python you shouldn't (in general) try to detect whether an exception will be thrown before attempting an operation. Just perform the operation and catch the exception. The above version ends up locating an element in a dictionary twice, which is just a waste. The above function should be implemented as:

    def info(self, timer_id):
        try:
            return self.__timers[timer_id]
        except KeyError:
            raise Exception('Timer not started')

Similar comments apply to your other functions.

    @staticmethod
    def profile(f):
        @functools.wraps(f)
        def wrap(self=None, *args, **kwargs):

You assume that your first parameter will be self (if it exists). Depending on how this is called, self may actually already be bundled into f as a method object. Also, if you are calling a function which is not a method something else will come in there. You shouldn't capture self this way, just let all parameters go into *args

            method = self.__class__.__name__ + '.' + f.func_name if self \
                     else f.func_name

As mentioned, you shouldn't capture self the way you do. The correct place to find the class is f.im_class. Be careful! That attribute won't be there on non-methods.

            Profiler.start(method)
            r = f(self, *args, **kwargs) if self else f(*args, **kwargs)

I recomment calling r, return_value for better clarity. Also by eliminating self, you'll make this bit of code cleaner
                Profiler.stop(method)

This is actually wrong in the case of recursion as another commenter has pointed out. Also, since Timer is really concerned with keeping track of times, perhaps calculating time spent would be better here.

            return r

        return wrap

Your API is counterintuitive on this point. I'd except a function called profile to profile a function, not return a new function which I then have to call in order to profile it. For what the function does it should be called profiled.

    @staticmethod
    def reset(timer_id):
        Profiler.__timers[timer_id] = Timer()

    @staticmethod
    def start(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            Profiler.reset(timer_id)

        Profiler.__timers[timer_id].start()

    @staticmethod
    def stop(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        Profiler.__timers[timer_id].stop()

if __name__ == '__main__':
    class Test(object):
        def isPrime(self, n):
            if n < 2 or (n % 2) == 0:
                return n == 2

            f = 3

            while (f * f) <= n:
                if (n % f) == 0:
                    return False

                f += 2

            return True

        @Profiler.profile
        def run(self):
            return filter(self.isPrime, range(1, 1000001))

    test = Test()

    for x in range(5):
        test.run()

    p = Profiler.info('Test.run')
    print 'runs = %d' % p.runs
    print 'elapsed = %d ms' % p.elapsed
    print 'average = %d ms' % p.average
    print 'deviation = %d ms' % p.deviation

I think a better API to implement would be one that works like this:

    class Test(object):
        def isPrime(self, n):
            if n < 2 or (n % 2) == 0:
                return n == 2

            f = 3

            while (f * f) <= n:
                if (n % f) == 0:
                    return False

                f += 2

            return True

        @profiled
        def run(self):
            return filter(self.isPrime, range(1, 1000001))

    test = Test()

    for x in range(5):
        test.run()

    stats = Test.run.stats
    print 'runs = %d' % stats.runs
    print 'elapsed = %d ms' % stats.elapsed
    print 'average = %d ms' % stats.average
    print 'deviation = %d ms' % stats.deviation

Essentially, store your Timer object on the function object itself. That will simplify your code considerably because you are using python's name resolution rather then your own.

As a final note, there are plenty of good profiling tools out there for python. You are probably best off using one one of those.


Finding an employee from a given mother company This method finds an employee from a given mother company which consists of group of companies. An employee can work for many child company.

$scope.getEmployee = function(subsidiary, salaryScale){ //1
  var workingDepartments = [];//2
  var findInGroupOfCompanies =  function(comGroup, salaryScale){//3
                                 var salaryIndex = subsidiary[salaryScale];//4
                                 if(salaryIndex != "SUPERIOR" && salaryIndex == comGroup.salaryIndex) {//5
                                     if(comGroup.hasSubsidiaries()) { //6
                                        findInGroupOfCompanies(comGroup, salaryScale++ ); //7
                                     } else {//8
                                        workingDepartments.push(comGroup);//8
                                       //and do some stuff
                                     }
                                 }
};

The method findInGroupOfCompanies and its function is separated by equal and intended. Is this formatting not adhering to general code styles in JS? Have I added spaces unnecessarily after line number 3?

Ultimately, style considerations are subject to opinion and your actual style usually doesn't matter as much as being consistent. That said, your code might be found more readable if formatted like so:

$scope.getEmployee = function(subsidiary, salaryScale) { //1
    var workingDepartments = []; //2
    var findInGroupOfCompanies = function(comGroup, salaryScale) { //3
        var salaryIndex = subsidiary[salaryScale]; //4
        if (salaryIndex != "SUPERIOR" && salaryIndex == comGroup.salaryIndex) { //5
            if (comGroup.hasSubsidiaries()) { //6
                findInGroupOfCompanies(comGroup, salaryScale++); //7
            } else { //8
                workingDepartments.push(comGroup); //8
                //and do some stuff
            }
        }
    };

It's not necessary to indent findInGroupOfCompanies all the way to align with the equals sign. One additional level of indentation is sufficient to indicate a new block, and anybody reading the code can see that it's a new function declaration.


NewPolish - unconventional translator in Python Hello everyone!
In today's assignment I had to complete a rather unusual translator, take a look at my solution, tell me what I can do to make it better and show off yours!
Write a function that translates some text into New Polish and vice versa. Polish is translated into New Polish by taking the last letter of each word, moving it to the beginning of the word and adding ano at the beginning. Tom has a cat' becomes ['Anomto anosha anoa anotca'].
def new_polish_translator(input):

    result = ''

    content = input.replace(',', '').replace('.', '').replace('?', '').replace('-', '')

        #Dzieli na linie bez wchodzenia do nowej linii (\n)
    lines = [line.rstrip() for line in content.split("\n")]
    lines = [line for line in lines if len(line) > 0]

        #sprawdza czy nie jest przetlumaczony
    if all(line[-3::] == 'ano' for line in lines for word in line.split(' ')):
        result = ' '.join(lines)

        #sprawdza czy nie jest
    else:
        result = ' '.join('ano' + word[-1] + word[0:-1] for line in lines for word in line.split(' '))
        result = result.capitalize()

    return result

new_polish_translator("Tom has a cat")

result:
'Anomto anosha anoa anotca'

Have a great day!

Your code is reasonable, but it does get tripped up if the text (input)
contains multiple adjacent spaces or the cleaned text (content) ends up
containing multiple adjacent spaces. It also could be simplified here and
there. Some suggestions to consider: (1) parameterize the function so the user
can control which punctuation characters to remove; (2) since the algorithm is
fundamentally a word-based translation, it makes sense to convert the text to
words early; (3) the check for already-translated text is not robust to
capitalization; and (4) use the no-argument form of split() to avoid the bug
noted above. Here's one way to make those changes:
def new_polish_translator(text, replace = ',.?-'):
    # Remove unwanted punctuation.
    for char in replace:
        text = text.replace(char, '')

    # Convert to words.
    words = text.split()

    # Translate, unless the text is already New Polish.
    prefix = 'ano'
    if all(w.lower().startswith(prefix) for w in words):
        np_words = words
    else:
        np_words = [prefix + w[-1] + w[0:-1] for w in words]

    # Return new text.
    return ' '.join(np_words).capitalize()

As you know already, this problem raises some tricky questions related to how
the algorithm defines a "word". Simply splitting on whitespace and removing a
few common punctuation markers will fail to handle a variety of human language
inputs reasonably. There are other types of punctation (colon, semicolon, dash,
and some weird ones), some words have internal punctuation (apostrophe), some
words contain or even start with digits, some words convey additional meaning
with capitalization, and some texts care about internal whitespace. Consider
this specimen from Ogden Nash, and notice the details of spacing and
punctuation lost during translation:
# English.

The camel has a single hump;
The dromedary, two;
Or else the other way around.
I'm never sure. Are you?

# New Polish.

Anoeth anolcame anosha anoa anoesingl ano;hump anoeth anoydromedar ano;two anoro anoeels anoeth anorothe anoywa anodaroun anomi' anorneve anoesur anoear anouyo

Is there a a practical way to make a translator that preserves more of
those details? One approach is to use a basic tokenizing technique to decompose
the input text into various tokens, some of which will be preserved as-is and
some of which will be word-translated. These tokenizers are easy to build
because they follow a simple pattern: try to match a sequence of regular
expressions; stop on the first match; emit a Token; then re-enter the loop.
In these situations, it helps to define some simple data-objects to represent
search patterns and tokens. A sketch is shown below. It is purposely unfinished
in the sense that it is missing some error handling (eg, checking that the
patterns exhaust the text) and
it doesn't try to preserve the original word capitalization. But those
improvements are fairly easy to add if you are so inclined.
from collections import namedtuple
import re

Pattern = namedtuple('Pattern', 'kind regex')
Token = namedtuple('Token', 'kind text')

def new_polish_translator(text):
    # Define the search patterns.
    patterns = [
        Pattern('whitespace', re.compile('\s+')),
        Pattern('word', re.compile('[A-Za-z]+')),
        Pattern('other', re.compile('\S+')),
    ]

    # Translate only Token(kind=word). Preserve the rest.
    words = []
    for tok in tokenize(text, patterns):
        if tok.kind == 'word':
            w = tok.text
            words.append('ano' + w[-1] + w[0:-1])
        else:
            words.append(tok.text)

    # Return joined text.
    return ''.join(words)

def tokenize(text, patterns):
    pos = 0
    limit = len(text)
    while pos < limit:
        for p in patterns:
            m = p.regex.match(text, pos = pos)
            if m:
                txt = m.group(0)
                pos += len(txt)
                yield Token(p.kind, txt)
                break

Output:
anoeTh anolcame anosha anoa anoesingl anophum;
anoeTh anoydromedar, anootw;
anorO anoeels anoeth anorothe anoywa anodaroun.
anoI'm anorneve anoesur. anoeAr anouyo?


PHP script for getting post data from Tampermonkey script I'm trying to shorten this piece of my code into a loop:

<?php header('Access-Control-Allow-Origin: http://mysite.com'); ?>

<?php

    if(sizeof($_POST))
    {
    file_put_contents;
    } else {
    echo "ERROR! Must be activated from Tampermonkey script!";
    exit();
    }

file_put_contents(
"content.html",
" Updated last: " . $_POST['date'] . "

"  .
//Please add more entries depending on how many accounts you have configured

"Account 1
(" . $_POST['accountname1'] . ")" . "
CREDITS
" . $_POST['credits1'] . "
-
" .
"Account 2
(" . $_POST['accountname2'] . ")" . "
CREDITS
" . $_POST['credits2'] . "
-
" .
"Account 3
(" . $_POST['accountname3'] . ")" . "
CREDITS
" . $_POST['credits3'] . "
-
" .
"Account 4
(" . $_POST['accountname4'] . ")" . "
CREDITS
" . $_POST['credits4'] . "
-
" .
"Account 5
(" . $_POST['accountname5'] . ")" . "
CREDITS
" . $_POST['credits5'] . "
-
" .
"Account 6
(" . $_POST['accountname6'] . ")" . "
CREDITS
" . $_POST['credits6']);

?>

Here's the JavaScript code I'm posting with:

function bprs() {

    {
        var rowCount = $('#accountsTable tr').length;
        var accountsCount = rowCount -1;
        var accounts = [];
        for (var n = 1; n <= accountsCount; n++) {
            accounts[n] = {
                name: $('#accountName' + n).text(),
                credits: $('#credits' + n).text()
            };
        }

        var date = new Date();
        var data = "date=" + date +
            accounts.reduce(function (prev, account, n) {
                return prev + "&accountname" + n + "=" + account.name +
                    "&credits" + n + "=" + account.credits;
            }, '');

        $.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
            options.async = true;
        });

        $.ajax({
            url: 'http://mysite.com/submit.php', // point to the php file here
            async:false,
            type: "POST",
            dataType: "json",
            data: data,
            success: function (result) {
                JSON.parse(result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr);
            }
        });

Here's the post data my browser gives me:

" array(13) { ["date"]=> string(58) "Sun Dec 27 2015 11:28:53 GMT-0700 (Mountain Standard Time)" ["accountname1"]=> string(28) "*****@gmail.com" ["credits1"]=> string(3) "110" ["accountname2"]=> string(33) "*****@gmail.com" ["credits2"]=> string(3) "109" ["accountname3"]=> string(23) "*****@gmail.com" ["credits3"]=> string(3) "536" ["accountname4"]=> string(32) "*****@outlook.com" ["credits4"]=> string(3) "333" ["accountname5"]=> string(19) "*****@gmail.com" ["credits5"]=> string(3) "188" ["accountname6"]=> string(20) "*****@gmail.com" ["credits6"]=> string(2) "72" } "

What this does is post data from a web page to a PHP script on a server, then the script parses the data into an HTML file.

As it stands right now, the script requires me to add a new entry when I create a new account and add it to the page.

What I'd like is for my PHP page to generate the HTML code based on how many entries are in the post data.

A somewhat better solution would be to take advantage of the fact that PHP auto-generates arrays from REQUEST data, if the fields are named correctly. Thus I propose changing the code posted by you to the following:

var date = new Date();
var data = "date=" + date +
           "&accountsnumber=" + accountsCount +
    accounts.reduce(function (prev, account, n) {
        // Note the use of square brackets here, they tell PHP to create an array.
        return prev + "&d[" + n + "][accountname]=" + account.name +
            "&d[" + n + "][credits]=" + account.credits;
    }, '');

As for the PHP code, it'll look like this:

<?php
// Renamed this to save_contents () as that is what we're actually doing.
function save_contents()
{
    // Use intval () here to ensure that we do indeed have an integer, and not some random injection code.
    $accountnumber = intval ($_POST['accountsnumber']);

    // Validate with DateTime to verify that this is indeed a valid date.
    $date = new DateTime ($_POST['date'], new DateTimeZone (DEFAULT_TIMEZONE));

    // Format the date, and use htmlspecialchars to ensure HTML-conformity of the output.
    $str = 'Updated last: %s

';
    $output = sprintf ($str, htmlspecialchars ($date->format ("Y-m-d")))

    // Create a string template to use with sprintf (), to make the code easier to read.
    $str = 'Account %1$d
(%2$s)
CREDITS
%3$s
-<br /';

    for ($id = 1; $id <= $accountnumber; $id++) {
        // Use htmlspecialchars to protect against XSS.
        $accName = htmlspecialchars ($_POST['d'][$id]['accountname']);
        $credits = htmlspecialchars ($_POST['d'][$id]['credits']);

        $output .= sprintf ($str, $id, $accName, $credits);
    }

    file_put_contents("content.html", rtrim ($output, '
-
'));
}

As you can see I've added some basic protection against attackers as well, as the code posted by you is woefully insecure. Basically allowing whomever wants full access to your web-server, to do whatever they like!
Check out OWASP for more information.


Generic thread-safe data structure I wrote the following class so that a single object can be shared across many threads. Is using the ReaderWriterLockSlim redundant in this case and only Interlocked.Funcs() can do the job and ensure thread safety?

using System.Threading;

public class SharedData<T> where T:class
{
T _data;
ReaderWriterLockSlim _lock;

public SharedData(T arg)
{
    Interlocked.Exchange<T>(ref _data, arg);
    _lock = new ReaderWriterLockSlim();
}

public T Value
{
    get
    {
        _lock.EnterReadLock();
        var ret = Interlocked.CompareExchange<T>(ref _data, default(T), default(T));
        _lock.ExitReadLock();

        return ret;
    }
    set
    {
        _lock.EnterWriteLock();
        Interlocked.Exchange<T>(ref _data, value);
        _lock.ExitWriteLock();
    }
}
}

Using Interlocked on a class reference grants atomic transaction when you exchange an object for another;

For example, using

Interlocked.Exchange<T>(ref _data, value);

will exchange an object for an other, returning the previous object.

ReaderWriterLockSlim will protect some parts of your code, and you could also protect the object get/set with it.

Use only one of the lock, not both !

Also, you don't need usually to protect the initial set statement in your Ctor. Basically, you can only create a new object once in only one thread, before  sharing anything related to this object.

One last point, with this code you are protecting the object reference, not the object itself. See below ...

class MyString {
    public string Data {get; set;}
}
...
var myString = new MyString() ;
var mySharedString = new SharedData<MyString>(myString) ;
...
... thread 1
... mySharedString.Value.Data = "Hello" ;
...
... thread 2
... mySharedString.Value.Data = "BAD" ;

If the shared object is ReadOnly, it works, if the object is mutable, it will fail badly.


Converting polar coordinates to Cartesian coordinates I have a functional script that converts polar coordinates to Cartesian coordinates and then matches a value in a separate array to the coordinates. It works well, but I find that it takes a long time to run due to the length of the matrices being processed. Each file has four columns and 2,880,000 rows which means that I have 11,520,000 total values being processed. The data looks like this-

   [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

The array rf.190301 is a three dimensional array that looks like this-

, , 1

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

, , 2

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

, , 3

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

I'm fairly new to R and am just looking for a way to optimize what I'm trying to do in order to make it run a bit faster.

Polar2Cart <- function(x) {

Cart.x <- matrix(NA, nrow = 2880000, ncol = 4)

   for (i in 1:nrow(x)) {

      z[i]<- x[i,1]
      t[i]<- x[i,2]
      r[i]<- x[i,3]

        theta.polar[i] <- (x[i,2] * (pi/180))
        r.polar[i] <- (x[i,3] * 0.075)

            x.cart[i] <- r.polar[i]*cos(theta.polar[i])
            y.cart[i] <- r.polar[i]*sin(theta.polar[i])
            value[i] <- rf.190301[z[i], t[i], r[i]]

        Cart.x[i,] <- cbind(z[i], y.cart[i], x.cart[i], value[i])
     }
}

You are missing a key feature of the R language: "vectorization". A fancy word for saying that most functions are implemented in such a way that you can provide them vectors and they will apply the computations to each element. As an example, the multiplication function * is vectorized so you can do r.polar <- x[, 3] * 0.075 and it will return the full vector of x[i, 3] * 0.075 where i goes from 1 to nrow(x). This is less typing than doing for (i in 1:nrow(x)) { r.polar[i] <- (x[i,3] * 0.075) } and also a lot faster as you can test.

Applying that idea throughout your code, you can rewrite your Polar2Cart as follows:

Polar2Cart <- function(x) {
   z <- x[, 1]
   t <- x[, 2]
   r <- x[, 3]
   theta.polar <- t * pi / 180
   r.polar <-  r * 0.075
   x.cart <- r.polar * cos(theta.polar)
   y.cart <- r.polar * sin(theta.polar)
   value  <- rf.190301[cbind(z, t, r)]
   Cart.x <- cbind(z, y.cart, x.cart, value)
}

One thing that needs explanation is the use of rf.190301[cbind(z, t, r)]. It is a little known use of the [ function documented as follows (you can access the doc by typing ?"[")

  A third form of indexing is via a numeric matrix with one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector.

Finally, a recommendation. Be careful using single characters as variable names, since R already uses a few of them for built-in variables or functions. You could for example confuse your variable t for the t() function for transposing data. Other single character variable names used by R that come to mind are c (concatenation), q (quit), T (TRUE), F (FALSE), I (inhibit). Anyway, it is always better to use descriptive variable names and that usually implies more than one character.


Interprocess CancellationToken I have a situation where I have a program will start up another program and it will do some work.  I need to be able to stop this work if certain conditions arise.  I want to use a CancellationToken on the worker side but as far as I know these can't be used across process boundaries.

I wrote the following code to accomplish this.  There are two parts, the the controller and the worker.  Here is the code for the controller:

class Program
{
    static void Main(string[] args)
    {
        var eventName = Guid.NewGuid().ToString();

        EventWaitHandle waitHandle;
        if (!EventWaitHandle.TryOpenExisting(eventName, out waitHandle))
        {
            waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, eventName);
        }

        Process.Start("Worker", eventName);

        Console.WriteLine("Press ENTER to cancel...");
        Console.ReadLine();

        waitHandle.Set();
    }
}

Here is the code for the worker:

public sealed class EventWaitHandleCancellationTokenSource : IDisposable
{
    private readonly EventWaitHandle waitHandle;
    private readonly CancellationTokenSource cancellationTokenSource;

    public EventWaitHandleCancellationTokenSource(string eventName)
    {
        if (!EventWaitHandle.TryOpenExisting(eventName, out waitHandle))
        {
            waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, eventName);
        }

        cancellationTokenSource = new CancellationTokenSource();
        ThreadPool.RegisterWaitForSingleObject(
            waitHandle,
            delegate
            {
                cancellationTokenSource.Cancel();
            }, null, Timeout.InfiniteTimeSpan, true);

    }

    public bool IsCancellationRequested => waitHandle.WaitOne(0);
    public CancellationToken Token => cancellationTokenSource.Token;

    public void Dispose()
    {
        waitHandle.Dispose();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var cancellationTokenSource = new EventWaitHandleCancellationTokenSource(args[0]);

        Console.Write("Waiting for cancellation...");
        cancellationTokenSource.Token.WaitHandle.WaitOne();
    }
}

Is this the best way to do this?  It is the only reasonable way I can think of.

Let’s refactor it a little bit for clarity and symmetry. We could have this class shared:

class NamedTokenSource : CancellationTokenSource
{
    const string Namespace = "4978406A-A7C0-4DE7-93C8-6BDB1145ED32";

    public static implicit operator NamedTokenSource(string name) =>
        new NamedTokenSource(name);

    public NamedTokenSource(string name)
        : this(new EventWaitHandle(false, EventResetMode.ManualReset, name + Namespace))
    {
    }

    public NamedTokenSource(EventWaitHandle handle)
    {
        Handle = handle;
        ThreadPool.RegisterWaitForSingleObject(handle, (s, to) => Cancel(), null, -1, true);
        Token.Register(() => handle.Set());
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        if (disposing)
            Handle.Dispose();
    }

    EventWaitHandle Handle { get; }
}

Now Controller looks like:

NamedTokenSource cts = "WorkerTokenSource";
Console.WriteLine("Press ENTER to cancel...");
Console.ReadLine();
cts.Cancel();

when Worker is:

NamedTokenSource cts = "WorkerTokenSource";
Console.WriteLine("Waiting for cancellation...");
cts.Token.WaitHandle.WaitOne();