texts: Automate The Boring Stuff - Character Picture Grid

texts:
I understand there is another question on this already, however this is what I coded and wanted to know if this would raise any red flags?
Regarding the Character picture exercise located at the end the following page:
https://automatetheboringstuff.com/chapter4/

Say you have a list of lists where each value in the inner lists is a
one-character string, like this:
grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

You can think of grid[x][y] as being the character at the x- and
y-coordinates of a “picture” drawn with text characters. The (0, 0)
origin will be in the upper-left corner, the x-coordinates increase
going right, and the y-coordinates increase going down.
Copy the previous grid value, and write code that uses it to print the
image.
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

It's different in that it doesn't hard-code the length of the list.
grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

x = 0
y = 0

for y in range(len(grid[x])):
    for x in range(len(grid)):
        print(grid[x][y],end='')
    print()

Thanks for the help and let me know if this is not appropriate to post!


texts: Performing a procedure for each form edit

texts:
I am a bit new to programming. I have some edits on my form, and for each edit completed it will have to do a procedure.

Currently, I use this code that works perfectly, but I am looking for a better way to accomplish this task. If I add another edit not have to repeat all the code.

string rgxExpr = @"(\w+)\s([\w\s]*)"; // Pega primeiro nome
string rgxExpr2 = @"\b(\w{1})"; // Abreviação
string s1, s2, s3, s4,s5;

/* EDIT 1 */
Match match1 = Regex.Match(edtAutor1.Text, rgxExpr);
Match match2 = Regex.Match(match1.Groups[1].ToString(), rgxExpr2);
s1 = match1.Groups[2].ToString().ToUpper() + ", " + match2.Groups[1].ToString().ToUpper();
// Apenas um autor
s4 = match1.Groups[2].ToString().ToUpper() + ", " + match1.Groups[1].ToString().ToUpper();
/* EDIT 2 */
Match match11 = Regex.Match(edtAutor2.Text, rgxExpr);
Match match22 = Regex.Match(match11.Groups[1].ToString(), rgxExpr2);
s2 = match11.Groups[2].ToString().ToUpper() + ", " + match22.Groups[1].ToString().ToUpper();
/* EDIT 3 */
Match match111 = Regex.Match(edtAutor3.Text, rgxExpr);
Match match222 = Regex.Match(match111.Groups[1].ToString(), rgxExpr2);
s3 = match111.Groups[2].ToString().ToUpper() + ", " + match222.Groups[1].ToString().ToUpper();
/* EDIT 4 */
Match match1111 = Regex.Match(edtAutor4.Text, rgxExpr);
Match match2222 = Regex.Match(match1111.Groups[1].ToString(), rgxExpr2);
s5 = match1111.Groups[2].ToString().ToUpper() + ", " + match2222.Groups[1].ToString().ToUpper();

if (radioButton1.Checked == true)
{
    if (edtAutor1.Text != "")
    {
        /* Bibliográfia - 1 AUTOR */
        if (string.IsNullOrWhiteSpace(edtAutor2.Text) && string.IsNullOrWhiteSpace(edtAutor3.Text))
        {
            addbb.dataGridView1.Rows.Add(s4+". ", abntrTitulo.Text+"." , abntrEdicao.Text +" Ed. ", abntrLocal.Text + ": ", abntrEditor.Text + ", ",
            abntrAno.Text + ". ", abntrPaginas.Text +"p.");
        }

        /* Bibliográfia - 2 AUTORES */
        if (string.IsNullOrWhiteSpace(edtAutor3.Text))
        {
            if (edtAutor2.Text != "")
            {
                addbb.dataGridView1.Rows.Add(s1 + "; " + s2 + ". ", abntrTitulo.Text + ".", abntrEdicao.Text + " Ed. ", abntrLocal.Text + ": ", abntrEditor.Text + ", ",
            abntrAno.Text + ". ", abntrPaginas.Text + "p.");
            }
        }

        /* Bibliográfia - 3 AUTORES */
        if (string.IsNullOrWhiteSpace(edtAutor4.Text))
        {
            if (edtAutor1.Text != "" & edtAutor2.Text != "" & edtAutor3.Text != "")
            {
                addbb.dataGridView1.Rows.Add(s1 + "; " + s2 + "; " + s3 + ". ", abntrTitulo.Text + ".", abntrEdicao.Text + " Ed. ", abntrLocal.Text + ": ", abntrEditor.Text + ", ",
            abntrAno.Text + ". ", abntrPaginas.Text + "p.");
            }
        }

        /* Bibliográfia - 4 AUTORES */
        if (edtAutor1.Text != "" & edtAutor2.Text != "" & edtAutor3.Text != "" & edtAutor4.Text != "")
        {
            addbb.dataGridView1.Rows.Add(s1 + "; " + s2 + "; " + s3 + ";" + s5 + ". ", abntrTitulo.Text + ".", abntrEdicao.Text + " Ed. ", abntrLocal.Text + ": ", abntrEditor.Text + ", ",
            abntrAno.Text + ". ", abntrPaginas.Text + "p.");
        }
    }
    else
    {
        MessageBox.Show("Você precisa preencher todos os campos obrigátorios (*). Por favor, verifique se todos os campos estão preenchidos corretamente!");
    }

}

The code uses regex and separates the words of EDIT, reverses the order and abbreviates.


texts:
I have this web site I inherited as part of my job and it has some old code.  I'd like to optimize it, but I don't really have the time to do it right, so I'm looking for some "low hanging fruit" to optimize. Basically I want minimal change with the greatest performance improvement.

One of the things I've come across is an old static method used to grab data from a remote database:

public static IDataReader GetRS(string sql, string connString)
{
    SqlConnection dbconn = new SqlConnection();
    if (connString.ToLower().Trim() == "shop")
        dbconn.ConnectionString = ConfigurationManager.ConnectionStrings["Shop.DbConnection"].ConnectionString;
    else
        dbconn.ConnectionString = connString;
    dbconn.Open();
    SqlCommand cmd = new SqlCommand(sql, dbconn);
    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}

I think this code is contributing to a high number of NumberOfReclaimedConnections we are seeing on the servers due to the calling code not cleaning up properly.  If I rewrite the above method like the one below, will it help make things more efficient without having to rewrite all the hundreds of instances of calling code?

public static IDataReader GetRS(string sql, string connString)
{
    IDataReader ans = null;
    using (DataTable tbl = new DataTable())
    {
        using (SqlConnection dbconn = new SqlConnection())
        {
            if (connString.ToLower().Trim() == "shop")
                dbconn.ConnectionString = ConfigurationManager.ConnectionStrings["Shop.DbConnection"].ConnectionString;
            else
                dbconn.ConnectionString = connString;
            using (SqlCommand cmd = new SqlCommand(sql, dbconn))
            {
                using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                { adapter.Fill(tbl); }
            }
        }
        if (tbl.Rows.Count > 0)
        {
            ans = tbl.CreateDataReader();
        }
    }
    return ans;
}

I'm pretty sure this will do a better job at cleaning up the connection as it will be disposed before the method returns and even if there is an error it will be disposed. Does the DataTable being disposed interfere with the caller's ability to extract data from the DataTableReader?  If I do need to remove the using around the DataTable, will not cleaning up the DataTable cause similar issues to not cleaning up the SqlConnection as it is now?

I'm also open to writing this code in a completely different way as long as I'm fulfilling the following:

I don't have to rewrite code on all the calling references to this method, I just don't have time to do that right now. But it's on the list.
Due to the above requirement, the return signature has to be compatible with an IDataReader. I'm open to writing a custom class that inherits this interface if that is what helps.
The code targets and will compile in a .NET 2.0 project. We're behind the technology curve.


texts:
I have a VBA code sample that I use on a table to delete spaces in cells. I want to ask if someone has a better and quicker way to the Trim function on a table than what I have:

This is the sample:

If Sheets("Main").Cells(8, 6) = 1 Then
    strName = Sheets("Main").Cells(8, 3)
    Workbooks.Open Filename:="V:\á÷øåú ùëø\ãåçåú\ãåçåú çæåúééí\ãåçåú ìäîøä\exhr0101.csv"
    Columns(7).Delete
    Cells.Select
    Selection.Copy
    Windows("Trim all cells.xlsm").Activate
    Sheets("Data").Select
    Cells.Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    'ñâéøú çæåúé î÷åø
    Windows("exhr0101.csv").Activate
    Application.DisplayAlerts = False
    ActiveWindow.Close
    Application.DisplayAlerts = True
    'áéöåò Trim
    Windows("Trim all cells.xlsm").Activate
    Sheets("Data").Select
    For Each cell In ActiveSheet.UsedRange.SpecialCells(xlCellTypeConstants)
    cell = WorksheetFunction.Trim(cell)
    Next cell
    'äãá÷ä áâéìéåï äãá÷ä
    Cells.Select
    Selection.Copy
    Sheets("Target").Select
    Cells.Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

Here is my specific trim:

For Each cell In ActiveSheet.UsedRange.SpecialCells(xlCellTypeConstants)
cell = WorksheetFunction.Trim(cell)
Next cell


texts:
I've wrote the code for Project Euler #15 and it runs amazingly fast. I know I can write it using binomials but I wanted to calculate by brute force as if I do not know Binomials. But I think it must be taking huge amount of memory so I want to know how I can reduce amount of memory used by program. I've tried to reduce elements in the Dictionary as much as possible but I cannot think of any other thing.

import time

st = time.clock()
results = {}

def routes(a, b):
    if a > b:
        a, b = b, a
    if a == 0:
        return 1
    if a == b:
        if str([a - 1, b]) in results:
            return 2 * results[str([a - 1, b])]
        else:
            part1 = routes(a - 1, b)
            results[str([a - 1, b])] = part1
            return 2 * part1

    if str([a - 1, b]) in results:
        part1 = results[str([a - 1, b])]
    else:
        part1 = routes(a - 1, b)
        results[str([a - 1, b])] = part1
    if str([a, b - 1]) in results:
        part2 = results[str([a, b - 1])]
    else:
        part2 = routes(a, b - 1)
        results[str([a, b - 1])] = part2
    return part1 + part2

number = int(input("Enter n : "))
#print((routes(20, 20)))
print((routes(number, number)))
#print((results))
print((len(results)))
print(("Time took : ", time.clock() - st))

Output 1:

Enter n : 20
Answer = 137846528820
Number of elements in hashtable/dictionary are 229
Time took : 0.002663 seconds.

Output 2:

Enter n : 480
Answer = 250892214537448775747234101104975594366453286042769782121222122282812207368859289614865150179674097028772541144903685677912632260432728444419421872981795600499773664936037617507243883516784270458848737326769427370361260166492752950426905484595009507753796738842521345046644373977709359600

Number of elements in hashtable/dictionary are 115919
Time took : 0.483901 seconds.


texts: Using parser_combinators to parse a string

texts:
I am playing with Rust, and am trying to write a simple parser.

I need to parse the string:

"0123,456789"

into a stucture:

Passport { label : i8 = 0, body : i32 = 123456789 }

I am using parser_combinators and my code is working, but very ugly.

How can I rewrite this code?

extern crate parser_combinators as pc;
 use pc::*;
 use pc::primitives::{State, Stream};

 fn main() {
     match parser(parse_passport).parse("a123,456") {
         Ok((r,l)) => println!("{} {} {}", r.label, r.body, l),
         Err(e) => println!("{}", e)
     }
 }

 struct Passport {
     label : i8,
     body  : i32,
 }

 fn parse_passport<I>(input: State<I>) -> ParseResult<Passport, I> where I: Stream<Item=char> {
     let mut label = digit().map(|i : char| (i as i8) - ('0' as i8));
     let mut fst = many1(digit()).map(|string : String| string.parse::<i32>().unwrap());
     let (i,input) = match label.parse_state(input) {
         Ok((x,n)) => (x,n.into_inner()),
         Err(e) => return Err(e)
     };
     let (f,input) = match fst.parse_state(input) {
         Ok((x,n)) => (x,n.into_inner()),
         Err(e) => return Err(e)
     };
     let (_,input) = match satisfy(|c| c == ',').parse_state(input) {
         Ok((x,n)) => (x,n.into_inner()),
         Err(e) => return Err(e)
     };
     let (s,input) = match fst.parse_state(input) {
         Ok((x,n)) => (x,n),
         Err(e) => return Err(e)
     };
     let p = Passport { label : i, body : f * 1000000 + s };
     Ok((p, input))
 }


texts: Using LINQ or Lambda instead of nested and multiple foreach statements

texts:
I want to use a better syntax than nested foreach statements to overwrite the initial list with items from the second list.

In the code below:

I want to overwrite initialList with those in secondList that have the same Value (Remove Red).
Use the items in secondList where Value was the same (Yellow)

New initialList list should include (Green and Yellow).

static void Main(string[] args)
{
    int useProd = 2;
    int useDomain = 0;

    var person1 = new Person() { prodId = 1, Value = "foo", domainId = 0, Name = "Red" };
    var person2 = new Person() { prodId = 1, Value = "bar", domainId = 0, Name = "Green" };
    var person3 = new Person() { prodId = 1, Value = "foo", domainId = 1, Name = "Yellow" };

    var initialList = new List<Person>();
    initialList.Add(person1);
    initialList.Add(person2);

    var secondList = new List<Person>();
    secondList.Add(person3);

    List<Person> personsToRemove = new List<Person>();
    List<Person> personsToUpdate = new List<Person>();

    foreach (var pers1 in initialList)
    {
        foreach (var pers2 in secondList)
        {
            if (pers1.Value == pers2.Value)
            {
                personsToRemove.Add(pers1);
                personsToUpdate.Add(pers2);
            }
        }
    }
    foreach (var remPers in personsToRemove)
    {
        initialList.Remove(remPers);
    }
    foreach (var updPers in personsToUpdate)
    {
        initialList.Add(updPers);
    }
    foreach (var item in initialList)
    {
        Console.WriteLine(String.Format("Value: {0}, prodId: {1}, domainId: {2}, Name: {3}", item.Value, item.prodId, item.domainId, item.Name));
    }

    Console.ReadKey();
}
public class Person
{
    public int prodId { get; set; }
    public string Value { get; set; }
    public int domainId { get; set; }
    public string Name { get; set; }
}


texts: A simple AngularJS application for counting the number of gallons of paint

texts:
I created a simple Angular JS application for calculation gallons of paint needed to paint the ceiling of a room.

I assume one gallon covers 350 square feet and use it as a constant.
Also, I round up a counting of the gallons to the next whole number.
Now my code seems to me too simple).

I will be grateful for advice as it is possible to complicate this task with the use of AngularJS or next version of Angular.

angular.module('my-App', [])
 .controller('paintCalculatorController', function($scope){
  $scope.length = 0;
  $scope.width = 0;
  const squareFeetForOneGallon = 350;
  $scope.square = function(){
   return $scope.length * $scope.width;
  }
  $scope.countGallon = function(){
   return Math.ceil($scope.length * $scope.width / squareFeetForOneGallon);
  }
 });
form{
 background-color: #f1f1f1;
 border-radius: 5px;
 }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Room ceiling area

  <form class="inline-form mt-3 py-3">
  Length:
  <input style="width:90px" type="number" ng-model="length" value="" name="" min="0" oninput="validity.valid||(value='');">
   feet
   X
  Width :
  <input style="width:90px" type="number" ng-model="width" value="" name="" min="0" oninput="validity.valid||(value='');">
   feet
    </form>

You will need to purchase {{countGallon()}} gallons of
 paint to cover {{square()}} square feet.


texts: How to verify if HTML table sort is stable or not?

texts:
I have implemented a HTML table sorting. I actually implemented a sort first using jQuery and then modified it based on the answer to this question for performance as I had done the same mistake. My question is how to make sure if the code I have written is stable or not?

I know that the stability of sorting depends on the sort method's algorithm and that changes with the browser, and according to this page, mozilla's implementation of sorting is stable, but when I checked with my code, it doesn't seem to be stable. Could someone have a look at my code and let me know how to determine whether the sort performed is stable or not?

                    Month
                    Savings

                    March
                    180

                    January
                    100

                    February
                    80

                    Januray
                    40

                    March
                    200

                    February
                    90

And if there can be any improvements for efficiency, can anyone point that out as well?


texts:
My solution to LeetCode problem Most Frequent Subtree Sum works, but I have several questions regarding the code. I am also looking for an advice on how to improve the code.

  Problem:

  Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

  Example 1

  5
 /  \
2   -3

  return [2, -3, 4], since all the values happen only once, return all of them in any order

  Example 2

  5
 /  \
2   -5

  return [2], since 2 happens twice, however -5 only occur once

My questions:

The function get_sums_freqs returns an int, but when I call it, I do not assign the result to anything: get_sums_freqs (root, sum_freqs);. Is it ok to do it this way?
For some reason, it feels like a bad style to me to initialize the hash map unordered_map<int, int> sum_freqs; in one function and then pass it to another function to fill it out. Is there a better way to do it? Or is this a correct way?

My solution:

vector<int> find_frequent_tree_sum(TreeNode* root) {

    // Collect freqs of sums into map
    unordered_map<int, int> sum_freqs;
    get_sums_freqs (root, sum_freqs);

    // Get the max freq
    int max_freq = 0;
    unordered_map<int, int>::iterator it;
    for (it = sum_freqs.begin(); it != sum_freqs.end(); ++it) {
        max_freq = max(max_freq, it->second);
    }

    // Collect all the values, which freq == max_freq
    vector<int> res;
    //unordered_map<int, int>::iterator it;
    for (it = sum_freqs.begin(); it != sum_freqs.end(); ++it) {
        if (it->second == max_freq) {
            res.push_back(it->first);
        }
    }

    return res;
}

int get_sums_freqs (TreeNode* root, unordered_map<int, int>& sum_freqs) {

    if (root) {

        int curr_sum = root->val +
            get_sums_freqs (root->left, sum_freqs) +
            get_sums_freqs (root->right, sum_freqs);

        sum_freqs[curr_sum]++;

        return curr_sum;

    } else {

        return 0;
    }
}

For context, here's the definition of TreeNode given by LeetCode:

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


texts: Getting partition boundaries in sorted integer array using only equalTo operator

texts:
For my task, I need to find partition boundaries in sorted input. Values are expected to be repeated, I just need to find range for each value. Please check comment in following output for example.
For some reason, I can not use < or > operation, I only have equality operator.

/*
Input:
Index :  Value
0 : 1
1 : 1
2 : 1
3 : 2
4 : 2
5 : 2
6 : 2

Output:
Value 1 is till 2 index
Value 2 is till 6 index
   */
   public void printPartitionBoundaries(ArrayList<Integer> array)
   {
      int f = 0;
      int l = array.size()-1;
      while (f < l) {
         int cp = ((Integer)array.get(f)).intValue();
         int of = f;
         boolean done = false;
         while (!done)
         {
            int m = (f + l)/2;
            if ((l-f) <= 1) {
               if ( l == array.size() -1 )
                  System.out.println("Value " + cp + " is till " + l + " index");
               else
                  System.out.println("Value " + cp + " is till " + (l-1) + " index");
               done = true;
               break;
            }
            if (array.get(f).equals(array.get(l)) == false) {
               if (array.get(f).equals(array.get(m)) == false)
                  l = m;
               else
                  f = m;
            } else {
               f = m;
            }
         }
         f = l;
         l =  array.size()-1;
      }
   }


texts:
I wrote an algorithm which should cut a companies name into 3 strings.

  Input: 1 String

  Output: 3 String.

  Conditions:

  String 1 2 and 3 shall not be longer then 35 signs. If the Input string is longer then it should be cut to a length of 105.

If you have fun and be interested in algorithms it would be nice if you take a look at it.

   Public Sub CompanyCut()
  //3 output Strings
    Dim var1 As String = ""
    Dim var2 As String = ""
    Dim var3 As String = ""

    If Module1.insertdict("company").Length > 35 Then

        Dim s1 As String = Module1.insertdict("company").ToString

        If s1.Length > 105 Then
            s1 = Microsoft.VisualBasic.Left(s1, 105)
        End If

        //Split String into array at every Whitespace
        Dim pattern As String = "\s"
        Dim sa() As String = Regex.Split(s1, pattern)

        //Variables for loop
        Dim i As Integer = 0
        Dim varyn As Boolean = True
        Dim varyn1 As Boolean = False
        Dim varyn2 As Boolean = False

        //loop which fills var1 var2 and var3 with arrayfields untill size 35
           would be reached

        For i = 0 To sa.Length - 1

            If var1.Length < 35 AndAlso varyn = True Then
                If var1.Length + 1 + sa(i).Length < 35 Then
                    var1 = var1 + " " + sa(i).ToString
                Else
                    varyn = False
                    varyn1 = True
                    varyn2 = False

                End If

            End If

            If var2.Length < 35 AndAlso varyn1 = True Then
                If var2.Length + 1 + sa(i).Length < 35 Then
                    var2 = var2 + " " + sa(i).ToString
                Else
                    varyn1 = False
                    varyn = False
                    varyn2 = True

                End If

            End If

            If var3.Length < 35 AndAlso varyn2 = True Then
                If var3.Length + 1 + sa(i).Length < 35 Then
                    var3 = var3 + " " + sa(i).ToString
                Else
                    varyn2 = False

                End If

            End If

        Next

        //my idea was that if it has the same or bigger length all fields must
          be in + the whitespaces

            If var1.Length + var2.Length + var3.Length >= s1.Length Then

            Module1.insertdict("Firma") = var1
            Module1.insertdict("Name2") = var2
            Module1.insertdict("Name3") = var3

        Else

            //this occurs when the string is smaller as 105 signs but not all
              fields  of the array could be placed in the variables.

            Module1.insertdict("Failure") = "Company name need to split by user"

        End If

    Else

        Module1.insertdict("Name2") = ""
        Module1.insertdict("Name3") = ""

    End If

End Sub

  **Edit: I forgot to bring up in the Conditions that if it is possible it should be cut at >the whitespace.

  What to do now? shall I open a new Post?**

My main problem is to find a sub algorithmn which  handles this case

Else

        //this occurs when the string is smaller as 105 signs but not all
          fields  of the array could be placed in the variables.

        Module1.insertdict("Failure") = "Company name need to split by user"

End If

An easy way would be to  cut it with substring like in the answers.
a more elegant way would be to cut the first 35 chars for  the first variable and then trying to cut at whitespaces. If it doesnt works also cut the second 35 for var2. and the rest is going to var3 :)


texts: Takes a list and return a dict of distinct values pointing to a list of index locations of each value

texts:
I came up with a way to get a dict of distinct elements in a list pointing to the location of each element; it works, but I feel pretty awful about this code, it's very ugly. Is there a more natural/pythonic way to do this?
from itertools import groupby
sample_data = [1,2,3,3,1,0,5]
give_groups = lambda dta: {item: list(map(lambda z: z[0], list(item_group))) for item, item_group in itertools.groupby(list(enumerate(dta)), lambda x:x[1])}
print(give_groups(sample_data))

{1: [4], 2: [1], 3: [2, 3], 0: [5], 5: [6]}

The performance is also bad.
Created this alternate that does work, but is kinda slow:
def alt_grouping(dta):
    retdict = defaultdict(list)
    for position, item in enumerate(dta):
        retdict[item].append(position)
    return retdict


texts: Generating histograms from "chunked" large data streams

texts:
I've been working in some tools lately that analize long streams of data and extract frequent patterns, histograms, etc. for personal use. Lately I've been coding a histogram generator; that is, given a long chunked data stream, generate a histogram with all distinct chunks; typical case, given a text, generate a word histogram.

The algorithm and code I've come up with is the following:

public static class HistogramGenerator
{
    public static IEnumerable<HistogramItem<T>> GetHistogram<T>(IEnumerable<IEnumerable<T>> stream)
        => BuildHistogram(BuildTree(stream));

    private static Tree<T> BuildTree<T>(IEnumerable<IEnumerable<T>> stream)
    {
        var tree = new Tree<T>();

        foreach (var chunk in stream)
        {
            var currentTree = tree;

            foreach (var item in chunk)
            {
                currentTree = currentTree.Add(item);
            }

            currentTree.Count++;
        }

        return tree;
    }

    private static IEnumerable<HistogramItem<T>> BuildHistogram<T>(Tree<T> tree) =>
        getAllCurrentTreeReversedPaths(tree).Select(histogram =>  new HistogramItem<T>(histogram.Count, histogram.Path.Reverse()))
                                        .OrderByDescending(h => h.Count);

    private static IEnumerable<HistogramItem<T>> getAllCurrentTreeReversedPaths<T>(Tree<T> tree)
    {
        foreach (var branch in tree.Branches)
        {
            if (branch.Value.Count > 0)
            {
                //Make sure we return a valid path included in a longer one. For example: "the" inside "therefore"
                yield return new HistogramItem<T>(branch.Value.Count, new[] { branch.Key });
            }

            foreach (var subBranch in getAllCurrentTreeReversedPaths(branch.Value))
            {
                yield return new HistogramItem<T>(subBranch.Count, subBranch.Path.Concat(new[] { branch.Key }));
            }
        }
    }

    //TODO: Check if this is should be kept as a struct.
    public struct HistogramItem<T>
    {
        public int Count { get; }
        public IEnumerable<T> Path { get; }

        public HistogramItem(int count, IEnumerable<T> path)
        {
            Path = path;
            Count = count;
        }
    }

    private class Tree<T>
    {
        public int Count { get; set; }
        public Dictionary<T, Tree<T>> Branches { get; }

        public Tree()
        {
            Branches = new Dictionary<T, Tree<T>>();
            Count = 0;
        }

        public Tree<T> Add(T value)
        {
            Tree<T> branch;

            if (!Branches.TryGetValue(value, out branch))
            {
                branch = new Tree<T>();
                Branches.Add(value, branch);
            }

            return branch;
        }
    }
}

I'm reasonably happy with how it performs (aprox. 60 ms to analyze a 1.4+ million character long stream with 260k+ chunks).

Still, as a learning process, and because I know my limitations writing software (I'm relatively new though I'm trying hard to learn fast) I'd appreciate any feedback that could help optimize my code, make it more elegant and readable or pointers to alternative "simple" (if any) algorithm that would perform better.


texts: How to make string.Format template more readable?

texts:
Have a look to the following example. Clearly it's very hard to understand the meaning of each parameter passed to the string.Format to be replaced to the numeric sequence of {0}, {1}, ...

I want to improve the software quality: Maintainability\Code readability
http://en.wikipedia.org/wiki/Software_quality

The problem is also bound to the difficulty of associating numbers to the corrisponding values in the template. i.e. at a first glance what is the meaning of {8}?

               @"<?xml version='1.0'?>
                <RemoteXMLData>
                    <Username agent_diff_type=""{10}"" usertype=""{5}"" ticket_language=""{6}"" min_slip_stake=""{7}"" max_stake=""{8}"" location=""{9}"">{0}</Username>
                    <Password>{1}</Password>
                    <Reseller>{2}</Reseller>
                    <Function>AutoLogin</Function>
                    <AppKey>{3}</AppKey>
                    <Sub>{4}</Sub>
                </RemoteXMLData>";

What should I change?

string autoLoginRequest = String.Format(
AutoLoginRequestTemplate,
username,
password,
Config.Val1,
Config.Val2,
requestSub,
Language,
minValue,
maxValue,
agentDiffType);


texts: Convert a Binary Tree to Doubly Linked List

texts:
Challenge

Link on geeksforgeeks: Binary Tree to DLL

  Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL)
  In-Place. The left and right pointers in nodes are to be used as
  previous and next pointers respectively in converted DLL. The order of
  nodes in DLL must be same as Inorder of the given Binary Tree. The
  first node of Inorder traversal (left most node in BT) must be head
  node of the DLL.

  Your Task:

  You don't have to take input. Complete the function bToDLL() that
  takes node and head as parameter. The driver code prints the DLL both
  ways.

The following code is given. Class Node may not be changed. Method bToDLL must be implemented, but its signature may not be changed.

class Node
{
    Node left, right;
    int data;

    Node(int d)
    {
        data = d;
        left = right = null;
    }

}

// This function should convert a given Binary tree to Doubly Linked List
class GfG
{
    Node head;
    Node bToDLL(Node root)
    {
        // TODO .. convert tree and store the result as head
    }
}

Solution

As pointed out in the comments, a solution is required to be in-place. This is what I came up with. Any type of feedback is invited.

class GfG
{
    Node head;
    Node bToDLL(Node root)
    {
        head = first(reduce(root));
        return head;
    }

    void append(final Node source, final Node node) {
        source.right = node;
        node.left = source;
    }

    Node reduce(final Node node) {
        if (node == null) return node;
        Node prev = reduce(node.left);
        Node next = reduce(node.right);
        if (prev != null) append(last(prev), node);
        if (next != null) append(node, first(next));
        return node;
    }

    Node first(Node node) {
        while (node.left != null) node = node.left;
        return node;
    }

    Node last(Node node) {
        while (node.right != null) node = node.right;
        return node;
    }
}


texts: Aggregation of a collection of object's nested array-properties

texts:
Use Case

So our lead programmer loves to follow the NIH Anti-Pattern and consequently I'm not allowed to use Underscore.js and can only use Vanilla JS... and we have to support IE8.

The goal is to produce an aggregation of unique values from nested collections buried within various collections of objects.

Desired Interface

The idea is to call a function to create an aggregation function give the list of the nested properties.

Example

The following would flatten all options collection that are buried under each object within the properties property.

var allUniqueOptions = aggregateByProperty('properties', 'options');
var allUniqueDoodadsOptions = aggregateByProperty('doodad', 'properties', 'options');

allUniqueOptions(myCollection);
allUniqueDoodadsOptions(myDoodadCollection);

Current Code

The code below works, but I'd like any advice on improving it for:

performance
readability
any further generalization

I have a jsFiddle created.

/* Returns the index of an object within a collection */
function arrayObjectIndexOf(arr, obj) {
    var search = JSON.stringify(obj);
    for ( var i = 0, k = arr.length; i < k; i++ ){
        if (JSON.stringify(arr[i]) == search) {
            return i;
        }
    };
    return -1;
};

/* Concatentates objects that don't exist in the source collection */
function concatIfNotExists(source, additions) {
    var result = source;
    for ( var i = 0, k = additions.length; i < k; i++ ) {
        var addition = additions[i];
        if (arrayObjectIndexOf(result, addition) === -1) {
            result.push(addition);
        }
    };
    return result;
};

/* Returns a nested collection buried within an object */
function getInnerCollection(obj, props) {
    var innerCollection = obj;

    for (var j = 0, l = props.length; j < l; j++) {
        if (innerCollection.hasOwnProperty(props[j])) {
            innerCollection = innerCollection[props[j]];
        } else {
            throw new TypeError("Property doesn't exist!");
        }
    }

    if (!innerCollection instanceof Array) {
        throw new TypeError("Inner property is not a collection!");
    }
    return innerCollection;
};

/* Returns an aggregation of objects based on collection properties */
function aggregateByProperty() {
    var props = Array.prototype.splice.call(arguments, 0);

    return function(objectCollection) {
        var result = [];
        for (var i = 0, k = objectCollection.length; i < k; i++) {
            var innerCollection = getInnerCollection(objectCollection[i], props);
            result = concatIfNotExists(result, innerCollection);
        }
        return result;
    }
};


texts:
I have a simple implementation for "Async.sequence" (the name came from here), but I would like someone to review it for performance, tail call optimization, and functional style.

It has the following signature, which is similar to Async.Parallel:

Async<'a> list -> Async<'a list>

Async.Parallel would be ideal for performance, but it may be important to run the operations in order even though they happen to be async.

let sequence list =
    let rec loop l acc =
        async {
            match l with
            | [] ->
                return List.rev acc
            | h::t ->
                let! h' = h
                return! loop t (h'::acc)
        }
    loop list []

Update

I came up with a minimal implementation built from other basic operations: map + apply (to get map2) and retn. cons is just a helper for the :: operation, since that is not actually a function in F#.

let sequenceList list =
    List.foldBack (map2 cons) list (retn [])

It is probably better to use a library already built, but I like defining these functions myself to better understand how the operations relate. Now that I have the formulation of sequence, I can literally copy and paste this code into my Result module which also has its own map2 and retn defined, and it will work the same.


texts:
Its working but I don't think its the best way of doing it. I also changed variable names just to let you know,

       string [] columnN = AnotherString.Split(',');  //Another String is something like this = "HEhehehehehE heeh, aSKdjhkaaksjd, asldkhja slkdlk, asdajsdlka, asdljkasd, asdkasjdasd, asdasdasdl, askdjasd"
                AnotherString = "";
                int i = 0;

            foreach (string cN in columnN)
            {
                if (!string.IsNullOrEmpty(Res.ResourceManager.GetString(cN.ToLower().Trim())))
                    AnotherEmptyString += Res.ResourceManager.GetString(cN.ToLower().Trim());
                else
                    AnotherString += cN;
                i++;

                if (i < columnN.Length)
                    AnotherString += ",";
            }

I saved all resources in lower case, also if in case cN doesn't got any resource won't it will give an exception.


texts:
My homework assignment:

  Write a function called saddle that finds saddle points in the input matrix M. For the purposes of this problem, a saddle point is defined as an element whose value is greater than or equal to every element in its row, and less than or equal to every element in its column. Note that there may be more than one saddle point in M. Return a matrix called indices that has exactly two columns. Each row of indices corresponds to one saddle point with the first element of the row containing the row index of the saddle point and the second element containing the column index. If there is no saddle point in M, then indices is the empty array.

My solution:

function ind=saddle(matrix)

size_=size(matrix);
a=[];
for ii=1:size_(1)

    for jj=1:size_(2)
        if (matrix(ii,jj)==max(matrix(ii,:))) && (matrix(ii,jj)==min(matrix(:,jj)))
            a=[a;[ii ,jj]];
        end
    end
end
ind=a;


texts: SPOJ GENERAL: sorting by swaps of distance k

texts:
I have been trying to solve this simple problem on SPOJ for quite some time now, but I keep on getting TLE (Time limit exceeded) for some reason.

Since the problem is in Portuguese, a brief description of the problem is like this (without the story):

  You are given an array of size N, you have to arrange the array in
  ascending order, such that an element can only be swapped with
  elements which are at a distance k from it. If the array can be
  sorted then print the number of swaps required to arrange them in
  ascending order, if it cannot be sorted print impossivel.

This is my code:

#include <iostream>
#include <cstdio>

using namespace std;
int a[100005];
int main() {
    int t;
    int n, k;
    scanf("%d", &t); //number of test cases
    while(t--) {
        scanf("%d %d", &n, &k);
        bool result = true;
        int count = 0;

        for(int i = 0; i < n; i++) {
            scanf("%d", &a[i]);
        }

        for(int i = n; i > 0; i = i - k) {
            int j = 0;
            for( ; j < i - k; j++) {
                if(a[j] > a[j + k]) {
                    int temp = a[j];
                    a[j] = a[j + k];
                    a[j + k] = temp;
                    count++;
                }
            }

            for( ; j < i - 1; j++) {
                if(a[j] > a[j + 1]) {
                    result = false;
                    break;
                }
            }

            if(!result)
                break;
        }
        if(result)
            printf("%d\n", count);
        else
            printf("impossivel\n");
    }
}

My logic : I perform N/k iterations on the array. I initialize the loop variable i to N. In each iteration I check i-k elements with the element at a distance k from it, if they are to be swapped then I swap them and increment the number of swaps needed, else I do nothing. Then I check the elements from i-k to i, if they are in ascending order, if not I break the loop and print "impossivel", else I change i to i-k and again perform the loop. By my logic after every iteration the last k elements will be in ascending order, if is possible to sort them, since at every step I move the elements which are greater to the right.

Does this seem correct to you? How can optimize this further?


texts: Using Choose and Apply Templates with Mode, vs Complexless Template Matches

texts:
So I have a little XML (Sub)language,
it has 3 elements of interest: para, point, and code

If a code occurs inside a para, point element I want to handle it for inline use,
if not, i want to set it up as it's own display section

Currently I'm doing it like so:

  <xsl:template match="code">
    <xsl:choose>
      <xsl:when test="exists(ancestor::para) or exists(ancestor::point)">
        <xsl:apply-templates select="." mode="inline"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:apply-templates select="." mode="display"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="code" mode="inline">
    <xsl:value-of select="."/>
  </xsl:template>

  <xsl:template match="code" mode="display">

<xsl:value-of select="."/>

  </xsl:template>

Instead of doing it like that i could have just two templates,
one for display and one for inline, and set up the match expressions to work out which it was.

Which is better?


texts: Fast way to calculate source response using Green's function

texts:
I am a newbie in the scientific computing in python. The function I am trying to calculate is the response of the wave equation for a given source term (For reference, See: Equation 11.67 in https://webhome.phy.duke.edu/~rgb/Class/phy319/phy319/node75.html).

$$\phi(\pmb{x},t) = \int_V G_+(\pmb{x}, t; \pmb{x'}, t)\rho(\pmb{x'}, t')d^3x'dt'$$

To give context, the term phi in the equation 11.67 is the displacement and the term rho can be thought as a source of disturbance.

Now, in my case, the problem is constructed in spatial dimension of 2 (x-y). Thus, I have to iterate the equation for grid points in x, y and t. This makes the overall calculation extremely time-consuming. Below is my lines of code:

import numpy as np

# Assigning grid points

Nx = 100
Ny = 100
Nt = 100

x = np.linspace(-Nx, Nx, 100)
y = np.linspace(-Ny, Ny, 100)
t = np.linspace(0, Nt-1, 100)

# Equation to solve
# phi(x,y,t) = ∫∫∫ G(x,y,t; x',y',t') . Source(x',y',t') dx' dy' dt'
# G(x,y,t; x',y',t') = Green's Function

# phi = displacement by the wave
phi = np.zeros((Nt,Ny,Nx))

# Define Function to realize Green's Function for Wave Equation
def gw(xx, yy, tt, mm, nn, ss):

    numer = (tt-ss) - np.sqrt((xx-mm)**2+(yy-nn)**2)
    denom = ((tt-ss)**2-(xx-mm)**2-(yy-nn)**2)

    if denom < 0:
        denom = 0
    else:
        denom = np.sqrt(denom)

    kk = np.heaviside(numer,1)/(2*np.pi*denom+1)
    return (kk)

# Define Function to realize Gaussian Disturbance
def g_source(xx, yy, tt):

    spatial_sigma  = 5   # spatial width of the Gaussian
    temporal_sigma = 30  # temporal width of the Gaussian
    onset_time     = 20  # time when Gaussian Disturbance reaches its peak

    kk = np.exp((-(np.sqrt((xx)**2+(yy)**2)/spatial_sigma)**2)))*np.exp(-((tt-onset_time)/temporal_sigma)**2)
    return (kk)

for k in range (Nt):
    for j in range (Ny):
        for i in range (Nx):

            # this is the Green's function evaluated in each grid points
            green = np.array([gw(x[i],y[j],t[k],i_grid,j_grid,k_grid) for k_grid in t for j_grid in y for i_grid in x])
            green = green.reshape(Nt, Ny, Nx)

            # this is the source term (rho), here it is a Gaussian Disturbance
            gauss = np.array([g_source(i_grid,j_grid,k_grid) for k_grid in t for j_grid in y for i_grid in x])
            gauss = gauss.reshape(Nt, Ny, Nx)

            # performing integration
            phi[k,j,i] = sum(sum(sum(np.multiply(green,gauss))))

Please let me know if there is a faster way to do this integration. Thanks in advance. I deeply appreciate your patience and support.


texts: Searching in a lock-free ordered single-linked list

texts:
The code below represents a lock-free ordered single-linked list, and is a modification of the algorithm proposed in this doc.

How can I improve speed of searching (lookingup) in the list maintaining lock-free capability? Any suggestions, code modifications, examples, maybe other lock-free data structures?

typedef uintptr_t               marked_ptr_t;
#define PTR_OF(x)               ((Node*)(x))
#define CONSTRUCT(ptr)          ((uintptr_t)ptr)
#define CAS(ADDR, OLDV, NEWV)   __sync_val_compare_and_swap((ADDR), (OLDV), (NEWV))
#define INCR(ADDR, INCVAL)      __sync_fetch_and_add((ADDR), (INCVAL))

typedef struct
{
    void            *value;
    uint64_t        key;
    marked_ptr_t    next;
} Node;

typedef struct
{
    marked_ptr_t    bucket;
    uint32_t        size;
} LF_List;

void *lf_list_get(LF_List*, uint64_t);

void *lf_list_put_if_absent(LF_List*, uint64_t, void*);

int lf_list_remove(LF_List*, uint64_t);

void* lf_list_find(marked_ptr_t* head, uint64_t key, marked_ptr_t** prev, marked_ptr_t* cur, marked_ptr_t* last)
{
    marked_ptr_t* tp_prev;
    marked_ptr_t tp_cur, tp_last;
    marked_ptr_t* tp_next;

    uint64_t cur_key;
    void* cur_value;

    tp_prev = head;
    tp_cur  = *head;
    tp_last = (marked_ptr_t)NULL;

    while(1)
    {
        if (PTR_OF(tp_cur) == NULL)
        {
            if(prev){*prev = tp_prev;};
            if(cur){*cur = tp_cur;};
            if(last){*last = tp_last;};

            return NULL;
        }

        tp_next = &PTR_OF(tp_cur)->next;

        cur_key = PTR_OF(tp_cur)->key;
        cur_value = PTR_OF(tp_cur)->value;

        if (key >= cur_key)
        {
            if(prev){*prev = tp_prev;};
            if(cur){*cur = tp_cur;};
            if(last){*last = tp_last;};

            return key == cur_key ? cur_value : NULL;
        }

        tp_last = tp_cur;
        tp_prev = tp_next;
        tp_cur = *tp_next;
    }
}

void* lf_list_get(LF_List* table, uint64_t key)
{
    return lf_list_find(&table->bucket, key, NULL, NULL, NULL);
}

void* lf_list_put_if_absent(LF_List* table, uint64_t key, void* value)
{
    marked_ptr_t* prev;
    marked_ptr_t cur, last;
    marked_ptr_t new_node;

    while(1)
    {
        if(lf_list_find(&table->bucket, key, &prev, &cur, &last) != NULL)
        {
            return PTR_OF(cur)->value;
        }

        new_node = CONSTRUCT(calloc(1, sizeof(Node)));

        PTR_OF(new_node)->value = value;
        PTR_OF(new_node)->key = key;

        PTR_OF(new_node)->next = *prev;

        if(CAS(prev, cur, new_node) == cur)
        {

            INCR(&table->size, 1);
            break;
        } else {
            free(PTR_OF(new_node));
            continue;
        }
    }
    return NULL;
}

int lf_list_remove(LF_List* table, uint64_t key)
{
    marked_ptr_t cur, last;
    marked_ptr_t *prev;

    while(1)
    {
        if(lf_list_find(&table->bucket, key, &prev, &cur, &last) == NULL)
        {
            return 0;
        }

        if (CAS(prev, cur, PTR_OF(cur)->next) == cur) {

            free(PTR_OF(cur));
            INCR(&table->size, -1);
            return 1;
        } else {
            continue;
        }
    }

    return 0;
}


texts:
I need to implement the Matlab filter(b,a,x) function in Java. Before I do this, I would like to rewrite the function in Matlab before translating into Java. So far, writing out all the coefficients works really well. See below:

x = load('data.csv');
windowSize = 10;
b = (1/windowSize)*ones(1,windowSize); % b coefficient - a is unused
i = 1;
for n = length(b) : length(x) % yes I know I am losing my first 10 samples
    y(i,:) = [ b(1)*x(n) + b(2)*x(n-1) + b(3)*x(n-2) + b(4)*x(n-3) + ...
        b(5)*x(n-4) + b(6)*x(n-5) + b(7)*x(n-6) + b(8)*x(n-7) + ...
        b(9)*x(n-8) + b(10)*x(n-9) ];
    i = i+1; % used for indexing calculated results into new array
end

However, I want the loop contents to automatically update when I change the window size. In the above example, if I were to increase the windowsize by a factor of two, then I would have to write out twice as many multiples of b and x within the for loop. Which is a terrible solution to my problem. Please advise.


texts: How can I extract these similar codes into only one method?

texts:
I have implemented three ways of Singleton idiom in Java, and now I want to write some test code to see there performance. Here is my code:

public static void main(String...args) {
    long startTime, endTime;
    int MAX_ITE = Integer.MAX_VALUE;

    // Eagerly initialized static instance guarantees thread safety.
    startTime = getCurrentTime();
    for(int i = 0; i < MAX_ITE; i++) {
        IvoryTower.getInstance();
    }
    endTime = getCurrentTime();
    System.out.println("Hungry initialization time:" + (endTime - startTime));

    // Double check locking, thread safe.
    startTime = getCurrentTime();
    for (int i = 0; i < MAX_ITE; i++) {
        ThreadSafeDoubleCheckLocking.getInstance();
    }
    endTime = getCurrentTime();
    System.out.println("Lazy initialization time:" + (endTime - startTime));

    // On demand holder
    startTime = getCurrentTime();
    for (int i =  0; i < MAX_ITE; i++) {
        InitializationOnDemandHolder.getInstance();
    }
    endTime = getCurrentTime();
    System.out.println("On demand holder time:" + (endTime - startTime));
}

These blocks of codes are very similar, but since getInstance() is static, I don't know how to extract each block into a same method call. Can anyone help?


texts: FIrst time trying tree classifier in python

texts:
Recentely I have started teaching myself some basic AI concepts and this was my first attemp at using a random forest in order to classify the iris data set. It would be great if anyone could give me any sort of feedback on the code, specifically the style and readability. I apologize if the code block is formatted incorrectly (this is my first time using stack exchange). Thank you!

import numpy as np
from sklearn.model_selection import cross_validate
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split

# Data goes through preprocessing, Label encoding is used to map
# String identifiers to float

def data_processor(input_file):
    data = []
    with open(input_file, 'r') as f:
        for line in f:
            line = line.strip().split(',')
            if line[-1] == 'Iris-setosa':
                line[-1] = 0
            elif line[-1] == 'Iris-versicolor':
                line[-1] = 1
            elif line[-1] == 'Iris-virginica':
                line[-1] = 2
            data.append(line)

    return np.array(data, dtype=float)

# create array of data and array of index
x, y = data_processor('iris.txt')[:, :-1], data_processor('iris.txt')[:, -1]

# create training and test data set, 80% training 20% test
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.20,
                                                random_state=5)

# params used to create classifier
# number of trees - 150, node depth - 5, random seed
params = {'n_estimators': 150, 'max_depth': 5, 'random_state': 10}
classifier = ExtraTreesClassifier(**params)
classifier.fit(x_train, y_train)
# make prediction
y_test_pred = classifier.predict(x_test)

# output info on model performance
class_names = ['Setosa', 'Versicolor', 'Virginica']
print("Training dataset results\n")
print(classification_report(y_train, classifier.predict(x_train),
                            target_names=class_names))
print("Testing dataset results\n")
print(classification_report(y_test, y_test_pred, target_names=class_names))


texts:
I have Implemented Unique_Ptr with move semantics for the sake of Learning. Any suggestions, feed backs are highly appreciated.

// author @asad_nitp
#pragma once

namespace Smart_Pointers {
template<typename T>

class Unique_Ptr {
    T* m_ptr;
public:
    explicit Unique_Ptr(T* ptr = nullptr) noexcept
        : m_ptr(ptr)
    {}

    ~Unique_Ptr() noexcept {
        if (m_ptr != nullptr) {
            delete m_ptr;
        }
        m_ptr = nullptr;
    }

    Unique_Ptr(const Unique_Ptr&) = delete;
    Unique_Ptr& operator = (const Unique_Ptr&) = delete;

    Unique_Ptr(Unique_Ptr&& ob) noexcept {
        m_ptr = ob.m_ptr;
        ob.m_ptr = nullptr;
    }
    Unique_Ptr& operator = (Unique_Ptr&& ob) noexcept {
        if (this != &ob) {
            m_ptr = ob.m_ptr;
            ob.m_ptr = nullptr;
        }
        return *this;
    }

    T* operator -> () const noexcept {
        return m_ptr;
    }

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

    T* get() const noexcept{
        return m_ptr;
    }

    T* release() noexcept {
        T* ans = m_ptr;
        m_ptr = nullptr;
        return ans;
    }

    void reset(T* ptr = nullptr) noexcept {
        T* old = m_ptr;
        m_ptr = ptr;
        if (old != nullptr)
            delete old;
    }

    void swap(Unique_Ptr& ob) noexcept {
        using std::swap;
        swap(m_ptr,ob.m_ptr);
    }

 };
}
  //Examples
  int main() {
     Smart_Pointers::Unique_Ptr<int> up1(new int(5));
     Smart_Pointers::Unique_Ptr<int> up2(new int(6));
     up1 = up2; // Error
     up1 = std::move(up2); //fine

     return 0;
   }


texts: Is this a sufficient way to prevent script injections and other bad stuff in strings

texts:
Would this function be sufficient enough to remove all malicious code and foreign characters from a string?

//Clean the string
$out = ltrim($do);
$out = rtrim($out);
$out = preg_replace('/[^(\x20-\x7F)]*/','', strip_tags($out));

This data is not going into a SQL database, so I dont have to worry about sql injection attempts. Is there any way to improve my code and make it more efficient?

This function would clean any user inputted data (forms, and ?), and then save it do a database. This would be used in a global sanitizing function.


texts: Proper way to insert a record and assign the id to the Entity object

texts:
Scenario: I need to insert a record in a database and use the id resulting from that operation for every other operation needed.

So I've created a class that contains all details of the object that needs to be persisted in the database and added an Id field to store the record id returned by the database operation.

public class MetadataObject {
    protected long Id { get; private set; }
    protected long RegistrationDate { get; private set; }
    protected long FileName { get; private set; }

    public MetadataObject(string fileName)
    {
        FileName = fileName;
        RegistrationDate = DateTime.Now;
    }
}

1) Once I create a MetadataObject, the Id property is 0 (not initialized). Then I make the call to the database.

metadata.Id = RegisterMetadataAndReturnId(metadata);

2) Another thing that I could do is to assign a value to the Id field immediately after I get it back from the database. The method that handles this would look like this

public void RegisterMetadata(MetadataObject metadata)
{
    long recordId;
    var metadataInsert = CreateStoredProcedure("RegisterMetadata");
    metadataInsert.Execute();

    [assign recordId with value received from stored procedure]

    metadata.Id = recordId;
}

Second version looks better in my opinion, the only doubt I have is if the method calling the stored procedure must make sure the metadata object Id property is set before exiting. Or is it better if I just return the Id value and let the calling procedure take care of that.

Is there a better/cleaner way of getting this done?


texts: Calculating the 'binary gap' of a number

texts:
Inspired by this question and therefore this one I decided that clearly the best most readable way to solve this is with Regular Expressions.

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.

I decided to remove the limit of positive numbers only.
Here's the code:
public static int ComputeLargestBinaryGap(int value)
{
    var regexp = new Regex("(?<=1)(0+)(?=1)");
    var valueAsBinary = Convert.ToString(value, 2);
    return
        regexp.Matches(valueAsBinary)
            .Cast<Match>()
            .Select(m => m.Value)
            .DefaultIfEmpty(string.Empty)
            .Max(s => s.Length);
}

You'll notice that this can be trivially extended to also work for long or any number representation you can convert to a string binary representation.
I appreciate that's a pretty small amount of code to review but would be intrigued as to whether there's anything I could improve.
For the record, my first actual solution was bit shifting an unsigned int but I stand by the Regular Expression solution.


texts:
I'm looking for a way to have an logarithmic incremental counter. The counter goal is related to a numeric value than goes from 1 to Infinity. The counter maximum value should be 1000.
The sequence looks like this:

number is below 10, increment by 1:

1,2,3...7,8,9,10
number is above 10, increment by ^10 when the number reaches the counter

100, 1000 stop at 1000

This is what I wrote so far (javascript):

let i = 0
let mod = 10
let result = document.getElementById('result')
result.innerText = ''

while (++i < 7322) {
  mod *= mod < 1000 && i === mod * 10 ? 10 : 1

  if (i < 10 || i % mod === 0) {
    //the further the `i` value is, the less this will be called
    result.innerText += i + ' pass the test. Mod is ' + mod + '.\n'
  }
}

I'm sure there is a more elegant way of doing this but can't get my hand on it. Do you have ideas on how to simplify the algorithm?


texts:
I need to simplify this code as well as a Linq query:

 var data = from linq_row in trend_data.AsEnumerable()
                       group linq_row by linq_row["questionnaire_uniquename"] into g

                       select new
                       {
                           questionnaire_uniquename = g.First<DataRow>()["questionnaire_uniquename"].ToString(),
                           question_name = g.First<DataRow>()["question_name"].ToString(),
                           question_score_type = g.First<DataRow>()["question_score_type"].ToString(),
                           sparkline_data = g.Select(s => s["trend_score"].ToString()).ToArray()
                       }; ;
            int rowspan = 2;

Based on some condition, I am adding just adding filtering to an existing query and modifying the selected query here. Instead of selecting question_name, I want to select response_label from a data table.

if (criteria.CorporateSummaryExpand == "1")
{
    data =
       from linq_row in trend_data.AsEnumerable()
       group linq_row by linq_row["questionnaire_uniquename"] into g
       where g.First<DataRow>()["questionnaire_uniquename"].ToString() != "[Questionnaire].[Questionnaire].[Question].&[OFSP]&[OFSP5000]"
       && g.First<DataRow>()["questionnaire_uniquename"].ToString() != "[Questionnaire].[Questionnaire].[Question].&[OFSP]&[OFSP5008]"
       && g.First<DataRow>()["questionnaire_uniquename"].ToString() != "[Questionnaire].[Questionnaire].[Question].&[OFSP]&[OFSP1130]"

       select new
       {
           questionnaire_uniquename = g.First<DataRow>()["questionnaire_uniquename"].ToString(),
           question_name = g.First<DataRow>()["response_label"].ToString(),
           question_score_type = g.First<DataRow>()["question_score_type"].ToString(),
           sparkline_data = g.Select(s => s["trend_score"].ToString()).ToArray()
       };
    rowspan = 4;
}


texts: Time interval class that enhances constructor argument handling of its parent class

texts:
I am making a subclass of a well-established python class:  pendulum.Period, which overrides both __new__ and __init__ (it does this because it is subclassing the python builtin class timedelta, which uses __new__).

In my case, I want my class to handle a wider range of arguments than the superclass.  The only way I have managed to get the code to work is to duplicate my handling code in both __new__ and __init__ -- this is because, per the documentation, the arguments passed to __new__ are then passed to the __init__ of the new instance, unaltered.

The result is repeated code execution. Is this avoidable?

from pendulum import Period, Date

def _toDate(val):
    """
    Convert various inputs into a Date
    """
    if isinstance(val, int) or isinstance(val, float):
        return Date.fromtimestamp(val)
    elif isinstance(val, tuple):
        return Date(*val)
    return Date(val.year, val.month, val.day)

class MyInterval(Period):
    def __new__(cls, start, end, inclusive=True, **kwargs):
        start = _toDate(start)
        end = _toDate(end)

        if inclusive:
            end = end.add(days=1)

        return super(MyInterval, cls).__new__(cls, start, end, **kwargs)

    def __init__(self, start, end, inclusive=True, **kwargs):
        """
        Creates a pendulum Period where the interval is limited to whole
        days. Both are cast to dates, then the end date is incremented by
        one day if inclusive=True
        :param start: cast to date
        :param end: cast to date
        :param inclusive: [True] whether the last day of the interval should
          be included (increments by 1 day)
        """
        start = _toDate(start)
        end = _toDate(end)

        if inclusive:
            end = end.add(days=1)

        super(MyInterval, self).__init__(start, end, **kwargs)


texts: Send single notification script until state change

texts:
I could not find the script I was looking for, so I made my own with the knowledge I have at this moment.

This is my custom PHP script to send a single notification/SMS/email when a script or site is either offline or online.  It could be set to run by cron every x minutes, but only send a notification after the state has changed from offline to online or vice-versa.  The state is remembered/saved in the toggle.txt file in the same directory.

I tested this and it works the way it should. For simplicity, the $site variable is the place where the server/site check would be and output wither ON or OFF (I used AAN/UIT here, to not confuse with ONLINE or OFFLINE written to the toggle.txt).  This could also be used for other purposes, with the same construction.

I would like to know what you think of this script and if and how it can be improved. Maybe a version without the external toggle.txt requirement, but to have it stored all in the same php file?

<?php
$site = 'AAN';
$file = 'toggle.txt';
$memory = file_get_contents($file);

 if (strpos($site,'UIT') !== false) // Site status OFFLINE
{
            if (strpos($memory,'OFFLINE') !== false) // when Memory ONLINE
            {
            // do nothing - send mail/sms script here.
            echo "We know server is OFFLINE - No alerts to send.";
            }
            else // when Memory OFFLINE
            {
            echo "ALERT: Your Server is OFFLINE"; // send notification
            $memory = "OFFLINE";
            }
}
 else // Site status ONLINE
{
            if (strpos($memory,'ONLINE') !== false) // Memory ONLINE
            {
            // do nothing - send mail/sms script here.
            echo "We know server is ONLINE - No alerts to send.";
            }
            else // when Memory OFFLINE
            {
            echo "ALERT: Your Server is Online"; // send notification
            $memory = "ONLINE";
            }
}

file_put_contents($file, $memory);
?>


texts: Override equals() and hashCode() using reflection

texts:
I wrote a utility method to override equals() using reflection. This works fine, but I wonder if this code will pass all the tests.

public static boolean checkObjectsEqualityFromInstance(Object currentObj,Object otherObj) throws Exception{
      if(currentObj==null || otherObj==null){
          return false;
      }
      else if(otherObj.getClass()!=null&&currentObj.getClass()!=null&&!currentObj.getClass().isInstance(otherObj)){
          return false;
      }
      boolean result =true;
        Field[] fields = otherObj.getClass().getDeclaredFields();
        Field[] currentObjFields = currentObj.getClass().getDeclaredFields();

        Map<String, Object> attriButeNameValueMap=null; /*This map to store *property name and its value of any of object in my calse the otherObj */
        try {
            attriButeNameValueMap=new HashMap<>();
            for (Field field : fields) {
                field.setAccessible(true);

                Object value = field.get(otherObj);
                attriButeNameValueMap.put(field.getName(), value);
            }
            for (Field field : currentObjFields) {
                field.setAccessible(true);

                Object value = field.get(currentObj);
                if(attriButeNameValueMap.containsKey(field.getName())){
                    if(value instanceof Boolean){
                result=areEqual((Boolean)value, (Boolean)attriButeNameValueMap.get(field.getName()));
                    }
                    else if(value instanceof Character){
                        result=result&&areEqual((Character)value, (Character)attriButeNameValueMap.get(field.getName()));
                            }
                    else if(value instanceof Long){
                        result=result&&areEqual((Long)value, (Long)attriButeNameValueMap.get(field.getName()));
                    }
                    else if(value instanceof Float){
                        result=result&&areEqual((Float)value, (Float)attriButeNameValueMap.get(field.getName()));
                    }
                    else if(value instanceof Double){
                        result=result&&areEqual((Double)value, (Double)attriButeNameValueMap.get(field.getName()));
                    }
                    else if(value instanceof Object[]){
                        result=result&&  Arrays.equals((Object[])value, (Object[])attriButeNameValueMap.get(field.getName()));
                    }
                    else{
                        result=result&&areEqual(value, attriButeNameValueMap.get(field.getName()));

                    }
                    if(!result){
                        return result;
                    }
                }
                else{
                    return false;
                }
            }

        } catch (IllegalArgumentException | IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
throw e;
        }
        return result;
    }

The areEqual() methods are overloaded for different types.


texts: Regex for a string with at least a letter and no repeating dash

texts:
I had a problem a few days back and had to find a regex that matches a string that:

Contains only letters in the alphabet [a-z0-9-] so lowercase latin letters, numbers 0 to 9, and the dash character
Must contains at least a letter [a-z]
Must not contains repeating dashes. abc-def-gh is ok but not abc--def
The size of the string must be between 1 and 10 characters

I came up with:

^(?=[a-z0-9-]*[a-z][a-z0-9-]*)(?:[a-z0-9]|[-](?![-])){1,10}$

A little explanation:

(?=[a-z0-9-]*[a-z][a-z0-9-]*) lookahead to find if the string contains at least a letter
(?:[a-z0-9]|[-](?![-])){1,10} A non capturing group (not really important to capture or not I believe) with two parts, that must be between 1 and 10 chars

[a-z0-9] any letter in the alphabet I want
[-](?![-] a dash then a negative lookahead to see if there is no dash following

Here is a list of strings that should not match:

#should not match
-
1
1-
-1
aaaaaaaaaaaaaaaaa
11111
2a2--af
a2a--22

And a list of string that should match:

#should match
a
a-
-a
a-2
a2a
2a2-
a2a-2a2
a-b-c-d
a123213232
123213213a
a12321322a

HERE you can find an online regex tester to play with it.

All improvements, remarks, feedbacks is welcome. My guts is telling me the lookahead can be improved but I did not find how. Also, I'm not even sure the lookahead is needed at all. I'm eager to improve my regex skill so if you have any alternative method also I'd be really glad to know.


texts: Find largest binary gap of a number N improved

texts:
This is a follow-up question based on the original one. Could you please see the updated and refactored version and point at things to be improved in term of logic or efficiency?

I have now know as I have been made aware about the Greedy Algorithm; Math.Max and binary shifting which deal more gracefully with the task, however, if I were in a position to be unaware of them and this is the code I managed to write, what's your thoughts on it?

    public static int FindGap(int number)
    {
        string toBinary = Convert.ToString(number, 2);
        char[] toChar = toBinary.ToCharArray();

        char previous = '0';
        char current = '0';
        int maxGap = 0;
        int answer = 0;

        for (int i = 0; i < toChar.Length; i++)
        {
            if (toChar[i] == '1')
            {
                current = toChar[i];

                // keep last/latest largest gap as an answer
                if (answer < maxGap)
                {
                    answer = maxGap;
                }

                // reset if 1 appeared and start counting next gap
                maxGap = 0;
            }
            if ((toChar[i] == '0' && current == '1') || (toChar[i] == '0' && previous == '0'))
            {
                current = '0';
                maxGap++;
                previous = current;
            }
        }

        if (answer != 0)
        {
            return answer;
        }
        else return 0;
    }


texts: Updated bash/zsh function that cd to the root of git tree

texts:
here's the updated version of the code for being reviewed. Fixes:

"private" _cg function
functions definition as cg() {}
general clean-up

#!/bin/bash

# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
cg() {
  _cg() {
    local top; top="$(git rev-parse --show-cdup)"
    top="${top:-./}"
    local super_root; super_root="$(git rev-parse --show-superproject-working-tree)"
    if [[ "$super_root" ]]; then
      printf '%s' "$top../"
      ( cd "$top../" && _cg || return )
    fi
    printf '%s' "$top"
  }
  local git_root
  git_root="$(_cg)"
  [[ "x${git_root}" != "x./" ]] && cd "${git_root}" && return || return 0
}


texts: GPA calculator, implemented for a course

texts:
This is from a Java course which I'm taking. The class StudentUtil, including method-declarations and comments, was provided by the instructor. I just had to finish the bodies of the two methods.

calculateGPA() computes the average performance of students. Every A-grade gives 4 points, every B-grade 3 and every C-grade 2 point.

calculateGPA() returns students which have performed within a specified range.

The StudentUtil class:

package modul;

import java.util.ArrayList;

public class StudentUtil {

    public static double[] calculateGPA(int[] studentIdList, char[][] studentsGrades) {
        double[] grades = new double[studentIdList.length];
        int i = 0;

        for (char[] studentGrade : studentsGrades) {
            double sumGrades = 0.0;

            for (char grade : studentGrade) {
                if (grade == 'A') {
                    sumGrades += 4;
                } else if (grade == 'B') {
                    sumGrades += 3;
                } else {
                    sumGrades += 2;
                }
            }
            grades[i++] = sumGrades / studentGrade.length;
        }

        return grades;
    }

    public static int[] getStudentsByGPA(double lower, double higher, int[] studentIdList, char[][] studentsGrades) {
        // perform parameter validation. Return null if passed parameters are not valid
        if (lower < 0.0) {
            return null;
        }

        if (higher > 4.0) {
            return null;
        }

        if (lower > higher) {
            return null;
        }

        if (studentIdList.length != studentsGrades.length) {
            return null;
        }
        // invoke calculateGPA
        double[] gpas = calculateGPA(studentIdList, studentsGrades);
        ArrayList<Integer> ids = new ArrayList<>();

        for (int i = 0; i < studentIdList.length; i++) {
            if (gpas[i] >= lower && gpas[i] <= higher) {
                ids.add(studentIdList[i]);
            }
        }
        // construct the result array and return it. You would need an extra for loop to compute the size of the resulting array
        int[] ret = new int[ids.size()];

        for (int i = 0; i < ret.length; i++) {
            ret[i] = ids.get(i);
        }

        return ret;
    }

}

My test class:

package modul;

import static java.lang.System.out;
import java.text.DecimalFormat;
import static java.lang.System.out;

public class Sandbox {

    public static void main (String[] args) throws Exception {
        int[] studentIdList = { 1001, 1002 };
        char[][] studentsGrades = { { 'A', 'A', 'A', 'B'  }, { 'A', 'B', 'B' } };

        double[] results = StudentUtil.calculateGPA(studentIdList, studentsGrades);

        for (double result : results) {
            out.printf("%.2f\n", result);
        }

        int[] ids = StudentUtil.getStudentsByGPA(3.2, 3.5, studentIdList, studentsGrades);

        for (int result : ids) {
            out.println(result);
        }
    }
}

It has passed the automated test.

But what do you think about the demand of returning null when the validation of getStudentsByGPA() fails? Would one really do that this way? Or would one throw some specific exception instead, IllegalArgumentException for example?

What do you think about my code in general? What would you have done else and why?


texts:
I have learned the question of solving Angular app optimization for search engines, and was frustrated that the most recommended option is prerendering HTML.

After some time spent, I suggested to create a directive that will load the bot after rendering templates or update scope.

Directive:

angular.module('test', []).directive('seoBot', ['$timeout', function($timeout){

    return {

        link: function($scope, element, attrs) {

            //publish event
            $scope.$on('runbot', function(){

                //hint for start after render
                $timeout(function () {

                    //find previos google's bot
                    var googleBot = document.getElementById('googleBot');

                    //if found - remove
                    if(googleBot) googleBot.parentNode.removeChild(googleBot);

                    //this is standard code from GA, but with ID "googleBot"
                    (function(i,s,o,g,r,a,m){
                        i['GoogleAnalyticsObject']=r;
                        i[r]=i[r]||function(){
                            (i[r].q=i[r].q||[]).push(arguments)
                        },i[r].l=1*new Date();
                        a=s.createElement(o),
                        m=s.getElementsByTagName(o)[0];
                        a.id="googleBot";
                        a.async=1;
                        a.src=g;
                        m.parentNode.insertBefore(a,m);
                    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

                    ga('create', 'UA-46685745-1', 'rktdj.com');
                    ga('send', 'pageview');

                    //log that bot is loaded
                    console.log("seo-bot loaded");

                    //check page to be rendered completely
                    console.log(document.body.innerHTML);

                }, 0, false);

            });

        }

    };

}]);

In controller:

//get some data from server and update scope
$http.get(GLOBAL.api.SERVER_PATH + GLOBAL.api.facultiesByCourse + s_id)
        .success(function (data) {

            $scope.courses = data;
            console.dir($scope.courses);

            //broadcast event to seo-bot
            $scope.$broadcast('runbot');

        } );

seo-bot tag in the bottom of template:

It works, and the bot loads every time when template have update or route changed.
I can check that all elements with data was rendered before.

But... will this solution really work? Will Google bot correctly correlate rendered page with the domain? Can I be banned for this?


texts:
My code has a nasty smell that looks like this:

@RequestMapping(value = { "/updateGraph" }, method = RequestMethod.POST)
public ResponseEntity<ArrowsGraph> updateGraph(@RequestBody ArrowsGraph g){
    try{
        g = arrowsBo.updateGraph(g);
        return new ResponseEntity<ArrowsGraph>(g, HttpStatus.OK);
    } catch (Exception e) {
        errorLogging.logFatalException(e,  sessionState);
        return new ResponseEntity<ArrowsGraph>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

@RequestMapping(value = { "/deleteGraph" }, method = RequestMethod.POST)
public ResponseEntity<ArrowsGraph>  deleteGraph(@RequestBody ArrowsGraph g){
    try{
        g = arrowsBo.deleteGraph(g);
        return new ResponseEntity<ArrowsGraph>(g, HttpStatus.OK);
    } catch (Exception e) {
        errorLogging.logFatalException(e,  sessionState);
        return new ResponseEntity<ArrowsGraph>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Things to mention:

The exceptions being caught are runtime exceptions, likely thrown if the database mapping is configured incorrectly. If the code is working correctly, exceptions should never be thrown, but in the case there is an error, I want to display an error the client side, instead of having unintended behaviour.
The reason I'm using ResponseEntity<..> instead of @ResponseBody is so I can return a 500 in the case that an exception is thrown.
The purpose of errorLogging.logFatalException(...) is to log the error, and notify admins.

Before I refactored to use ResponseEntity<...> and catch the runtime exceptions, the methods looked a lot cleaner:

@RequestMapping(value = { "/deleteGraph" }, method = RequestMethod.POST)
public ArrowsGraph  deleteGraph(@RequestBody ArrowsGraph )
     return arrowsBo.deleteGraph(g);
}

Is there a nice way to avoid this repetition/boilerplate?


texts:
I'm trying to write simple parser using regexes. This is what I currently have, it looks really messy. Any tips what can I change?
from re import compile
from typing import Dict, Iterator, List, NamedTuple, TextIO

# PATTERNS
registers_pattern = list(map(compile, [
  r'(rax=[0-9a-f]{16}) (rbx=[0-9a-f]{16}) (rcx=[0-9a-f]{16})\n',
  r'(rdx=[0-9a-f]{16}) (rsi=[0-9a-f]{16}) (rdi=[0-9a-f]{16})\n',
  r'(rip=[0-9a-f]{16}) (rsp=[0-9a-f]{16}) (rbp=[0-9a-f]{16})\n',
  r' (r8=[0-9a-f]{16})  (r9=[0-9a-f]{16}) (r10=[0-9a-f]{16})\n',
  r'(r11=[0-9a-f]{16}) (r12=[0-9a-f]{16}) (r13=[0-9a-f]{16})\n',
  r'(r14=[0-9a-f]{16}) (r15=[0-9a-f]{16})\n',
]))

flags_pattern = compile(r'iopl=[0-9a-f]+(?:\s+[a-z]{2}){8}\n')
segments_pattern = compile(r'(?:[a-z]{2}=[0-9a-f]{4}\s+){6}efl=[0-9a-f]{8}\n')
label_pattern = compile(r'[\w\+]+:\n')

instruction_pattern = compile(
  r'[0-9a-f]{8}`[0-9a-f]{8}\s+(?P<ENCODING>[0-9a-f]+)\s+(?P<INSTRUCTION>.+?)\n?'
)

class Instruction(NamedTuple):
  instruction: str
  encoding: str
  registers: Dict[str, str]

def parse_trace(stream: TextIO) -> Iterator[Instruction]:
  """ TODO: some description
  """

  iterator = iter(enumerate(stream, start=1))
  for index, line in iterator:
    # Parse general-purpose registers
    registers: Dict[str, str] = {}

    for pattern in registers_pattern:
      if match := pattern.fullmatch(line):
        # Extract register values from regex match and go to the next line
        registers.update(group.split('=') for group in match.groups())
        index, line = next(iterator)
      else:
        raise RuntimeError(f'Failed to parse line: {index}')

    if flags_pattern.fullmatch(line) is None:
      raise RuntimeError(f'Failed to parse line: {index}')

    if segments_pattern.fullmatch(next(iterator)[1]) is None:
      # TODO: here will be something
      raise RuntimeError(f'Failed to parse line: {index}')

    if label_pattern.fullmatch(next(iterator)[1]) is None:
      raise RuntimeError(f'Failed to parse line: {index}')

    if (match := instruction_pattern.fullmatch(next(iterator)[1])) is None:
      raise RuntimeError(f'Failed to parse line: {index}')

    yield Instruction(match.group('INSTRUCTION'), match.group('ENCODING'), registers)

# Example of usage:
from io import StringIO

trace = StringIO("""rax=0000000000000000 rbx=0000000000000000 rcx=0000000000000000
rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000000
rip=000000000040100a rsp=0000000000000000 rbp=0000000000000000
 r8=0000000000000000  r9=0000000000000000 r10=0000000000000000
r11=0000000000000000 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei pl zr na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
lol+0x1000:
00000000`00401000 48bba47868302035e80c mov rbx,0CE83520306878A4h
rax=0000000000000000 rbx=0000000000000000 rcx=0000000000000000
rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000000
rip=000000000040100a rsp=0000000000000000 rbp=0000000000000000
 r8=0000000000000000  r9=0000000000000000 r10=0000000000000000
r11=0000000000000000 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei pl zr na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
lol+0x1000:
00000000`00401000 48bba47868302035e80c mov rbx,0CE83520306878A4h""")

for each in parse_trace(trace):
  print(each.instruction)
```


texts: Print a random anagram of a given string

texts:
I am given a task to create a function that prints a random anagram of a given string:

def anagram(value):
    '''Prints random anagram of given value'''
    import random
    newWord = ''
    for i in range(len(value)):
        pos = random.randint(0, len(value)-1)
        newWord += value[pos]
        value = value[:pos] + value[pos+1:]
    print newWord

anagram('12345')
anagram('should')

What all edge cases should this program cover?


texts: Determine total number of ways of reaching a destination

texts:
Question:

  One of Scotland Yard’s most wanted criminal (Mister X) is on the run
  and needs to reach a certain destination safely. There are three modes
  of transport available for him - By air, by train or by cab.  With air
  travel, he can go from station i to station i+3. Using a train would
  make him reach station i+2 when starting from i and by taxi he could
  go to the next station (i+1).

  Now, clearly there can be multiple ways of travelling between two
  stations. Thus, you need to help him find out the total number of ways
  of reaching station N from station 0. Since the number of ways can be
  very large output the answer mod 109 +7.

  Input Specification:

  The first line contains the number of test cases, T. This is followed
  by T lines each containing an integer N, the station ID.

  Output Specification:

  Print T lines, each line having the corresponding test case's output.

  Sample Input:

  2 3 4

  Sample Output:

  4 7

  Constraints:

  1 <= T <= 100000

  2 <= N <= 107

My code to be optimized:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution {
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int testCases=Integer.parseInt(br.readLine());
        short ways[]=new short[testCases],i=0;
        int stationId;
        while(testCases!=0)
        {
            stationId = Integer.parseInt(br.readLine());
            ways[i++] = (short)(getWays(stationId)%(10^9 +7));
            testCases--;
        }
        for(int k:ways)
            System.out.println(k);
    }
    static int getWays(int n)
    {
        int sum = 1,i=1;
        while(i<=n)
        {
            sum+=(i-1);
            i++;
        }
        return sum;
    }
}


texts: I'm torn between conditionals and abrupt return functions

texts:
Which one of these two is better?

This one:

middleware.response_redirect = function(){
   return function (req, res, next){
       var redirect = function(){
           if(req.form.redirect) return url.parse(req.form.redirect);
           return {
               protocol: "http",
               hostname: config.domain,
               pathname: "thanks",
           }
       }();
       redirect.query = querystring.stringify({
           "status": "success",
           "message": req.form.message
       });
       return res.redirect(url.format(redirect);
   }
}

Or this one:

middleware.response_redirect = function(){
   return function (req, res, next){
       var redirect;
       if(req.form.redirect){
           redirect = url.parse(req.form.redirect);
       }else{
           redirect = {
               protocol: "http",
               hostname: config.domain,
               pathname: "thanks",
           }
       }
       redirect.query = querystring.stringify({
           "status": "success",
           "message": req.form.message
       });
       return res.redirect(url.format(redirect);
   }
}

The function within function thing bothers me a little. But so does setting redirect in two places.


texts:
The way I am using this method assumes all data is byte-aligned, so I don't really care about the rest of the bits.

This method is written in an extension of BinaryReader which provides more methods when I'm reading binary data from files. The BinaryReader provided does not appear to support reading bits.

Is there a better way I could write this method? Also I'm not sure if there's a more direct way to build a bitmask so I did it the long way.

/* Returns the value of the first n bits. */
public byte ReadBits(byte n)
{
    byte val = base.ReadByte();
    byte sum = 0;
    for (int i = 0; i < n; i++)
        sum += (byte)(val & (1 << i));
    return sum;
}

I am using .NET 3.5


texts: Given a list of numbers and a number, return whether any two numbers from the list add up to

texts:
For example, given [10, 15, 3, 7] and a number k of 17, return True since 10 + 7 is 17.
How can I improve the below solution?
from itertools import combinations

def add_up_to(numbers, k):

 c_k_2 = list(combinations(numbers, 2))

 return any([True for pair in c_k_2 if sum(pair) == k])


texts: Getting the largest element in an array using recursion

texts:
Any suggestions on how to make this code more efficient?

import java.util.Scanner;
public class RecursionLargestInArray
{
public static void main (String[] args)
{
    int max = -999;
    Scanner scan = new Scanner (System.in);
    System.out.print("Enter the size of the array: ");
    int arraySize = scan.nextInt();
    int[] myArray = new int[arraySize];
    System.out.print("Enter the " + arraySize + " values of the array: ");
    for (int i = 0; i < myArray.length; i++)
        myArray[i] = scan.nextInt();
    for (int i = 0; i < myArray.length; i++)
        System.out.println(myArray[i]);
    System.out.println("In the array entered, the larget value is "
                        + getLargest(myArray, max) + ".");
}

public static int getLargest(int[] myArray, int max)
{
    int i = 0, j = 0, tempmax = 0;
    if (myArray.length == 1)
    {
        return myArray[0] > max ? myArray[0] : max;
    }
    else if (max < myArray[i])
    {
        max = myArray[i];
        int[] tempArray = new int[myArray.length-1];
        for (i = 1; i < myArray.length; i++)
        {
            tempArray[j] = myArray[i];
            j++;
        }
        tempmax = getLargest(tempArray, max);
        return tempmax;
    }
    else
    {
        int[] tempArray = new int[myArray.length-1];
        for (i = 1; i < myArray.length; i++)
        {
            tempArray[j] = myArray[i];
            j++;
        }
        tempmax = getLargest(tempArray, max);
        return tempmax;
    }
}
}


texts: Loop Animation on several UIButton's NSLayoutConstraint

texts:
I took the belated plunge to look at Autolayout.  Normally I'd animate based on a UIView's frame (i.e I'd have used the following):

    NSArray *sortedArray = [self.buttonArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:ascendingSort]];

for (int i = 0;i<sortedArray.count;i++) {

    UIButton * theButton = [sortedArray objectAtIndex:i];

    [UIView animateWithDuration:1 delay:i *0.05 usingSpringWithDamping:10 initialSpringVelocity:20 options:UIViewAnimationOptionCurveEaseIn animations:^{
        [theButton setFrame:frameToAnimateTo];
    } completion:nil];
}

Am I right in thinking that I now have to animate based on the Constant property of a buttons constraint?

NSArray *sortedArray = [self.ButtonHorizonalConstraints sortedArrayUsingDescriptors:[NSArray arrayWithObject:ascendingSort]];

for (int i = 0;i<sortedArray.count;i++) {

    NSLayoutConstraint * constraint = [sortedArray objectAtIndex:i];
    UIButton * theButton = constraint.firstItem;

    constraint.constant = toShow?0:-theButton.frame.size.width;
    [self.view setNeedsUpdateConstraints];

    [UIView animateWithDuration:1 delay:i *(toShow?0.1:0.05) usingSpringWithDamping:10 initialSpringVelocity:toShow?20:-20 options:UIViewAnimationOptionCurveEaseIn animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];
}

The end result I get is what I desire, but something doesn't seem right.


texts: Binary to decimal (and back) converter in c++

texts:
I'm mainly looking for error checking / type safety advice.
main.cpp
#include <iostream>
#include <string>
#include <cmath>
#include <numeric>

void binaryToDecimal();
void decimalToBinary();

int main()
{
    std::ios::sync_with_stdio(false);

    bool running = true;
    int ans;

    while (running)
    {
        std::cout << "1. Binary to decimal\n2. Decimal to binary\n3. Quit\n";
        std::cin >> ans;

        std::cout << '\n';

        switch (ans)
        {
        case 1:
            binaryToDecimal();
            break;

        case 2:
            decimalToBinary();
            break;

        case 3:
            running = false;
            break;

        default:
            break;
        }
    }

    return 0;
}

void binaryToDecimal()
{
    int out = 0;
    std::string in;

    std::cout << "Input binary number: ";
    std::cin >> in;

    int i = in.size() - 1;
    if (i > 32)
    {
        std::cerr << "That number is too big!\n\n";
        return;
    }

    for (int j = 0; i > -1; --i, ++j)
    {
        out += static_cast<int>(std::pow(2, i)) * (in[j] - '0');
    }

    std::cout << in << " when converted to decimal is " << out << "\n\n";
}

void decimalToBinary()
{
    std::string out = "";
    std::string in;
    std::cout << "Input decimal number: ";
    std::cin >> in;

    if (in.size() > std::to_string(std::numeric_limits<int>::max()).size())
    {
        std::cerr << "That number is too big!\n\n";
        return;
    }

    int mod = std::stoi(in);

    while (mod > 0)
    {
        out += (mod % 2) + '0';
        mod /= 2;
    }
    std::reverse(out.begin(), out.end());

    std::cout << in << " when converted to binary is " << out << "\n\n";
}


texts: Alternative Way of comparing multiple variable's to multiple variables

texts:
Hi guys Im very very new To Angular/Typescript Im teaching my self section by section by just messing around and figuring things out.
Currently im just doing loop's and outputs so I decided to write a Randomizer for a Moba
Its. 5 Arrays then I select a Random item from each Check that they dont match and output
But I just have to think theres a way to improve on this, Note: I will be expanding to classes and 1 list where i'll pull item's based on a Role: ID but for the moment I need to get arround the if's because its making the values blank when it fails which is fine, but I feel like this can be avoided with an alternative to my way of doing it.
Would appreciate any suggestions or alternative's
Learning Material Welcomed
 constructor() {

  }
  midhero;
  tophero;
  botHero;
  hardShero;
  softShero;
  ngOnInit(): void {
   this.createHeroes();
  }

  createHeroes(): void{
    var topheroz = [
      "Mars", "Void Spirit" ,"Pango", "Brisle", "Axe", "Ogre"
    ];
    var midheroz = [
      "OD", "Void Spirit" ,"SkyWrath", "TA", "Morph"
    ];
    var botheroz = [
      "AM", "WK" , "Ursa" , "Morph" , "Brisle"
    ];
    var hardSupz = [
      "Dazzle", "Winter Wyvern" , "Ogre" , "Crystal Maidan" , "Jakiro"
    ];
    var softSupz = [
      "Dazzle", "Winter Wyvern" , "Ogre" , "Crystal Maidan" , "Jakiro"
    ];
    var miditem = midheroz[Math.floor(Math.random() * midheroz.length)];
    var topitem = topheroz[Math.floor(Math.random() * topheroz.length)];
    var botitem = botheroz[Math.floor(Math.random() * botheroz.length)];
    var harditem = hardSupz[Math.floor(Math.random() * hardSupz.length)];
    var softitem = softSupz[Math.floor(Math.random() * softSupz.length)];

    var midfine;
    var topfine;
    var botfine;
    var hardfine;
    var softfine;

    if(topitem == miditem || topitem == botitem || topitem == harditem || topitem == softitem){
      var topitem = topheroz[Math.floor(Math.random() * topheroz.length)];
    }
    else{
      topfine = true;
    }
    if(miditem == topitem || miditem == botitem || miditem == harditem || miditem == softitem){
      var miditem = midheroz[Math.floor(Math.random() * midheroz.length)];
    }
    else{
      midfine = true;
    }
    if(botitem == topitem || botitem == miditem || botitem == harditem || botitem == softitem ){
      var miditem = botheroz[Math.floor(Math.random() * botheroz.length)];
    }
    else{
      botfine = true;
    }
    if(softitem == topitem || softitem == miditem || softitem == botitem || softitem == harditem){
      var miditem = botheroz[Math.floor(Math.random() * botheroz.length)];
    }
    else{
      softfine = true;
    }
    if(harditem == topitem || harditem == miditem || harditem == botitem || harditem == softitem){
      var miditem = botheroz[Math.floor(Math.random() * botheroz.length)];
    }
    else{
      hardfine = true;
    }
    if(midfine && topfine && botfine && softfine && hardfine){
      this.midhero = miditem;
      this.tophero = topitem;
      this.botHero = botitem;
      this.hardShero = harditem;
      this.softShero = softitem;
    }
    else{
      this.createHeroes();
    }
  }

Mid:{{midhero}}

Top:{{tophero}}

Bot:{{botHero}}

Soft Support:{{softShero}}

Hard Support:{{hardShero}}

```


texts:
I am quite new to Java. I have data structured like this:

tree 503(there is a null character here)040000 tree 0bfec80bc7b7aa0a50e0b373044929cb0aae278b build/
100755 blob e30876c61eb7712ad09b50593a30513d9b173805 build.xml
100755 blob 1574df4a2de5d2884f33a5d3e30ae3daa5affee1 manifest.mf
040000 tree fdab6a12a56a709212f105c9c8e31cd062d01e0a nbproject/
040000 tree 3c977009b6104310d7f3a66200f29bff8cda7576 src/
100755 blob de4bcf5c862c352531819e082204bb51ddabaa9c test_file
100755 blob 26af8cac3b104b4b6514621b1c512e353307a867 unicode.txt

I call each line of this an entry. To parse this data into an array of entries, I wrote this;

class TreeEntry {
    public String perms;
    public String type;
    public String hash;
    public String name;

    @Override
    public String toString() {
        return perms + " " + type + " " + hash + " " + name;
    }
}

private static TreeEntry[] parseTree(String hash) {
    String tree = readObject(hash);

    if (!tree.startsWith("tree")) {
        System.err.println("Given hash doesn't belong to a tree object");
        return null;
    }
    int currentArrayCapacity = 4;
    int currentEntries = 0;
    TreeEntry[] entries = new TreeEntry[currentArrayCapacity];

    // We are interested in data after null character
    int nullCharacterPosition = 0;
    while (tree.charAt(nullCharacterPosition) != '\0') {
        nullCharacterPosition++;
    }
    tree = tree.substring(nullCharacterPosition + 1);

    StringTokenizer st = new StringTokenizer(tree, "\n");
    while (st.hasMoreElements()) {
        TreeEntry e = new TreeEntry();
        StringTokenizer st2 = new StringTokenizer((String)st.nextElement(), " ");
        e.perms = (String) st2.nextElement();
        e.type = (String) st2.nextElement();
        e.hash = (String) st2.nextElement();
        e.name = (String) st2.nextElement();

        // There can be space in name
        while (st2.hasMoreElements()) {
            e.name += " " + (String) st2.nextElement();
        }
        currentEntries++;

        // To increase capacity of the array
        if (currentEntries > currentArrayCapacity) {
            currentArrayCapacity = currentArrayCapacity * 2;
            TreeEntry[] tmp = new TreeEntry[currentArrayCapacity];
            System.arraycopy(entries, 0, tmp, 0, entries.length);
            entries = tmp;
        }

        entries[currentEntries - 1] = e;
    }
    return entries;
}

How does it look as a Java code, and how does it look data structures and algorithms wise?