texts: Morgan and a String HackerRank challenge

texts:
I am solving a HackerRank problem called 'Morgan and a String'.  Given two strings, each consisting of up to 105 uppercase characters, the task is to form the lexicographically smallest string from those letters by taking the first remaining character from either of the strings at each step.  Example, for input strings "ACA" and "BCF", the answer should be "ABCACF":

Jack    Daniel  Result
ACA     BCF
CA      BCF     A
CA      CF      AB
A       CF      ABC
A       CF      ABCA
        F       ABCAC
                ABCACF

Sample input, with one test case:

1
ACEG
BDFH

Output:

ABCDEFGH

I've solved it by writing my own code which works perfectly on smaller test cases. But when they run it against test cases which are approx 6000 characters long I get a runtime error. How can I increase the efficiency?

n=int(input())#number of pairs to input
for mn in range(n):
    a=input()# String1 in the pair
    b=input()#String2 in the pair
    la=[]
    lb=[]

    for i in range(max(len(a),len(b))):#creating lists with all possible elements by slicing off the characters
        la.append(a[i:])
        lb.append(b[i:])

    if len(a)>len(b):#removes empty elements
        lb=[x for x in lb if x!='']
    else:
        la=[x for x in la if x!='']

    while True:#Create empty list for sorting the 0th elements of 'la' nd 'lb'
        temp=[]
        temp.append(la[0])
        temp.append(lb[0])
        temp=sorted(temp)
        print(temp[0][0],end='')#print the 1st character

        if(temp[0] in la):#removing the element after printing the first character
            la.pop(0)
        else:
            lb.pop(0)

        if len(la)==0:#breaks the while loop if a list gets empty
            print(temp[1],end='')
            break
        elif len(lb)==0:
            print(temp[1],end='')
            break


texts:
I have an IEnumerable of a view model that I need to convert to CSV and send back as a file response. I have written it out quite manually and I'm just seeking code review and suggestions on a more elegant solution, or alternatively if this looks acceptable, confirmation of that:

    public ActionResult ExportBasicReads(string nmi, DateTime fromDate, DateTime toDate)
    {
        var reads = _dataService.GetBasicReads(nmi, fromDate, toDate)
                    .Where(r => r.CurrentReadQuality != ReadQuality.Estimate)
                    .OrderBy(r => r.CurrentReadDate)
                    .ThenBy(r => r.DeviceKey)
                    .ThenBy(r => r.ValidationCode);

        StringBuilder csv = new StringBuilder();

        csv.AppendLine("Read Date,Device : Suffix,Read,Quality,Tran Code,Service Order,Previous Read Date,Previous Read,Previous Quality," +
            "Previous Tran Code,Dial Diff,Quantity,UOM,Dial Factor,Direction,Validation,From Date,To Date,Kwh,Avg Daily Load,Profile Name," +
            "Profle Area,Reading Timestamp,Update Date,ChangedBy,ChangeType,ChangeComment");

        reads.ForEach(x => csv.AppendLine(
                string.Format("{0},{1} : {2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22}," +
                "{23},{24},{25},{26},{27}",
                    x.CurrentReadDate,
                    x.DeviceKey,
                    x.Suffix,
                    x.CurrentReadRawValue,
                    x.CurrentReadQualityDesc,
                    x.CurrentReadTransactionCode,
                    x.CurrentServiceOrder,
                    x.PreviousReadDate,
                    x.PreviousReadRawValue,
                    x.PreviousReadQualityDesc,
                    x.PreviousReadTransactionCode,
                    x.DialDifference,
                    x.Quantity,
                    x.UOMDesc,
                    x.Multiplier,
                    x.DirectionDesc,
                    x.ValidationDesc,
                    x.EffectiveFromDateTime,
                    x.EffectiveToDateTime,
                    x.Kwh,
                    x.AverageDailyLoad,
                    x.ProfileName,
                    x.ProfileArea,
                    x.EffectiveFromDateTime,
                    x.UpdateTimestamp,
                    x.ChangedBy,
                    x.ChangeType,
                    x.ChangeComment
                )
            ));

        return File(Encoding.ASCII.GetBytes(csv.ToString()), "text/csv", "BasicReadsExport.csv");
    }


texts:
I'm pretty new to Haskell and was playing around with some number manipulation in different bases when I had to write an integer logarithm function for my task.

I don't mean discrete/modular logs, but simply greatest x s/t b^x <= n

I developed a few versions and can't decide which I like best.  Was hoping to hear what some of you think, or if you have other alternatives to suggest

All have signature: intlog :: (Integral a) => a -> a -> a

intlog :: (Integral a) => a -> a -> a
intlog n b
    | n < b = 0
    | otherwise = succ (intlog (div n b) b)

intlog' :: (Integral a) => a -> a -> a
intlog' n b = maximum [i | i<-[0..n], b^i <= n]

logg = log . fromIntegral
intlog'' :: (Integral a) => a -> a -> a
intlog'' intlog n b = floor $ logg n / logg b

The 'best' one relies on haskell's standard natural log function which I was hoping to avoid (as an exercise) and somewhat messy type conversion.  Of the remaining two, one is probably fastest but seems nearly procedural in nature.  The other feels very functional and 'haskelly' (looking for word analogous to pythonic, meaning in haskells best style) but i cant see it being too efficient unless there is really really good optimization under the hood.

Would love to hear what you guys think.

BTW - i know that for the second one, intlog' i could find a better upperbound than n but im looking for feedback and/or different way to code it.  not incremental improvement like that


texts: Building a simple singly-linked list in C++11

texts:
The implementation below works, but I'm wondering if there's a modern C++ alternative.

For example:

Should I replace the raw new with a braced initializer?
Should I replace the Node* with a shared_ptr?

Let me know if you see any other things I could improve. I know I could also use a class, but I'd like to understand how to do this with struct.

#include <iostream>

struct Node {
  int data;
  Node* next;
};

void insert(Node*& head, int data) {
  Node* new_node = new Node;
  new_node->data = data;
  new_node->next = head;
  head = new_node;
}

void print_list(Node* list) {
  Node* p {list};
  std::cout << "Printing list: " << std::endl;
  if (p) {
    std::cout << p->data;
    p = p->next;
    while(p) {
      std::cout << " -> " << p->data;
      p = p->next;
    }
    std::cout << std::endl;
  }
}

int main(int argc, char* argv[]) {
  Node* my_list {};
  insert(my_list, 10);
  insert(my_list, 20);
  print_list(my_list);
}
// Printing list:
// 20 -> 10


texts: JavaScript infinite scroll with intersection observer

texts:
I built a simple infinite scroll using the intersection observer API, would love some feedback on ways to improve my JavaScript and make it more maintainable and reusable, and feedback according to best JavaScript practices.
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Infinite Scroll</title>

Loading more content...


texts:
I recently started to learn Python for the purpose of making my life as a network engineer easier when performing repetitive tasks.

The script below does parse a huge inventory.xml file I get from a reporting tool to find the ID of ports I want it to and then writes back to the XML file a structure representing a cable between the two network ports. I do convey the name of the ports I want to link in a basic CVS file with 2 columns.

<link>
<portid1>ca1cfd39-cf8f-4d69-a52b-d06357da66b1</portid1>
<portid2>79d8c32a-8891-4bd4-a0a1-1a6e1b333a4b</portid2>
</link>

This is the code I tried to comment to the best of my ability:

#links.csv file shoud be made as follows :
#port1,port2
#port1,port2
#   .
#   .
#   .
from lxml import etree
import csv
import fileinput

#preparing variables
result=[]
trigger=False
tree=etree.parse("inventory.xml")

#parsing the csv file containing the port names to link together
with open('links.csv', 'rb') as csvfile:
    fichier=csv.reader(csvfile)
    for row in fichier:
        name1=row[0] #name of the first port
        name2=row[1]
        portid1=str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name1)) #searches for the port id in the .xml
        portid2=str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name2))
        portid1=portid1[2:-2] #output was surrounded by [""] so i cut the first two and last two
        portid2=portid2[2:-2]
        result.append(("<link>\n<portid1>{}</portid1>\n<portid2>{}</portid2>\n</link>\n").format(portid1, portid2)) #store data

result="".join(result)
#search the file until we find the <links> line, then we print the result
for line in fileinput.input('inventory.xml', inplace=1):
    if line.startswith('    <links>'):
        trigger=True
    else:
        if trigger:
            print result
        trigger=False
    if line.rstrip():
        print line, #wannabe pretty print

The goal of posting here is mainly to make my code as readable to others and as standard as possible, because I know the work I do will probably be read of tweaked by others in the future.


texts: Rendering column headers, some of them with a cellRenderer attribute

texts:
How can I make this code block shorter? I'm repeating myself, because of this prop cellRenderer.

{headers.map((header, i) => {
  return header.index ? (
    <Column
      label={header.label}
      dataKey={header.id}
      disableSort
      width={100}
      flexGrow={1}
      cellRenderer={this._generateCheckbox}
    />
  ) : (
    <Column
      label={header.label}
      dataKey={header.id}
      disableSort
      width={100}
      flexGrow={1}
    />
  );
})}


texts: Pandas data extraction task taking too much memory. How to optimize for memory usage?

texts:
I need to process some data (one of its columns contains a json/dict with params- I need to extract those params to individual columns of their own; catch- some rows have some parameters, others have others.. but all rows put together have 1142 individual parameters.) and so I've written the following script, which works, but the sys, AWS EC2 instance, shut it down after about 64% of its execution.. The output just stopped and terminal shows "Killed". The systems guys at my company told me its a memory issue and it was killed by the os.
Can someone help me make this more memory efficient?

The raw data for this process is roughly 1GB in size.. I load it from a csv into a pandas dataframe of 2.2+ Mn rows and 11 columns.. 1 column has links- prbably around 60 - 80 chars, most of them. Two other columns have either a dict with key/value pairs or a get url with its set of parameters. The other columns have only null or simple short texts. I'm trying to get these parameters from the GET urls and links into their own individual dataframe columns- for most parameters I suspect most rows will have nulls but nonetheless I want this in seperate clean row column structure so I can proceed to analyze this data.

My server has 32Gb of memory.

The code

import pandas as pd, numpy as np, datetime, ast
import sys

qdata = pd.read_csv('q_data_parsed.csv')
print qdata.shape

fl = open('q_unique_params.txt','r')
cols = fl.read()
cols = ast.literal_eval(cols)
print type(cols)
print cols
fl.close()

global key_
def get_params(rw):
    try:
        return rw['params'][key_]
    except KeyError:
        print "KeyError"
        return ""
    except Exception as e:
        print key_, e
        return ""

f = open('q_params_parsed.txt','w')
f.write('\n')
f.close()

for col in cols:
    key_=col
    print key_
    qdata["{}_param".format(key_)]=qdata.apply(get_params)
    f = open('qtr_params_parsed.txt','a')
    f.write('\n' + str(key_))
    f.close()
    print qdata.shape

print qdata.shape
qdata.to_csv('q_data_parsed_to_col_full.csv')


texts: Find out max duplicate number between 1 to N numbers

texts:
How can I make this method better?

int[] _input = new int[] { 5,45,184,594,14,8,5,184,1841,184,594,5,78,594,14,8,18,4,18,14,8,594};

Dictionary<int, int> _inputDictionary = new Dictionary<int, int>();

foreach (int i in _input)
{
    if (_inputDictionary.ContainsKey(i))
    {

        _inputDictionary[i] = ++_inputDictionary[i] ;

    }
    else
    {
        _inputDictionary.Add(i,1);
    }
}

Console.WriteLine();
Console.WriteLine("Maximum number repeated is " + _inputDictionary.OrderByDescending(g => g.Value).First().Key + " and it is repeated " + _inputDictionary.OrderByDescending(g => g.Value).First().Value+" times");


texts: Print all possible combinations of size r, from an array of size n

texts:
This is my working solution for the following problem: given an array of integers of size n, print all possible combinations of size r.

Before I proceed to the solution, I have the following question: combination means that the order does not matter, right? I.e. printing {1, 2} is the same as {2, 1}, so I want to avoid repetitions?

If yes, here is what I do to avoid printing duplicate combinations: presort the given array arr, and if for some i I have that arr[i] == arr[i+1] I just skip this iteration.

Is my approach correct? Is there better solution?

package recursion;

import java.util.Arrays;

public class Combinations {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 4, 5};
        int r = 3;
        Arrays.sort(arr);
        combine(arr, r);
    }

    private static void combine(int[] arr, int r) {
        int[] res = new int[r];
        doCombine(arr, res, 0, 0, r);
    }

    private static void doCombine(int[] arr, int[] res, int currIndex, int level, int r) {
        if(level == r){
            printArray(res);
            return;
        }
        for (int i = currIndex; i < arr.length; i++) {
            res[level] = arr[i];
            doCombine(arr, res, i+1, level+1, r);
            //way to avoid printing duplicates
            if(i < arr.length-1 && arr[i] == arr[i+1]){
                i++;
            }
        }
    }

    private static void printArray(int[] res) {
        for (int i = 0; i < res.length; i++) {
            System.out.print(res[i] + " ");
        }
        System.out.println();
    }
}


texts: Rock Paper Scissors without arrays and if-statements, how to reduce

texts:
As working on a little private programming challenge, I tried "Rock Paper Scissors" without arrays or if-statements. It works as intended, though, I am sure this can be done a little bit more optimized. Especially in the context of Math/Programming.

What I try to achieve:

Create 2 Players, one Computer one Human.
They both can make a Gesture (Rock, Paper or Scissors at Random or to Choose for the Human Player).
The value of each Gesture is calculated into a Score
The calculated Scores are calculated into a Winner of the Duel

The Players are two classes that implement an abstract class.
The Winner and Gesture are Enums with specified values

The random Method just sets a random Gesture value for the player like:

 public void Random() => _gesture = (Gesture)_random.Next(0, 3);

The score for a single Hand is created as if it were points on a circle at 0, 120 and 240 degrees

((double)(_winner + 1) * 3 + (double)_gesture * 2) % 6 * Math.PI / 3;

The opposite hand is done the same, however, it starts at 180 degrees ( 180, 300, 60 degrees)

I try to find the position of both hands on the circle and calculate that into a unique value that results in a winner.

(Winner)(Math.Round(Math.Sin(other.Score() - this.Score())) * -(int)_winner);

This all works nice, however I suppose that the latter both rules could be reduced.

double Score() => ((double)(_winner + 1) * 3 + (double)_gesture * 2) % 6 * Math.PI / 3;
public Winner Duel(Player other) => (Winner)(Math.Round(Math.Sin(other.Score() - this.Score())) * -(int)_winner);

Complete code:

using System;

namespace RockPaperScissors
{
    public enum Winner
    {
        Draw = 0,
        Computer = -1,
        Human = 1
    }

    public enum Gesture
    {
        Rock = 0,
        Paper = 1,
        Scissors = 2,
    }

    public abstract class Player
    {
        private static readonly Random _random = new Random(DateTime.Now.Millisecond);
        private readonly Winner _winner;
        protected Gesture _gesture;

        protected Player(Winner winner)
        {
            _winner = winner;
        }

        public Gesture Gesture => _gesture;
        public void Random() => _gesture = (Gesture)_random.Next(0, 3);
        double Score() => ((double)(_winner + 1) * 3 + (double)_gesture * 2) % 6 * Math.PI / 3;
        public Winner Duel(Player other) => (Winner)(Math.Round(Math.Sin(other.Score() - this.Score())) * -(int)_winner);
    }

    public class Computer : Player
    {
        public Computer() : base(Winner.Computer)  { }
    }

    public class Human : Player
    {
        public Human() : base(Winner.Human) { }
        public void Choose(Gesture gesture) => _gesture = gesture;
    }

    class Program
    {

        static void Main(string[] args)
        {
            Computer computer = new Computer();
            Human human = new Human();

            for(int i = 0; i < 10; i ++)
            {
                computer.Random();
                human.Random();

                Console.WriteLine($"Computer does {computer.Gesture}, Human does {human.Gesture}");
                Console.WriteLine($"Winner = {computer.Duel(human)}");
                Console.WriteLine($"Winner = {human.Duel(computer)}");

                Console.ReadLine();
            }
        }
    }
}


texts: Synchronized block over concurrent collections

texts:
Here, this vector was used at many APIs in the code with sync block on it. And all the places they want to search another collection based on each itr.next().

synchronised(vector)
{
    Iterator itr = vector.iterator();
    while (itr.hasNext)
    {
       //Perform some search on another collection using the value from itr.next() :: THIS IS COSTLY JOB WITH SYNCH BLOCK
       //If that collection doesn't have any entry for itr.next() then perform itr.remove();
     }
}

This is like a vector of conference IDs.  Using each conference ID, it gets a conference from list of conferences, then searches again for a user within that conference having user ID from list of users available in that conference.

As stated above: now the sync block is doing a time-consuming search job on another objects.  And other threads keep waiting for this vector lock.  And the total number of threads in the blocked state increases much while load testing.

I changed the code from Vector to Collections.newSetFromMap(new ConcurrentHashMap<psConference,Boolean>()). I assume that, since this is concurrent collection, no ConcurrentModificationException while performing iteration. Add/remove operations while iteration is allowed here, so I have removed all sync block in my code.

But I come to know from ConcurrentHashMap Java doc:

  iterators are designed to be used by only one thread at a time.

From the above, I think I have moved the sync block problem from my code to the Java API. There is no advantage over this change.

I finally found the best return copy of original vector collection each time any APIs requires that vector of conference IDs. Let the iteration happen on this new vector with that costly searching and other jobs and then finally perform the remove separately.

Vector newVectorObject = mgr.getCopyOfVector();
List toBedeleted = new ArryList();

Iterator itr = newVectorObject .iterator();
    while (itr.hasNext)
    {
       //Perform some search on another collection using itr.next()
       //If that collection doesn't have any entry for itr.next() then perform toBedeleted.add(itr.next())
     }
mgr.removeVector(toBedeleted);

public Vector getCopyOfVector(){
      return new Vector(vector);
}

public Vector removeVector(List toBedeleted){
      return vector.removeAll(toBedeleted);
}

I think in this case, no lock is required on the vector.  No threads will be blocked.


texts: Optimize Yahoo Finance Code for Analysis

texts:
I am trying to analyze a number of companies using financial data I gathered from Yahoo Finance. I am also using the yfinance API to get some more details about the company using functions. Since I am trying to do this for a number of companies Each Iteration needs to be quick. Currently, 1 Company takes about 3 seconds.
Is it because of the API calls or requests? Can I increase the below code efficiency?
import pandas as pd
import numpy as np
from pandas import ExcelWriter
import requests
import timeit
import yfinance as yf

def get_industry(stock):
    tickerdata = yf.Ticker(stock)
    return tickerdata.info['industry']

def get_symbol(symbol):
    url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}&region=1&lang=en".format(symbol)
    result = requests.get(url).json()
    for x in result['ResultSet']['Result']:
        if x['symbol'] == symbol:
            return x['name']
def get_currency(stock):
    tickerdata = yf.Ticker(stock)
    return tickerdata.info['currency']

quarters = ['Q4-2020','Q3-2020','Q2-2020','Q1-2020','Q4-2019','Q3-2019','Q2-2019','Q1-2019','Q4-2018','Q3-2018','Q2-2018','Q1-2018']
start_time = timeit.default_timer()
r = []
for i in stock[:1]:
    try:
        df = pd.read_csv(i+'_quarterly_balance-sheet.csv')
        df = df.drop('ttm',axis=1,errors='ignore')
        df['name'] = df['name'].str.replace('\t','')
        df = df.iloc[:,:13].T
        df.columns = df.iloc[0]
        df = df[1:]
        df.insert(0,'Q',quarters)
        try:
            df.insert(0,'Currency',get_currency(i))
        except:
            df.insert(0,'Currency','Not Found')
        df.insert(0,'Ticker',i)
        df.insert(0,'Company',get_symbol(i))
        try:
            df.insert(0,'Industry',get_industry(i))
        except:
            df.insert(0,'Industry','Unknown')
        df = df.loc[:,df.columns.isin(['Q','Currency','Ticker','Company','Industry','TotalRevenue'])]
        r.append(df)
    except:
        continue
df = pd.concat(r)
# code you want to evaluate
elapsed = timeit.default_timer() - start_time
elapsed

3.041297 Seconds


texts: Providing const- and non-const overloads of a strstr() implementation

texts:
In a question about reimplementing strstr(), I posted an answer.  I pointed out a need for const- and non-const versions of the function, and provided Implementation A below, which received criticism about the ugliness of the const_cast.  Therefore, I've written two more implementations (B and C).

Implementation A: const version that chains to a non-const version

char *strstr(char *input, const char *find) {
    do {
        const char *p, *q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

const char *strstr(const char *input, const char *find) {
    return strstr(const_cast<char *>(input), find);
}

Implementation B: template

template <typename T>
T *strstr(T *input, const T *find) {
    do {
        const T *p, *q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

Implementation C: template with char_traits

template <typename T>
struct char_traits {
    typedef T type;
    typedef const T const_type;
};

template <typename T>
static typename char_traits<T>::type *strstr(
        typename char_traits<T>::type *input,
        typename char_traits<T>::const_type *find) {
    do {
        typename char_traits<T>::const_type *p, *q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

// Explicit instantiation doesn't help with overloading?
// http://stackoverflow.com/a/8061522/1157100
//
// template char *strstr<char>(char *input, const char *find);
// template char *strstr<const char>(char *input, const char *find);

// So it seems that chaining is still necessary?
const char *strstr(const char *input, const char *find) {
    return strstr<const char>(input, find);
}

char *strstr(char *input, const char *find) {
    return strstr<char>(input, find);
}

I suspect that I may have done something stupid with (C), since I'm still chaining the calls.  Is there a way to provide an overloaded strstr() just using template instantiation?

Of the three approaches, which is best, and why?


texts:
Since I am trying to learn many programming languages, I created this simple Android app. What it does basically is taking a sentence phrase from an EditText ed and translate it to speech when you click the start button.
I used onActivityResult to prevent app from crashing when the EditText becomes empty.
I am sensing that this code, while working perfectly, is far from perfect.
import android.support.v7.app.AppCompatActivity;
import java.util.Locale;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements OnInitListener {

private TextToSpeech myTTS;
private EditText ed;
private String phrase;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ed = findViewById(R.id.editText);

    Button startButton = findViewById(R.id.start_button);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Intent checkIntent = new Intent();
            checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
            startActivityForResult(checkIntent, 1);

            phrase = ed.getText().toString();

        }
    });
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {

        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            myTTS = new TextToSpeech(this, this);
            myTTS.setLanguage(Locale.US);
        } else {
            // TTS data not yet loaded, try to install it
            Intent ttsLoadIntent = new Intent();
            ttsLoadIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(ttsLoadIntent);
        }
    }
}

public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        myTTS.speak(phrase, TextToSpeech.QUEUE_FLUSH, null);
    } else if (status == TextToSpeech.ERROR) {
        myTTS.shutdown();
    }
}

}


texts: Raspberry PI switching from Soft Access Point to WIFI client

texts:
I am relatively new to C language and Linux systems I would like some feedback/review. The main function of the code is to read the dhcpcd file looking for the 3 lines and then either adding/removing to the new file. It works and the Pi can switch from AP to client without a reboot, but I feel like it is more of a hack than a proper solution.

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct word {
    int linenumber;
    char *value;
};

struct words {
    int wordcount;
    struct word wordlist[3];
};

int main(void) {
    FILE *fp;
    FILE *temp;
    char filename[] = "/etc/dhcpcd.conf";
    char tempname[] = "/etc/temp.conf";
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    int linecount = 0;
    int index = 0;
    int shouldSkip = 0;
    struct words searchlist;
    struct word wordA;
    struct word wordB;
    struct word wordC;

    wordA.value = "interface wlan0";
    wordA.linenumber = -1;
    wordB.value = "static ip_address=192.168.4.1/24";
    wordA.linenumber = -1;
    wordC.value = "nohook wpa_supplicant";
    wordC.linenumber = -1;

    searchlist.wordcount = 3;
    searchlist.wordlist[0] = wordA;
    searchlist.wordlist[1] = wordB;
    searchlist.wordlist[2] = wordC;

    fp = fopen(filename, "r");
    temp = fopen(tempname, "w");

    if (fp == NULL || temp == NULL) {
        printf("Unable to open file!\n");
        exit(-1);
    }

    while ((read = getline(&line, &len, fp)) != -1) {
        struct word *xword = &searchlist.wordlist[index];
        if(strstr(line, xword->value) != NULL) {
            xword->linenumber = linecount;
            if(index > 0 && index != searchlist.wordcount - 1) {
                if ((linecount - searchlist.wordlist[index - 1].linenumber) != 1) {
                    for (int i = 0; i < searchlist.wordcount; i++) {
                        struct word *wd = &searchlist.wordlist[i];
                        wd->linenumber = -1;
                        index = 0;
                    }
                }
            }
            index = (index == (searchlist.wordcount - 1)) ? index : index + 1;
        }
        linecount++;
    }
    linecount = 0;
    //AP is on so toggle off
    if (fseek(fp, 0L, SEEK_SET) == 0) {
      while ((read = getline(&line, &len, fp)) != -1) {
        for(int i = 0; i < searchlist.wordcount; i++) {
          if(linecount == searchlist.wordlist[i].linenumber && strstr(line, searchlist.wordlist[i].value) != NULL) {
            shouldSkip = 1;
          }
        }

            if(!shouldSkip)
          fputs(line, temp);
        shouldSkip = 0;
            linecount++;
      }
    }

    if (index != searchlist.wordcount - 1) {
       for(int i = 0; i < searchlist.wordcount; i++) {
         fputs(searchlist.wordlist[i].value, temp);
         fputs("\n", temp);
       }
    }

    fclose(fp);
    fclose(temp);
    remove(filename);
    rename(tempname, filename);
    if(line)
     free(line);

    if (index == searchlist.wordcount - 1) {
      printf("Turning WIFI on\n");
    } else {
      printf("Turning Access Point on\n");
    }
    system("sudo service hostapd stop");
    system("sudo service dhcpcd restart");
    system("sudo service hostapd start");

    exit(0);
}


texts: Verifying private class members in Unit Testing

texts:
This code is an academic example. I was trying to write something easy because the domain is not important but the principles and best practices.

In this code, I have a class - Table. It has a private array (of objects Cell), which is used by many public functions in the code but there is no function that will return a particular cell. So the problem I have, is how can I test the Reset function? I can call this function but I can't review its result especially with the Option 2 where I don't have any references to this array.

That got me thinking if the design is correct.. and that lead me here.

My questions are:

Do I violate any SOLID principle?
Is the option 2 better way to go? (although in that case, there's no way to test it

Here's the code:

public class Cell
{
    public int X { get; set; }
    public int Y { get; set; }
    public string Value { get; set; }
}

public class Table
{
    private Cell[,] Cells { get; }
    public Table(Cell[,] cells)
    {
        Cells = cells;
    }

    public void SetCell(int x, int y, string value)
    {
        Cells[x, y].Value = value;
    }

    public void Reset()
    {
        for (int i = 0; i < Cells.GetLength(0); i++)
        {
            for (int j = 0; j < Cells.GetLength(1); j++)
            {
                Cells[i, j].Value = "";
            }
        }
    }

    public bool AreNeighborCellsSet(int x, int y)
    {
        bool areNeighborCellsSet = false;

        // checking...

        return areNeighborCellsSet;
    }
}

Option 2:

public class Table
{
    private Cell[,] Cells { get; }

    public Table(int height, int width, ICellFactory cellFactory)
    {
        Cells = new ICell[height, width];
        for (int i = 0; i < Cells.GetLength(0); i++)
        {
            for (int j = 0; j < Cells.GetLength(1); j++)
            {
                Cells[i, j].Value = cellFactory.Create(i, j);
            }
        }
    }

    // Rest is the same
}


texts: Group list into elements with same value

texts:
This is my Result class:

public class Result
{
    public DateTime Checked { get; set; }
    public bool IsWorking { get; set; }
}

Let's say I have theese results in list:

Date: ..., IsWorking = true;
Date: ..., IsWorking = true;
Date: ..., IsWorking = false;
Date: ..., IsWorking = false;
Date: ..., IsWorking = true;
Date: ..., IsWorking = false;
Date: ..., IsWorking = true;
Date: ..., IsWorking = true;

I want to split them as following:

// group 1
Date: ..., IsWorking = true;
Date: ..., IsWorking = true;

// group 2
Date: ..., IsWorking = false;
Date: ..., IsWorking = false;

// group 3
Date: ..., IsWorking = true;

// group 4
Date: ..., IsWorking = false;

// group 5
Date: ..., IsWorking = true;
Date: ..., IsWorking = true;

I've managed something like this:

public static List<List<T>> SplitByEqualProperty<T>(this IEnumerable<T> inputs, string property)
{
    List<List<T>> temp = new List<List<T>>();
    temp.Add(new List<T>());

    object previousSelector = null;
    for (int i = 0; i < inputs.Count(); i++)
    {
        var current = inputs.ElementAt(i);
        Type t = current.GetType();
        PropertyInfo prop = t.GetProperty(property);
        object currentSelector = prop.GetValue(current);

        if (previousSelector == null)
        {
            temp.LastOrDefault().Add(current);
        }
        else
        {
            if (currentSelector.Equals(previousSelector))
            {
                temp.LastOrDefault().Add(current);
            }
            else
            {
                temp.Add(new List<T>() { current });
            }
        }

        previousSelector = currentSelector;
    }

    return temp;
}

And this is working, but I don't like the code. Expecially part with string property. How can I improve that?


texts:
I'm looking for feedback specifically about what I might add to this to make it more usable or general, especially with regard to scala collection traits to implement.

import scala.collection.{GenTraversableOnce, SortedSet}

object NonEmptySortedSet {
  def apply[A](elems: A*)(implicit ord: scala.Ordering[A]) =
    new NonEmptySortedSet(SortedSet[A](elems: _*))

  def apply[A](s: SortedSet[A]) =
    if (s.nonEmpty) Some(new NonEmptySortedSet(s)) else None

  def apply[A](s: Set[A])(implicit ord: scala.Ordering[A]) =
    if (s.nonEmpty) Some(new NonEmptySortedSet(SortedSet[A]()(ord) ++ s)) else None

  object Implicits {
    implicit class SortedSetOps[A](s: SortedSet[A]) {
      def toNes = apply(s)
    }

    implicit class SetOps[A](s: Set[A]) {
      def sorted(implicit ord: scala.Ordering[A]) = apply(s)
    }
  }
}

class NonEmptySortedSet[A] private(s: SortedSet[A]) extends SortedSet[A] {
  override val head: A = s.head

  override val tail: SortedSet[A] = s.tail

  def contains(elem: A): Boolean = s.contains(elem)

  override val isEmpty = false

  def +(elem: A): NonEmptySortedSet[A] = new NonEmptySortedSet(s + elem)

  def -(elem: A): SortedSet[A] = s - elem

  override def ++(elems: GenTraversableOnce[A]): NonEmptySortedSet[A] = new NonEmptySortedSet(s ++ elems)

  def map[B](f: A => B)(implicit ord: scala.Ordering[B]): NonEmptySortedSet[B] =
    new NonEmptySortedSet(s.map(f))

  def iterator: Iterator[A] = s.iterator

  implicit val ordering: Ordering[A] = s.ordering

  override def rangeImpl(from: Option[A], until: Option[A]): SortedSet[A] = s.rangeImpl(from, until)

  override def keysIteratorFrom(start: A): Iterator[A] = s.keysIteratorFrom(start)
}


texts: Reading a list of file paths and adding them to a map

texts:
I have many thousands of image files spread around various places and would like to copy them into one directory. However, may of the files are duplicates with the same names (often thumbnails or reduced resolution etc).  I want to delete all files that have the same name except for the largest.

The following code reads a list of these file paths (fullpath/name). It splits the filename from the path, determines the size of the file and adds each filename and its size to a list (map).  Where a name is found that is already in the list, the larger of the two is kept in the list and the smaller is 'deleted' (by which I mean emitting the command "rm path/to/file").

I know this is naive C++, because I am a novice (though not at C). Any help making it less naive would (or just better) is appreciated.

#include <iostream>
#include <string>
#include <sys/stat.h>
#include <map>

using std::map;
using std::string;

class filedata {
    std::string path;
    size_t size;
public:
    filedata (void) : path(""), size(0) { }
    filedata (const string& p, size_t s) : path(p), size(s){ }
    filedata (const filedata& f) : path(f.path), size(f.size) { }

    size_t filesize(void) {
        return size;
    }

    string& filepath(void) {
        return path;
    }

    std::ostream& print(std::ostream& os) const {
        os << size << " " << path << "\n";
        return os;
    }
};

std::ostream& operator<<(std::ostream& os, const filedata& f)
{
    return f.print(os);
}

static size_t file_size(const string& s)
{
    struct stat st;
    if (stat(s.c_str(), &st) == 0) {
        return st.st_size;
    }
    return 0;
}

static void delete_file(const string& s)
{
    std::cerr << "rm \"" << s << "\"\n";
}

static bool file_name(const string& path, string& name)
{
    size_t pos = path.rfind('/');
    if (pos == string::npos) {
        return false;
    }
    name = path.substr(pos+1);
    return true;
}

int main(int argc, char **argv)
{
    (void) argc;
    (void) argv;

    string s;
    map<string, filedata> files;

    while (getline(std::cin, s)) {
        string name;
        if (file_name(s, name) == false) {
            break;
        }

        size_t size = file_size(s);
        if (size == 0) {
            delete_file(s);
        }
        else if (files.count(name) > 0) {
            filedata f(files[name]);
            if (f.filesize() <= size) {
                delete_file(f.filepath());
                files[name] = filedata(s, size);
            }
        }
        else {
            files[name]= filedata(s, size);
        }
    }

    for (auto i = files.begin(); i != files.end(); ++i) {
        std::cout << i->first << " "  << i->second;
    }
    return 0;
}


texts:
Worked 2 hours on this. It print Pascal's triangle. Change MAX_LEN to any desired triangle size. What do you think about the quality of the code?

#include "stdafx.h"
#include <stdio.h>
#include <malloc.h>

int main() {
        const unsigned int MAX_LEN = 20;
        unsigned char rowNum, rowWidth, rowOffset, i;
        unsigned int *numPointer, *num;
        unsigned int maxNum = 0;

        for (char len = 1; len <= MAX_LEN; len++)
            maxNum += len;
        num = (unsigned int*)malloc(sizeof(unsigned int)*maxNum);
        if (num == NULL)
            return 1;

        for (rowNum = 0; rowNum < MAX_LEN; rowNum++) {
            rowOffset = 0;
            for (i = 0; i <= rowNum; i++) {
                rowOffset += i;
            }
            num[rowOffset] = 1;
            for (i = 1; i < rowNum; i++) {
                num[rowOffset + i] = num[rowOffset + i - rowNum] + num[rowOffset + i - rowNum - 1];
            }
            num[rowOffset + rowNum] = 1;
        }

    numPointer = num;
    for (rowNum = 0; rowNum < MAX_LEN; rowNum++) {
        for (rowWidth = 0; rowWidth <= rowNum; rowWidth++) {
            printf_s("  %d  ", *numPointer);
            numPointer++;
        }
        printf_s("\n");
    }
        return 0;
}


texts:
Please critique my implementation of a tail-recursive method for generating the Fibonacci sequence:

def fib(n: Int): Option[Int] = {
    @tailrec
    def go(count: Int, prev: Int, acc: Int): Option[Int] = {
        if   (count == n) Some( acc )
        else              go(count+1, acc, acc + prev)
    }
    if      ( n < 0)   None
    else if ( n == 0 ) Some( 0 )
    else if ( n == 1)  Some ( 1 )
    else               go(2, 1, 1)
}


texts:
The question for reference:

  The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?
  answer: 6857

I'm looking for general feedback as to style and particularly usage of the STL.  Efficiency is a concern but a simple link to a better algorithm will suffice.

#include <list>
#include <algorithm>
#include <iostream>

template <class T>
std::list<T> TrialFactorization(T n) {
    std::list<T> base_factors;
    if(n == 1 || n == 2)
        base_factors.push_back(n);
    for(T p = 2; p < n; ++p) {
        while(n % p == 0) {
            n /= p;    // <~~ Shortens outer for-loop.
            base_factors.push_back(p);
        }
    }
    if(n != 1)
        base_factors.push_back(n);
    return base_factors;
}

int main() {
    typedef long long my_type;
    my_type my_int = 600851475143LL;
    std::list<my_type> my_base_factors = TrialFactorization<my_type>(my_int);
    // std::cout << *std::max_element(my_base_factors.begin(), my_base_factors.end());
    // Exploit sorted.
    std::cout << (* --my_base_factors.end());
}


texts: Minesweeper, python Tkinter, Checking close by tiles

texts:
Is there any smart way to compress the following code:

def __total(self, x, y):
    count = 0
    for x_offset in range(-1, 2):
        x_index = x + x_offset
        for y_offset in range(-1, 2):
            y_index = y + y_offset
            if 0 <= x_index < self.Size and 0 <= y_index < self.__Size:
                count += self.__buttons[y_index][x_index].mine
    if not count:
        for x_offset in range(-1, 2):
            x_index = x + x_offset
            for y_offset in range(-1, 2):
                y_index = y + y_offset
                if 0 <= x_index < self.__Size and 0 <= y_index < self.__Size:
                    self.__push(x_index, y_index)
    return count

I have been trying forever with an extreme "coder-blackout" not being able to succeed....


texts:
Here is the interface of my generic dynamic array;

/* dynamic array interface */

#ifndef DA_HEADER
#define DA_HEADER

#include <stdlib.h> /* size_t */

/* creates a new dynamic array, with each element of "size" bytes */
void *danew(size_t unitsize);

/* returns pointer to element after the last element */
void *daend(void *arr);

/* appends new element after last element
   return pointer to array head
*/
void *daappend(void *arr, const void *elem);

/*
    removes the last element and returns a pointer to it or null if empty
*/
void *dapop(void *arr);

/*
  frees the array
*/
void dafree(void *arr);

#endif /* DA_HEADER */

and this is the implementation of my generic dynamic array:

/* dynamic array implementation */

#include <string.h> /* memcpy */
#include <stdlib.h> /* free */
#include "xalloc.h" /* xmalloc, xrealloc */

struct dynamic_array {
        size_t cap;
        size_t len;
        size_t unitsize;
        char data[1];
};

#define DATAOFFSET ((unsigned long)(((struct dynamic_array*)0)->data))
#define DA_STRUCT(DATAPTR) (struct dynamic_array *)((char *)DATAPTR-DATAOFFSET)

void *danew(size_t unitsize)
{
        /* -1 because we already have one byte in struct */
        struct dynamic_array *da = xmalloc(sizeof(struct dynamic_array) +
                                          unitsize - 1);

        da->cap = 1;
        da->len = 0;
        da->unitsize = unitsize;

        return &(da->data);
}

static __inline struct dynamic_array *__dagrow(struct dynamic_array *da,
                                                            size_t size)
{
        while(size > da->cap)
                da->cap = 2*da->cap;

        /* -1 because we already have one byte in sizeof(struct) */
        return xrealloc(da, sizeof(struct dynamic_array) + da->unitsize*da->cap
                                                         - 1);
}

void *daappend(void *arr, const void *elem)
{
        struct dynamic_array *da = DA_STRUCT(arr);
        da = __dagrow(da, da->len + 1);
        memcpy(&da->data[da->unitsize * da->len++], elem, da->unitsize);
        return &da->data;
}

void *dapop(void *arr)
{
        struct dynamic_array *da = DA_STRUCT(arr);
        if(!da->len)
                return NULL;

        return &da->data[da->unitsize * --da->len];
}

void *daend(void *arr)
{
        struct dynamic_array *da = DA_STRUCT(arr);
        return &da->data[da->unitsize * da->len];
}

void dafree(void *arr)
{
        struct dynamic_array *da = DA_STRUCT(arr);
        free(da);
}

And this is the example usage:

#include <stdio.h>

#include "dynamic_array.h"

struct foo {
        int number;
        char *text;
};

int main()
{
        struct foo *myfoos = danew(sizeof(struct foo));
        struct foo *tmp_ptr;
        struct foo tmp;
        int i;
        int numbers[] = {1,2,3,4,5};
        char *texts[] = {"ali", "veli","osman","zekiye","mahmut"};

        for (i=0; i < 5; i++) {
                tmp.number = numbers[i];
                tmp.text   = texts[i];
                myfoos = daappend(myfoos, &tmp);
        }

        /* Random access */
        printf("3rd element is number: %d, text: %s", myfoos[2].number,
                                                      myfoos[2].text);

        printf("Accessing sequentially\n");
        /* Sequential access */
        for (tmp_ptr = myfoos; tmp_ptr != daend(myfoos); tmp_ptr++) {
                printf("current element: number: %d, text: %s\n", tmp_ptr->number,
                                                                tmp_ptr->text);
        }

        printf("Accessing LIFO\n");
        /* LIFO access */
        while((tmp_ptr = dapop(myfoos)))
                printf("current element number: %d, text: %s\n", tmp_ptr->number,
                                                               tmp_ptr->text);

        return 0;
}


texts: Parse through an XDocument efficiently and match values to matching object

texts:
Minimum viable test program:

class Program
{
    private static List<Param> paramList;

    private class Param
    {
        public string xmlName;
        public double scalingFactor;
        public double Value { get; set; }

        public Param( string xmlName, double scalingFactor)
        {
            this.xmlName = xmlName;
            this.scalingFactor = scalingFactor;
        }
    }

    private static void UpdateParams(XDocument xDoc)
    {
        IEnumerable<Param> filteredParamList;
        foreach (XElement xElement in xDoc.Root.Elements())
        {
            filteredParamList = paramList.Where(param => param.xmlName == xElement.Name.LocalName);
            if (filteredParamList != null && filteredParamList.Any())
            {
                filteredParamList.Single().Value = double.Parse(xElement.Value) * filteredParamList.Single().scalingFactor;
            }
        }
    }

    static void Main(string[] args)
    {
        paramList = new List<Param>
        {
            new Param("paramA",1),
            new Param("paramB",.5),
            new Param("paramC",.01)
        };

        /* For testing, this XDocument is hard coded here. */
        UpdateParams(XDocument.Parse("<root><paramA>121</paramA><paramB>100</paramB><paramC>197</paramC></root>"));

        foreach(Param param in paramList)
        {
            Console.WriteLine("Name: {0} Value: {1}", param.xmlName, param.Value);
        }

        Console.Read();
    }
}

Let's focus on UpdateParams. So I have an XDoc that has a root and values. Looks like this:

<root>
 <paramA>121</paramA>
 <paramB>100</paramB>
 <paramC>105</paramC>
  ...
</root>

I have a List of my param objects with an xmlName field which matches my XML key's. The xmlName of each Param object in my list will be unique; I'm manually creating every Param class in the main class's constructor (or in this test program, the main function). For context, the param objects will eventually have UI/WPF bindings from Value to textboxes or other UI elements as needed. For each key in the XML, i want to find the matching param object from my list, and fill in the Value field. If there's something weird in my XDocument that doesn't match my object list, I want to ignore it (and not throw an exception).

Is there a simpler/better way to write the parsing? Seems a little verbose, and i don't like that I have that extra IEnumerable filteredParamList just to work around null checking.


texts: Drawing a Thue-Morse pattern recursively

texts:
This is web exercise 3.1.63. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:

Write a program  that reads in a command line input N and plots the
N-by-N Thue-Morse pattern.  Below are the Thue-Morse patterns for
N = 4, 8, and 16.

Here is my program:
public class ThueMorse
{
    public static void drawThueMorse1(int n, double x, double y, double size)
    {
        if (n == 0) return;
        double x1 = x - size/2, x2 = x + size/2;
        double y1 = y - size/2, y2 = y + size/2;
        StdDraw.setPenColor(StdDraw.BOOK_BLUE);
        StdDraw.filledRectangle(x+(3*size/4),y,size/4,size/2);
        //StdDraw.pause(300);
        StdDraw.filledRectangle(x-(3*size/4),y,size/4,size/2);
        //StdDraw.pause(300);
        StdDraw.filledRectangle(x,y+(3*size/4),size/2,size/4);
        //StdDraw.pause(300);
        StdDraw.filledRectangle(x,y-(3*size/4),size/2,size/4);
        //StdDraw.pause(300);
        StdDraw.setPenColor(StdDraw.WHITE);
        StdDraw.filledSquare(x,y,size/2);
        //StdDraw.pause(300);
        StdDraw.filledSquare(x+(3*size/4),y+(3*size/4),size/4);
        //StdDraw.pause(300);
        StdDraw.filledSquare(x+(3*size/4),y-(3*size/4),size/4);
        //StdDraw.pause(300);
        StdDraw.filledSquare(x-(3*size/4),y-(3*size/4),size/4);
        //StdDraw.pause(300);
        StdDraw.filledSquare(x-(3*size/4),y+(3*size/4),size/4);
        //StdDraw.pause(300);
        drawThueMorse1(n-1, x1, y1, size/2);
        drawThueMorse2(n-1, x1, y2, size/2);
        drawThueMorse2(n-1, x2, y1, size/2);
        drawThueMorse1(n-1, x2, y2, size/2);
    }
    public static void drawThueMorse2(int n, double x, double y, double size)
    {
        if (n == 0) return;
        double x1 = x - size/2, x2 = x + size/2;
        double y1 = y - size/2, y2 = y + size/2;
        StdDraw.setPenColor(StdDraw.WHITE);
        StdDraw.filledRectangle(x+(3*size/4),y,size/4,size/2);
        //StdDraw.pause(300);
        StdDraw.filledRectangle(x-(3*size/4),y,size/4,size/2);
        //StdDraw.pause(300);
        StdDraw.filledRectangle(x,y+(3*size/4),size/2,size/4);
        //StdDraw.pause(300);
        StdDraw.filledRectangle(x,y-(3*size/4),size/2,size/4);
        //StdDraw.pause(300);
        StdDraw.setPenColor(StdDraw.BOOK_BLUE);
        StdDraw.filledSquare(x,y,size/2);
        //StdDraw.pause(300);
        StdDraw.filledSquare(x+(3*size/4),y+(3*size/4),size/4);
        //StdDraw.pause(300);
        StdDraw.filledSquare(x+(3*size/4),y-(3*size/4),size/4);
        //StdDraw.pause(300);
        StdDraw.filledSquare(x-(3*size/4),y-(3*size/4),size/4);
        //StdDraw.pause(300);
        StdDraw.filledSquare(x-(3*size/4),y+(3*size/4),size/4);
        //StdDraw.pause(300);
        drawThueMorse1(n-1, x1, y1, size/2);
        drawThueMorse2(n-1, x1, y2, size/2);
        drawThueMorse2(n-1, x2, y1, size/2);
        drawThueMorse1(n-1, x2, y2, size/2);
    }
    public static int log2(int x)
    {
        return (int) (Math.log(x)/Math.log(2));
    }
    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        n = log2(n)-1;
        drawThueMorse1(n, 0.5, 0.5, 0.5);
    }
}

StdDraw is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:
Input: N = 256
Output:

Is there any way that I can improve my program?
Thanks for your attention.


texts:
This finds duplicate video files using size, duration and partial filename. I have a mass of 17000+ videos and it seems to do an OK job; the amount of duplicates has certainly reduced drastically. Even so there should be many more methods of finding duplicates using these three (or possibly more?) properties.

I don't entirely trust the code here. Some duplicates remain that could've been spotted with better filename comparison. Once it recycled both duplicates of a file! I was baffled. Never found the problem and I'm still using it. Also it's quite slow for a massive collection.

echo.>%temp%\vdat
for /f "delims=" %%v in ('dir d:\videos /b /s /a-d 2^>nul') do (
    for /f "tokens=2 delims=," %%i in ('ffprobe -v quiet -show_entries "format=duration" -of csv "%%v"') do echo %%i/%%v/%%~zv
)>>%temp%\vdat
for /f "tokens=1,2,3* delims=/" %%i in ('sort "%temp%\vdat"') do if exist "%%j" call :strict "%%j" "%%i" "%%k"
for /f "tokens=1,2,3* delims=/" %%i in ('sort "%temp%\vdat"') do if exist "%%j" call :loose "%%j" "%%i" "%%k"
exit /b

:strict
:: if same exact duration+size then remove. blind to filenames. which is nice.
if "%~2" equ "%lastdura%" if "%~3" equ "%lastsize%" recycle -f "%lastfull%" && echo recycled identical duplicate "%lastfile%"
set "lastfile=%%~nx1" & set "lastfull=%%~1" & set "lastdura=%%~2" & set "lastsize=%%~3"
exit /b

:loose
:: if same exact duration+size within the megabyte+same start of filename then remove.
if "%~2" equ "%lastdura%" echo %~3 | findstr /b /c:"%lastsize:~,-6%" >nul && echo "%~nx1" | findstr /i /c:"%lastbite%" >nul && recycle -f "%lastfull%" >nul && echo recycled near-identical "%lastfile%"
set "lastfile=%%~nx1" & set "lastfull=%%~1" & set "lastdura=%%~2" & set "lastsize=%%~3"
set "lastbite=%lastfile:~0,21%"
exit /b

Note that it uses recycle.exe instead of del so for testing you might wanna change that into something else if you don't have it. Also it is set to look for videos in d:\videos and ffprobe.exe is needed for fetching duration.

Even minor feedback very welcomed.


texts: Is decimal, hexadecimal, octadecimal, binary converter efficient?

texts:
I have made a method which takes two parameters: the value to convert and the base. Based upon those two parameters my method is adjusted (with several helper methods) to change the desired decimal number to a number with a different base.

Is this code practical and clean? If not, what should I change to make it better?

public String baseConversion(int base, int value){
    String finalResult = "";
    String tempResult = "";
    int countLength = 0, countFit = 0; // countLength counts the length of the tempResult string in order to know how many '0' to add. countFit counts how many times the tempValue fits into the current parameter 'value'
    int placeValue; // Records the place value. ex 245: '2' is in the hundreds place value
    int tempValue = 0;

    while (value > 0){
        placeValue = 1;
        // calculates the highest power that fits in the value (takes desired base into account)
        while (value > placeValue){
            placeValue*=base;
            countLength++;
        }
        if (value!=placeValue){
            countLength--; // subtract to account for the value in the tempResult that is not '0'
            placeValue/=base; // divide back as the previous while loop went one placeValue higher than needed in order to break out
        }
        //figures out how many times the placeValue can fit into the value
        while (tempValue+placeValue <= value){
            tempValue+=placeValue;
            countFit++;
        }
        if (base==16){
            tempResult += numConverter(countFit);
        }
        if (base==8 || base == 2 || base == 10){
            tempResult += String.valueOf(countFit);
        }
        // adds zeros to the rest of the string
        while (countLength > 0){
            tempResult+="0";
            countLength--;
        }

        // takes the current tempResult and combines with previous. ex combine 10000 with 100 = 10100
        finalResult = combineResults(finalResult, tempResult);

        value -= tempValue;
        countFit=0;
        tempValue=0;
        tempResult="";
    }
    return finalResult;
}

Helper methods:

private String numConverter(int number){
    // only for hexadecimal
    if(number == 10){
        return "A";
    }else if (number == 11){
        return "B";
    }else if (number == 12){
        return "C";
    }else if (number == 13){
        return "D";
    }else if(number == 14){
        return "E";
    }else if (number == 15){
        return "F";
    }else {
        return String.valueOf(number);
    }
}

private String combineResults(String a, String b){
    String result = "";
    int indexA = 0, indexB = 0;
    int aTempLength = a.length(), bTempLength = b.length();
    if (a.length() > b.length()){
        while (aTempLength > bTempLength){
            result+=a.charAt(indexA);
            indexA++;
            aTempLength--;
        }
    }else {
        while (bTempLength > aTempLength){
            result+=b.charAt(indexB);
            indexB++;
            bTempLength--;
        }
    }
    while (aTempLength > 0){
        if (String.valueOf(a.charAt(indexA)).equals("0")){
            result+=b.charAt(indexB);
            indexA++;
            indexB++;
        }else {
            result+=a.charAt(indexA);
            indexA++;
            indexB++;
        }
        aTempLength--;
    }
    return result;
}


texts: Summation Over Lines in a File (Advent of Code 2018 Day 1)

texts:
Preface: I am learning Rust through the Advent of Code

The task is to read lines from a file, parse each as an integer, then provide a summation of all the numbers. My solution looks like this:

use std::fs::File;
use std::io::{self, prelude::*, BufReader};

fn main() -> io::Result<()> {
    let file = File::open("day01.txt")?;
    let reader = BufReader::new(file);

    let mut sum: i32 = 0;

    for line in reader.lines() {
      let value: i32 = line.unwrap().parse().unwrap();
      sum += value
    }

    println!("{}", sum);

    Ok(())
}

I'd like to use the iterator methods map and sum in my solution, but I haven't figured out how to do so with the type checker. Suggestions?


texts:
I have two links in my header:

Register
Login

I am not creating it dynamically. If the user clicks on "login," the login form will be visible, similarly for the register form.

My registration:

<?php
 include 'configdb.php';
 global $connection;

 if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['email']) && !empty($_POST['password']))
 {
   /*
    *Get Details From User Table To Check Whether User Is Registered Already
    *Used Prepare Statement To Avoid SQL Injection
    */
    if($getUserData = mysqli_prepare($connection,"SELECT emailID FROM users WHERE emailID = ?"))
    {
       mysqli_stmt_bind_param($getUserData,"s",$_POST['email']);
       mysqli_stmt_execute($getUserData);
       mysqli_stmt_store_result($getUserData);/*It Is Required To Get Number Of Rows By stmt_num_rows Method */
      //mysqli_stmt_fetch($getUserData);
    }
    /*
     *Check Whether ResultSet Is Empty
     *If Not Empty, Return This JSON Error Message
     */
    if (mysqli_stmt_num_rows($getUserData) > 0)
    {
     mysqli_stmt_close($getUserData);
     die(
          '{
            "status":"1",
            "message":"Email Already Exists"
           }'
        );
    }
    else
    {
      $email = htmlentities($_POST['email'], ENT_QUOTES, "UTF-8");
      $password = password_hash(htmlentities($_POST['password'], ENT_QUOTES, "UTF-8"), PASSWORD_DEFAULT);
      $com_code = md5(uniqid(rand())); /* It Will Be Used Later For Confirmation-link*/

      if($insertData = mysqli_prepare($connection, "INSERT INTO users (emailID, password, com_code) VALUES(?,?,?)"))
       {
         mysqli_stmt_bind_param($insertData, "sss", $email, $password, $com_code);
         mysqli_stmt_execute($insertData);
         //print_r($insertData); - Handle error by checking num_rows in the object insertdata
       }
       else
       {
          print_r("Prepared statement error");
       }

       //$_SESSION['username'] = $_POST['email'];
       die('{
          "status":"0",
          "message":"Registration Successful"
        }');
    }
 }
?>

My Ajax method

/**
*
* @param form
*
* AJAX METHOD FOR REGISTER
*/
function callAjaxRegisterSubmitMethod(form)
{
  $.ajax({
     type: "POST",
     url: "lib/registration_validate.php",
     data: $("#id_registerForm").serialize(),
     dataType: 'json',
     beforeSend: function()
     {
        $(".cls_register_login_error label, .cls_register_login_error .error_link").text('');
     },
     success: function(response,status,jqXHR)
            {
                //Show homepage
                if(response.status == 1)
                {
                    $(".cls_register_login_error .cls_register_login_error_message").text(response.message+". Try");
                    $(".cls_register_login_error .error_link").text("login");
                    $(".cls_register_login_error .error_link").addClass("enable_login");
                    $(".cls_register_login_error .error_link").removeClass("enable_register");
                    $(".cls_registerForm input[type='password']").val('');
                }
                else if(response.status == 0)
                {
                    console.log("Registered Successfully");
                    alert("Registered Successfully");
                    //$(".body_content").load("",function(){});
                }
                else
                {
                    console.log("Common Success Error Page");
                }
            },
    error:function(jqXHR,status,error)
            {
                console.log("Common Error Page");
            },
    complete:function(response)
            {
            }

 });
}

Please let me know of any problems with this approach.

And I am planning to use load method to load my homepage into contnets div because I have fixed header and footer which is common for all the pages.


texts: Pure bash program for auto-filling a template file with ENV variables

texts:
Goal of Program

Consider a template file template.txt with double brace variables, intended to be replaced by values:

hello there {{ MY_VAR1 }}
some other stuff
some other stuff
foo: {{ MY_VAR2 }}
{{ MY_VAR2 }} is the value of MY_VAR2

and assume you have defined and exported those variables:

export MY_VAR1=val1
export MY_VAR2=val2

we want a script fill_template such that fill_template template.txt produces:

hello there val1
some other stuff
some other stuff
foo: val2
val2 is the value of MY_VAR2

and which gives an appropriate error message if any of the required template variables are not defined.

Code for review

Here is working code for fill_template:

#!/bin/bash

if [[ ! -f $1 ]]; then
  >&2 echo "Usage: $0 <filename>"
  exit 1
fi

# Gather all the required template variables

vars=()
while IFS= read -r line; do
    vars+=( "$line" )
done < <( awk 'match($0, /{{ (.*) }}/, a) { print a[1] }' "$1" | sort -u )

# Verify that all template variables are set and exported

missing=()
for var in "${vars[@]}"; do
  if [[ -z ${!var+x} ]]; then
    missing+=( "$var" )
  fi
done

if [[ ${#missing[@]} -gt 0 ]]; then
  >&2 echo "The following required variables have not been set and exported:"
  for var in "${missing[@]}"; do
    >&2 echo "${var}"
  done
  exit 1
fi

# Dynamically construct the sed cmd to do the replacement

sed_cmd=
for var in "${vars[@]}"; do
  sed_cmd+="s/\\{\\{ *${var} *}}/${!var}/g;"
done

sed -E "${sed_cmd}" "$1"

Notes

All comments welcome, from the high-level approach to nitpicks.
Currently we assume there will be only one {{ TEMPLATE_VAR }} per line


texts: parsing log file and get time difference between two timestamp actions in python

texts:
I am quite a beginner in python, so probably the taks I would like to perform is relative simple. I have log files with first column timestamp and second column describes the action, and I need to get the time difference between two actions. The log file called log.txt looks like:

2017-05-11T12:22:12.760 End step: first action

2017-05-11T12:22:13.724 Start step: other action

2017-05-11T12:22:15.069 End step: other action

2017-05-11T12:22:15.933 Start step: first action

I wrote a basic script that parses trough the directories, searches for specific words and calculate the time difference. However, the code is really basic and would like to improve it a little bit, for example by defining a config function that arises error and keeps running when the key words are missing. Any suggestion would be really appreciate. the code I use looks like:

   from datetime import datetime
   from datetime import timedelta
   import re
   import os
   import numpy as np

   inputDir = os.path.dirname(os.path.realpath(__file__))

   for subdir, dirs, files in os.walk(inputDir):
     for file in files:

     filepath = subdir + os.sep + file

     if 'log.txt' in filepath:
     filename=open(os.path.join(filepath))

         with open("OutputTime.csv","a") as outfile:

           for line in filename:
           line = line.rstrip()

           if re.search('Start step: first action', line):
              start_first_step=line[:23]
              start_step=datetime.strptime(start_first_step, "%Y-%m-%dT%H:%M:%S.%f")

           if re.search('End step: first action', line):
              end_first_step=line[:23]
              end_step=datetime.strptime(end_first_step, "%Y-%m-%dT%H:%M:%S.%f")
              minutes=end_step - start_step
              minutes=minutes.total_seconds()/60
              print minutes


texts:
I have a fair few years experience with programming, and am currently working in a software development role, writing internal web applications in C#.

This is the first C++ code I have ever written, so I therefore don't know the conventions, code smells, do's/don't's of the language.

I decided to write an extremely basic Rock, Paper, Scissors implementation using the command line.

Please let me know if I can improve anything?

main.cpp

#include <iostream>
#include <stdlib.h>

using namespace std;

enum Outcome { user, bot, draw };
string outcomeMap[3] = {"You win!", "Bot wins!", "It was a draw!"};
enum Choice { rock, paper, scissors };
string choiceMap[3] = {"rock", "paper", "scissors"};

Choice getUserChoice() {
    cout << "Rock, paper or scissors? " << endl;

    string input;
    getline(cin, input);

    if(input == "rock" || input == "ROCK" || input == "1" || input == "r" || input == "R") {
        return rock;
    } else if(input == "paper" || input == "PAPER" || input == "2" || input == "p" || input == "P") {
        return paper;
    } else if(input == "scissors" || input == "SCISSORS" || input == "3" || input == "s" || input == "S") {
        return scissors;
    } else {
        throw invalid_argument("You must choose rock, paper or scissors.");
    }
}

Choice getBotChoice() {
    auto randomNumber = rand() % 3 + 1;

    switch(randomNumber) {
        case 1:
            return rock;
        case 2:
            return paper;
        case 3:
            return scissors;
        default:
            throw invalid_argument("Random number was generated outside of the given range.");
    }
}

Outcome decideOutcomeOfGame(Choice userChoice, Choice botChoice) {
    if (userChoice == botChoice) {
        return draw;
    } else if (userChoice == rock && botChoice == paper) {
        return bot;
    } else if (userChoice == rock && botChoice == scissors) {
        return user;
    } else if (userChoice == paper && botChoice == rock){
        return user;
    } else if (userChoice == paper && botChoice == scissors){
        return bot;
    } else if (userChoice == scissors && botChoice == rock){
        return bot;
    } else if (userChoice == scissors && botChoice == paper) {
        return user;
    }
}

bool shouldGameExit() {
    cout << "Quit?" << "\r\n";
    string input;
    getline(cin, input);
    if(input == "no" || input == "NO" || input == "n" || input == "N" || input == "0") {
        return false;
    } else {
        return true;
    }
}

void gameLoop() {
    auto quit = false;
    while(!quit) {
        auto userChoice = getUserChoice();
        auto botChoice = getBotChoice();

        cout << "You chose " << choiceMap[userChoice] << "\r\n";
        cout << "The bot chose " << choiceMap[botChoice] << "\r\n";
        cout << outcomeMap[decideOutcomeOfGame(userChoice, botChoice)] << "\r\n";

        quit = shouldGameExit();
    }
}

int main() {
    gameLoop();
    return 0;
}


texts:
I'm an 'old school' programmer (C, C++), and I have step-by-step, algorithmic thinking. I'm writing some code in Angular + Django and I know that this code is ugly but I don't have any idea how to refactor it.

First of all, I have the models:

class Product(models.Model):
    name = models.CharField(max_length=100)
    status = models.CharField(max_length=10, choices=STATUSES.items(), default='new')

class Ad(models.Model):
    image = models.ImageField(upload_to="ad")
    width = models.IntegerField(blank=True)
    height = models.IntegerField(blank=True)
    product = models.ForeignKey(Product, null=True, blank=True)

class AdStatus(models.Model):
    status = models.IntegerField(default=1)
    ad = models.ForeignKey(Ad)

Next I have simple classes for serializing:

class AdSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Ad
        fields = ["url", "id", "image", "width", "height". "product"]
#etc...

And every model has its own factory in Angular:

  .factory('AdStatus',["$resource", function ($resource){
    var Resource = $resource(
        "/api/ad_status/:ad_id/",
        {ad_id: '@id'},
        {
            query: {
                isArray: true,
                transformResponse: function (data) {
                    var items = angular.fromJson(data);
                    return items.results;
                }
            },
            update: {
                method: "PUT",
            }
        },
        {
            stripTrailingSlashes: false
        }
    );
    Resource.prototype.changeStatus = function(status){
        this.status = status;
        this.$update();
    };
    return Resource;
  }])
/etc

This is the main code:

//controller isn't bad

angular.module('controllers.statuses', [])
.controller('StatusCtr', ["$scope", "$stateParams", "StatusSetter",  function($scope, $stateParams, StatusSetter) {
    $scope.click = function(){
        $scope.t = StatusSetter.change($stateParams.id);// this is id of product
    };
}]);

But this makes me a little sick:

.factory('StatusSetter', ["AdStatus", "Product", "Ad", function(AdStatus, Product, Ad){
    var changeStatus = function(id, productStatus, adStatus){
        var product = Product.get({product_id: id});
        product.$promise.then(function(data) {
            product.changeStatus(productStatus);
            var ads = Ad.query();
            var ad_status = AdStatus.query();
            var tmp = [];
            ads.$promise.then(function(data){
                for (var i = 0; i < ads.length; i++) {
                    if (ads[i].product == product.url){
                        tmp.push(ads[i]);
                    }
                }
                ad_status.$promise.then(function(data){
                    for (var i = 0; i < ad_status.length; i++){
                        for (var j = 0; j < tmp.length; j++){
                            if (ad_status[i].ad == tmp[j].url){
                                ad_status[i].changeStatus(adStatus);
                            }
                        }
                    }

                })
            });
        });
        return product;
    };
    return {
        change: function(id){
            return changeStatus(id, "new_status", 30);
        }
    }
  }])

The main philosophy of this code is:

  change AdStatuses which points at Ads (which points at Products)

Any ideas? Maybe I can separate this 'filtering' to $resource or something.


texts:
I have written a CFG (text file) parser for my specific needs. I have found other libraries to be much too large. Even other parsers that bill themselves as "simple" run hundreds of line long.

The code that I need reviewed is the parsing and tokenizing of the input. I feel like it can be simplified. I have added more comments than required just to make it easier for you guys to read.

Here are member variables used in the class:

std::string m_cfgFilename;
std::map<std::string, std::string> m_cfgMap;
std::stringstream m_buffer;

The initialization:

bool CFG::Init(std::string filename)
{
    // Save the filename for the reload
    m_cfgFilename = filename;

    if(filename.empty())
    {
        return false;
    }

    std::ifstream t(filename);

    if (!t.is_open())
        return false;

    m_buffer << t.rdbuf();

    Parse();

    return true;
}

The parsing:

void CFG::Parse()
{
    std::string line;
    std::istringstream s(m_buffer.str());
    std::string commentKey("#");

    while (std::getline(s, line))
    {
        // Ignore empty and comment lines
        if (!line.empty() && line.compare(0, commentKey.length(), commentKey))
        {
            // Split the line
            std::vector<std::string> seglist;
            std::string segment;
            std::istringstream ss(line);

            while (std::getline(ss, segment, '='))
            {
                // Trim the white space
                std::stringstream trimmer;
                trimmer << segment;
                segment.clear();
                trimmer >> segment;

                std::transform(segment.begin(), segment.end(), segment.begin(), ::tolower);

                seglist.push_back(segment);
            }

            // Only
            if (seglist.size() == 2)
            {
                m_cfgMap[seglist[0]] = seglist[1];
            }
        }
    }
}

I am curious if there is a way to cut down on all the different strings and stream conversions.

Here is a sample cfg I would throw at it:

# Test CFG File

# General
name                =   alfred
numPopsicles        =   12
height              =   14.5
loadCharacters      =   true

I should also mention that it does work perfectly. Just worried about redundant code.


texts: Project Euler #8: Maximum product of 13 consecutive digits


texts:
I need to have some thread-safe event handler (like C#'s EventHandler), so I made one. Here is my event handler class and sample code (compiled with VS2013). Is this code OK to be operated in multithreaded environment?

#include <functional>
#include <memory>
#include <atomic>
#include <list>
#include <conio.h>

////////////////////////////////////////////////////////////////////////////
// Event Handler class

template <typename _EventArg>
class EventHandler
{
public:
    EventHandler()
    {
        m_flag.clear();
    }

    EventHandler(const EventHandler& other)
    {
        m_flag.clear();
        m_ptr = other.m_ptr;
    }

    EventHandler& operator= (const EventHandler& other)
    {
        m_flag.clear();
        m_ptr = other.m_ptr;
        return *this;
    }

    virtual ~EventHandler()
    {
        while (m_flag.test_and_set(std::memory_order_acquire));
    }

    template <typename _Type>
    EventHandler(void (_Type::*memFn)(_EventArg), _Type *obj)
    {
        m_flag.clear();
        m_ptr.reset(new std::function<void(_EventArg)>(std::bind(memFn, obj, std::placeholders::_1)));
    }

    void operator() (_EventArg e)
    {
        while (m_flag.test_and_set(std::memory_order_acquire));
        if (m_ptr.get()) { (*m_ptr)(e); }
        m_flag.clear(std::memory_order_release);
    }

    bool operator== (const EventHandler& other)
    {
        while (m_flag.test_and_set(std::memory_order_acquire));
        bool equal = (m_ptr == other.m_ptr);
        m_flag.clear(std::memory_order_release);
        return equal;
    }

private:
    std::atomic_flag m_flag;
    std::shared_ptr<std::function<void(_EventArg)>> m_ptr;
};

template <typename _Type>
class IEvent
{
public:
    IEvent()
    {
        m_flag.clear();
    }

    virtual ~IEvent()
    {
        while (m_flag.test_and_set(std::memory_order_acquire));
    }

    void operator+= (const EventHandler<_Type>& handler)
    {
        while (m_flag.test_and_set(std::memory_order_acquire));
        m_list.push_back(handler);
        m_flag.clear(std::memory_order_release);
    }

    void operator-= (const EventHandler<_Type>& handler)
    {
        while (m_flag.test_and_set(std::memory_order_acquire));
        m_list.remove(handler);
        m_flag.clear(std::memory_order_release);
    }

    void operator() (_Type arg)
    {
        while (m_flag.test_and_set(std::memory_order_acquire));
        for (auto& f : m_list) { f(arg); }
        m_flag.clear(std::memory_order_release);
    }

private:
    std::atomic_flag m_flag;
    std::list<EventHandler<_Type>> m_list;

    // make non-copyable
    IEvent(const IEvent&);
    IEvent& operator= (const IEvent&);
};

////////////////////////////////////////////////////////////////////////////

// Event source class
class CSource {
public:
    void RaiseEvent(int value)
    {
        MyEvent(value); // Raise event
    }

    IEvent<int> MyEvent;
};

// Event receiver class
class CReceiver {
public:
    void MyHandler1(int e)
    {
        printf("CReceiver::MyHandler1 called with value %d\n", e);
    }

    void MyHandler2(int e)
    {
        printf("CReceiver::MyHandler2 called with value %d\n", e);
    }
};

void main()
{
    CSource source;
    CReceiver receiver;

    // define event handler
    EventHandler<int> handler1 = EventHandler<int>(&CReceiver::MyHandler1, &receiver);
    EventHandler<int> handler2 = EventHandler<int>(&CReceiver::MyHandler2, &receiver);

    // add event handler
    source.MyEvent += handler1;
    source.MyEvent += handler2;

    // raise event with value 1234!
    source.RaiseEvent(1234);

    // remove event handler
    source.MyEvent -= handler1;
    source.MyEvent -= handler2;

    _getch();
}


texts: Using model relationships to find number of responses by a user, to posts of a certain topic type

texts:
I have a user, a micropost and a response model.

The user has many microposts and has many responses.

Microposts have tags using the acts as taggable gem.

I need to find the number of responses a user has, to microposts that are tagged with a specific tag. To be clear, for example, how many responses has user 1 given to microposts on "exercise"

There is some basic ruby syntax and relationship logic I am missing. This is what I have in my user

This works as a User model method

   def user_responses_on_topic(interest)
        microposts = Micropost.tagged_with(interest, :on => :tags )
         count = 0
         microposts.each do |micropost|
         responses =  micropost.responses.size
         count = count + responses
      end
    count
   end

But there's got to be a better rails way?


texts: Select non-task workorders, but include the costs of the tasks

texts:
IBM's Maximo Asset Management platform has a WORKORDER table (265 columns).
Details:
The WORKORDER table contains two different kinds of rows:

WO records (istask = 0)
Task records (istask = 1).

The table has columns that store the actual costs (populated for both non-task WOs and for tasks):

actlabcost (actual labor cost)
actmatcost (actual material cost)
actservcost (actual services cost)
acttoolcost (actual tool costs)

View:
I've written a query/view that selects non-task WOs.
For those non-task workorders, the view rolls up the costs from the related tasks and summarizes them in these columns:

actlabcost_incltask
actmatcost_incltask
actservcost_incltask
acttoolcost_incltask
acttotalcost_incltask

I plan to use the view for multiple reports. So I've included all 265 columns in the view via select * (although, Oracle will convert the select * to actual column names when the view is created).
--WO_INCL_TASK_ACT_VW (non-task WOs, includes task actuals)
select
    t.task_actlabcost,
    t.task_actmatcost,
    t.task_actservcost,
    t.task_acttoolcost,
    t.task_acttotalcost,
    nt.actlabcost   + t.task_actlabcost     as actlabcost_incltask,
    nt.actmatcost   + t.task_actmatcost     as actmatcost_incltask,
    nt.actservcost  + t.task_actservcost    as actservcost_incltask,
    nt.acttoolcost  + t.task_acttoolcost    as acttoolcost_incltask,
    t.task_acttotalcost + nt.actlabcost + nt.actmatcost + nt.actservcost + nt.acttoolcost as acttotalcost_incltask,
    nt.*
from
    workorder nt --non-task WOs
left join
    (
    select
        parent,
        sum(actlabcost)  as task_actlabcost,
        sum(actmatcost)  as task_actmatcost,
        sum(actservcost) as task_actservcost,
        sum(acttoolcost) as task_acttoolcost,
        sum(actlabcost) + sum(actmatcost) + sum(actservcost) + sum(acttoolcost) as task_acttotalcost
    from
        workorder
    group by
        parent,
        istask
    having
        istask = 1
    ) t                --tasks
    on nt.wonum = t.parent
where
    nt.istask = 0

Question:
The view works just fine. However, it's fairly lengthy for what it does.
Can it be improved?


texts: Going to the thread pool and back using custom awaiters

texts:
I've figured out a way to switch threads in the middle of a method. The benefit of that seems super obvious to me: that's what everyone wants to do anyway, and splitting up methods, using callbacks, or lambdas, or whatever is just code bureaucracy to make it work.

But if this is so obvious to me, Microsoft guys probably thought of that too, yet didn't implement it as the default way of doing things in TPL. This makes me nervous. These custom awaiters seem to run correctly, but maybe I just haven't hit the gotchas yet.

What could possibly go wrong?

public static class UsageTest
{
    public static async Task DoItTheUsualWay()
    {
        // update UI
        Dictionary<string, string> cantUseVar = null; // have to initialize
        await Task.Run(() =>
        {
            // do heavy lifting
            var cantAccessVarOutsideTheLambda = new object();
            cantUseVar = new Dictionary<string, string>();
        });
        // update UI
    }

    public static async Task UseTheCoolNewAwaiters()
    {
        // update UI
        await GoToThreadPool.Instance;
        // do heavy lifting
        var smoothSailing = new object();
        await GoToMainThread.Instance;
        // update UI
        smoothSailing.ToString();
    }
}

public class GoToThreadPool : INotifyCompletion
{
    public static readonly GoToThreadPool Instance = new GoToThreadPool();

    public bool IsCompleted
    {
        get { return Thread.CurrentThread.IsThreadPoolThread; }
    }

    public GoToThreadPool GetAwaiter()
    {
        return this;
    }

    public void GetResult() { }

    public void OnCompleted(Action continuation)
    {
        ThreadPool.QueueUserWorkItem(o => continuation());
    }
}

public class GoToMainThread : INotifyCompletion
{
    public static readonly GoToMainThread Instance = new GoToMainThread();

    public bool IsCompleted
    {
        get { return Thread.CurrentThread == Application.Current.Dispatcher.Thread; }
    }

    public GoToMainThread GetAwaiter()
    {
        return this;
    }

    public void GetResult() { }

    public void OnCompleted(Action continuation)
    {
        Application.Current.Dispatcher.BeginInvoke(continuation);
    }
}


texts: Improving my solution to the Quiz project from Gophercises in Golang

texts:
I'm new to Go and I completed the first challenge from Gophercises. Any feedback would be highly appreciated.
There are some things that I am unsure of if they are made in an optimal way.
Github repo

Goroutines and channels in the quizList loop

Better error logging for the cli portion

The Shuffle function only works for string, how can I make it work for other types as well?

How should I approach writing test cases?

How should the folder structure be structured?
 package main

 import (
     "encoding/csv"
     "flag"
     "fmt"
     "log"
     "math/rand"
     "os"
     "strings"
     "time"
 )

 type question struct {
     prompt, answer string
 }

 func main() {

     var (
         csvFile = flag.String("csv", "problems.csv", "a csv file in the format of 'question,answer'")
         timeLimit = flag.Int("limit", 3, "the time limit for the quiz in seconds")
         isShuffle = flag.Bool("shuffle", false, "shuffle the quiz order each time it is run")
     )

     flag.Parse()

     if *csvFile == "" {
         fmt.Printf("%s does not exist, please choose another file", *csvFile)
     }

     if *timeLimit == 0 {
         fmt.Printf("Not a valid limit, please choose another limit")
     }

     score := 0

     file, err := os.Open(*csvFile)

     if err != nil {
         log.Fatal(err)
     }

     r := csv.NewReader(file)

     problems, err := r.ReadAll()

     if err != nil {
         log.Fatal(err)
     }

     if *isShuffle {
         Shuffle(problems)
     }

     quizList := populateQuiz(problems)

     timer := time.NewTimer(time.Duration(*timeLimit) * time.Second)

     isTimerDone := true

     ch := make(chan string)

     for _, quiz := range quizList {

         fmt.Printf(quiz.prompt)

         var recipientAnswer string

         go func() {
             fmt.Scanln(&recipientAnswer)
             ch <-recipientAnswer
         }()

         if isTimerDone {
             select {
             case <-ch:
                 if recipientAnswer == quiz.answer {
                     score += 1
                 }
             case <-timer.C:
                 isTimerDone = false
                 fmt.Println()
                 return
             }
         } else {
             break
         }

     }

     fmt.Printf("\nYou scored %d out of %d.\n", score, len(problems))

 }

 func Shuffle(l [][]string) {
     rand.Seed(time.Now().UnixNano())

     rand.Shuffle(len(l), func(i, j int) {
         l[i], l[j] = l[j], l[i]
     })
 }

 func populateQuiz(problems [][]string) []question {

     var questions []question

     for index, record := range problems {

         prompt := fmt.Sprintf("Problem: #%d: %s = ", index + 1, record[0])
         answer := record[1]

         questions = append(questions, question{
             prompt: prompt,
             answer: strings.TrimSpace(answer),
         })

     }

     return questions
 }


texts: I want to verify if argument value passed to a function is an instance of X

texts:
I want to make sure that some arguments are instance of a class.
Here is my code, is there a better approach?

class Object(object):

    @property
    def _attr_classes(self):
        return {'x': str, 'y': int}

    def __init__(self, x=None, y=None):

        self.x = x
        self.y = y

    def __setattr__(self, attr_name, value):

        if attr_name in self._attr_classes:
            correct_instance = self._attr_classes[attr_name]
            if value and isinstance(value, correct_instance) is False:
                raise TypeError('Error for key argument: "{0}", value: "{1}" is not instance of "{2}"'.
                                format(attr_name, value, correct_instance))
        return super(Object, self).__setattr__(attr_name, value)


texts: Find primes that are also primes when its digits are rotated

texts:
The program below is meant to find all of the fare prime numbers under a user specified value. A fare prime being a number that when its digits are rotated, each combination makes a prime number. An example being 113 because 113, 311, and 131 are all prime numbers. My current problem is that the program takes a very long time to process very large numbers so I need a way of making it run quicker. I've tried to explain the code with the comments but if any part doesn't make sense I'll do my best to explain.

#get user input for the number range
n = int(input("number"))
primes = []
#find all the prime numbers up to the specified value and append them to a list
for num in range(2, n+1):
  for i in range(2, num):
      if num % i == 0:
          break
  else:
     primes.append(num)

#find out if the prime number is a fare prime
for i in primes:
  length = len(str(i))
  #if the number has one digit it is automatically a fare prime
  if length == 1:
    print(i)
  #if the number is longer, rotate the digits to see if it is a fare prime
  if length >= 2:
    number = i
    fare_primes = []
    #rotate the number to figure out if all combinations are prime
    for j in range(length):
      #turns # into a list of digits
      digit_list = list(str(number))
      #rearranges
      number = [*digit_list[1::], digit_list[0]]
      part = ""
      #turns it back into an int value
      number = part.join(number)
      int_num = int(number)
      #check if # is prime
      for divider in range(2,int_num):
        if int_num % divider == 0:
          break
      else:
        fare_primes.append(number)
    #if all combinations of the digits are prime the original # is printed
    if len(fare_primes) == length:
      print(fare_primes[-1])


texts: Tarjan's algorithm for Strongly Connected Components without keeping SCC in stack

texts:
I've been looking for an implementation of Tarjan's algorithm in C#/C++ for a strongly-connected components in graphs, and couldn't find any implementation without use of additional Stack - most of them just follow wikipedia pseudocode. I've decided to create one in case if someone is looking for it. Please take a look and codereview. The main point is that mark the SCC as completed once I'm done with descendand processing, and that any cross-edge towards completed SCC will be ignored.

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

public class Graph
{
    private int _verticesCount;
    private List<int>[] _vertexAdjancedVertices; // i-th element contains info about all adjanced vertices of vertex #i

    public Graph(int[,] edges)
    {
        _verticesCount = edges.Cast<int>().Max() + 1;
        _vertexAdjancedVertices = new List<int>[_verticesCount];
        for (int i = 0; i < _verticesCount; ++i)
            _vertexAdjancedVertices[i] = new List<int>();

        for(int i = 0; i < edges.GetLength(0); ++i)
            AddDirectedEdge(edges[i, 0], edges[i, 1]);
    }

    public void AddEdge(int vertex1, int vertex2, bool directed = false)
    {
        AddDirectedEdge(vertex1, vertex2);
        if (!directed)
            AddDirectedEdge(vertex2, vertex1);
    }

    public void AddDirectedEdge(int vertex1, int vertex2)
    {
        _vertexAdjancedVertices[vertex1].Add(vertex2);
    }

    public List<List<int>> GetStronglyConnectedComponents()
    {
        //DFS
        var processed = new bool[_verticesCount];
        var minConnectedValue = new int[_verticesCount];
        var sccCompleted = new bool[_verticesCount];
        int currentTime = 0;

        for(int startingVertex = 0; startingVertex < _verticesCount; ++startingVertex)
            if (!processed[startingVertex])
                GetStronglyConnectedComponents(startingVertex, ref currentTime, processed, minConnectedValue, sccCompleted);

        var res = minConnectedValue.Select((mcv, i) => new {Vertex = i, MinConnectedValue = mcv})
            .GroupBy(vmcv => vmcv.MinConnectedValue)
            .Select(g => g.Select(vmcv => vmcv.Vertex).ToList()).ToList();
        return res;
    }

    private void GetStronglyConnectedComponents(int vertex, ref int currentTime, bool[] processed, int[] minConnectedValue, bool[] sccCompleted)
    {
        processed[vertex] = true;
        ++currentTime;
        //var currentDiscoveryTime = currentTime;
        minConnectedValue[vertex] = currentTime; // initialize to current time
        sccCompleted[vertex] = false;
        foreach (var neighbour in _vertexAdjancedVertices[vertex])
        {
            if (!processed[neighbour])
            {
                GetStronglyConnectedComponents(neighbour, ref currentTime, processed, minConnectedValue, sccCompleted);
                minConnectedValue[vertex] = Math.Min(minConnectedValue[vertex], minConnectedValue[neighbour]); // if we will ever find cycle
            }
            else if (!sccCompleted[minConnectedValue[neighbour]]) // ignore references to completed sccs
            {
                minConnectedValue[vertex] = Math.Min(minConnectedValue[vertex], minConnectedValue[neighbour]); // we've reached processed vertex - use it as a minConnectedValue we could reach to (if smaller)
            }
        }
        if (minConnectedValue[vertex] == vertex) // we are going up to the stack, meaning that we are done with all the descendands
            sccCompleted[vertex] = true; // mark as completed in case if we are the root of current scc
    }
};

Usage:

    var g = new Graph(new[,] {
        {1, 2}, {2, 3}, {2, 4}, {2, 5}, {3, 1}, {4, 1}, {4, 6}, {4, 8}, {5, 6}, {6, 7}, {7, 5}, {8, 6}
    });

    var sccs = g.GetStronglyConnectedComponents();

    Console.WriteLine("g1");
    foreach (var scc in sccs)
        Console.WriteLine(String.Join(",",scc)); // print out


texts:
I am writing some C# that will be running on Linux and will extract values from a kernel generated system file that represents readings from a sensor.

The file contains two lines of text, and I have a method which will extract two values from the file.

The file looks like this:

$ cat /sys/bus/w1/devices/28-00000*/w1_slave
c3 01 4b 46 7f ff 0d 10 2f : crc=2f YES
c3 01 4b 46 7f ff 0d 10 2f t=28187

The method only cares about the crc=2f and YES (can also be NO) fields. The method returns a Nullable<SensorResult> type to indicate the success of parsing the fields:

If parsing could not happen at all because the passed parameter (a string) was invalid then a null will be returned.
If parsing was successful but the CRC was invalid (set to NO) then return a SensorResult and set appropriate fields to indicate that the CRC value is invalid.
If parsing was successful then return a SensorResult and set fields to indicate that the CRC value is valid.
Set the CrcValue field in SensorResult to the value extracted from the string. (If the YES/NO field is set to NO then getting the CRC value is still required.)

Because I'm parsing the string and extracting fields from specific positions, I've made a couple of enums to store these positions instead of relying on magic numbers.

Can the code be improved? If so, how? Are there any best practices I'm not following?

Parser:

    // <summary>
    // Parses the given line from the sensor file and determines if the CRC value is valid.
    // </summary>
    // <param name="sensorFileLine">The sensor file line.</param>
    // <returns>A <see cref="Nullable<SensorCrcValue>" /> that is used to indicate whether parsing the sensor data was successful.</returns>
    public static SensorCrcValue? TryParseCrcValue(string sensorFileLine)
    {
        if (string.IsNullOrWhiteSpace(sensorFileLine))
        {
            return null;
        }

        string[] initialSplitString = sensorFileLine.Split(' ');
        if (initialSplitString.Count() != (int)ParserFieldCount.CrcLineFieldCount)
        {
            return null;
        }

        string crcValueField = initialSplitString[(int)ParserFieldPosition.CrcValue].Split('=')[1];
        string crcValidField = initialSplitString[(int)ParserFieldPosition.CrcIsValid];

        SensorCrcValue sensorCrcValue;

        sensorCrcValue.CrcValue = Convert.ToByte(crcValueField);
        sensorCrcValue.IsCrcValid = false;

        if (crcValidField.Equals("YES"))
        {
            sensorCrcValue.IsCrcValid = true;
        }
        else if (crcValueField.Equals("NO"))
        {
            sensorCrcValue.IsCrcValid = false;
        }

        return sensorCrcValue;
    }

SensorResult struct:

public struct SensorCrcValue
{
    public bool IsCrcValid;
    public byte CrcValue;
}


texts:
Is there any way to improve this kind of code? I have converted this from production code for privacy reasons, so there might be some mistakes.

public class AddNewUserDto
{

    public bool IsAdmin { get; set; }
    public bool IsRead { get; set; }
    public bool IsWrite { get; set; }

    public string[] GetRolesByDto()
    {
        List<string> roles = new List<string>();

        if (this.IsAdmin)
        {
            roles.Add(USER_ROLES.ADMIN);
        }
        if (this.IsRead)
        {
            roles.Add(USER_ROLES.IsRead);
        }
        if (this.IsWrite)
        {
            roles.Add(USER_ROLES.IsWrite);
        }
        if (this.IsEntityUser)
        {
            roles.Add(USER_ROLES.IsEntityUser);
        }

        return roles.ToArray();
    }
}

public static class USER_ROLES
{
    public const string IsAdmin= "Admin";
    public const string IsRead= "Read";
    public const string IsWrite= "Write";
    public const string IsEntityUser = "EntityUser";
}