texts:
What are anagrams?
An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other
def anagram_check(string1,string2):
    list1 = [char1.lower() for char1 in string1 if char1 != " "]
    list2 = [char2.lower() for char2 in string2 if char2 != " "]
    if len(list1) != len(list2):
        return False
    else:
        list1.sort()
        list2.sort()
        return list1 == list2

print(anagram_check('clint eastwood','old west action'))

Question
I have started to learn data structures and algorithms, and my question is: Am I using too many Python tricks to solve this problem or do I need to think of a more basic approach to solve this?


texts:
This is the problem:

  You notice that the device repeats the same frequency change list over
  and over. To calibrate the device, you need to find the first
  frequency it reaches twice.

  For example, using the same list of changes above, the device would
  loop as follows:
    - Current frequency  0, change of +1; resulting frequency  1.
    - Current frequency  1, change of -2; resulting frequency -1.
    - Current frequency -1, change of +3; resulting frequency  2.
    - Current frequency  2, change of +1; resulting frequency  3.
    - (At this point, the device continues from the start of the list.)
    - Current frequency  3, change of +1; resulting frequency  4.
    - Current frequency  4, change of -2; resulting frequency  2, which has already been seen.

  In this example, the first frequency reached twice is 2. Note that
  your device might need to repeat its list of frequency changes many
  times before a duplicate frequency is found,  and that duplicates
  might be found while in the middle of processing the list.

  Here are other examples:
    - +1, -1 first reaches 0 twice.
    - +3, +3, +4, -2, -4 first reaches 10 twice.
    - -6, +3, +8, +5, -6 first reaches 5 twice.
    - +7, +7, -2, -7, -4 first reaches 14 twice.

  What is the first frequency your device reaches twice?

  Here is my implementation in C, why does it not work. It loops through the > whole list but never finds a match.

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

int main(void){

    int sum = 0;
    int q = 0;
    int len = 0;
    char buffer[20];
    int val = 0;
    int list[2000];
    int *plist = list;

    FILE *pFile = NULL;
    pFile = fopen("input.txt", "r");
    if (pFile == NULL){
        printf("file failed to open\n");
        return -1;
    }

    while((fgets(buffer, 20, pFile)) != NULL){  //store all the sums (calculated frequncies induced by changes) in an array called list
        sum += atoi(buffer);
        *plist = sum;
        ++plist;
        ++len;
        }

    fclose(pFile);
    pFile = NULL;
    plist = list;

    printf("length is %d\n\n", len);

    //below will now iterate through the loop and treat it as circular, so up to the element before current element

    for(int i = 0; i < len && val == 0; ++i){
        for(int j = i + 1; j < len + i; ++j){
            if (j >= len)
                q = abs(len - j);
            else
                q = j;
            printf("here is i: %d\there is j: %d\n", list[i], list[q]);
            if(list[i] == list[q]){
                val = list[i];
                break;
            }
        }
    }

    printf("the first frequency is %d\n", val);
    getchar();
    return 0;
}


texts:
I have set up a Dictionary that calls on a class to fill a DataGridView via SQL statements.  The problem is in two (out of 5) instances the value passed HAS to be an integer, but the value comes from a textbox so it is being passed as string.  Before I set these Dictionaries up I was just using a switch statement that can be seen here.  In my switch statement I simply added:

int n;
bool isNumber = int.TryParse(textBox.Text, out n);

if (!isNumber)
{
  MessageBox.Show("Input must be an integer");
  break;
}

to the two cases that needed the value to be an integer type.

Any idea on how I can add error handling to this? Preferably a message box that just says "value needs to be an integer".

    private void findScriptsQueryButton_Click(object sender, EventArgs e)
    {
        SqlConnection connection = new SqlConnection();
        string value = this.valueTextBox.Text;
        connection.ConnectionString = GetSqlConnection[serverComboBox.SelectedItem.ToString()];
        findScriptsDataGrid.DataSource = GetDataSource[findByComboBox.SelectedItem.ToString()](connection, value).Tables[0];
    }
    private static TableAdapters.FindScript dataSource = new TableAdapters.FindScript();
    private static readonly Dictionary<String, Func<SqlConnection, String, DataSet>> GetDataSource = new Dictionary<String, Func<SqlConnection, String, DataSet>>()
    {
        {"Target VDN", dataSource.FillByTargetVDN},
        {"Skill Group", dataSource.FillBySkillGroup},
        {"Translation Route Pool", dataSource.FillByTranslationRoutePool},
        {"Name", dataSource.FillByName},
        {"Label", dataSource.FillByLabel}
    };

    private static readonly Dictionary<String, String> GetSqlConnection = new Dictionary<String, String>()
    {
        {"SERVER01", ConfigurationManager.ConnectionStrings["csS01"].ConnectionString},
        {"SERVER02", ConfigurationManager.ConnectionStrings["csS02"].ConnectionString}
    };


texts:
Edit: The comments have been incorporated to this module in GitHub. The final code has been included at the end of this thread. Thanks very much for the detailed and brilliant suggestions.

Inspired in this color gradient generator, this is a gradient generator in perl6. I wonder if the code could be simplified or improved. It converts the hex colour to base10, calculates the gradient colours, and then converts the colour to base16.
my $initial_color = '#FF0000';
my $final_color   = '#00FF00';
my $gradient      = 10;

my @initial   = ($initial_color ~~ /\#(..)(..)(..)/).list.map: { .Str.parse-base(16) };
my @final     = ($final_color   ~~ /\#(..)(..)(..)/).list.map: { .Str.parse-base(16) };
my @range     = @final Z- @initial;
my @increment = @range.map: { $_ / $gradient };

my @color;
@color.push: @initial;
for (1..$gradient) -> $i {
  @color.push: @(@color[$i-1]) Z+ @increment;
}

for (0..$gradient) -> $i {
  @color[$i] = '#' ~ ( @(@color[$i]).map: { .base(16,0).fmt('%02s') } ).join;
}

my $fh = open '/tmp/delete.html', :w;
for (0..$gradient) -> $i {
  $fh.print: "&nbsp;";
}
$fh.print: '&nbsp';
$fh.close;

run <elinks -dump -dump-color-mode 3 /tmp/borrem.html>;


texts: Caching 1600 integers and searching from treeSet takes a lot of time

texts:
What should I use to cache the result so that it takes less time to search?  It currently takes a large number of minutes to complete 10000 test cases with range 1-99999999999999 (18 times 9 - the worst case), even though the search values have been hard-coded for testing purposes (1600, 1501).

Set<Integer> set = new TreeSet<Integer>();
//some logic to populate 1600 numbers
for (int cases = 0; cases < totalCases; cases++) {
    String[] str = br.readLine().split(" ");
    long startRange = Long.parseLong(str[0]);
    long endRange = Long.parseLong(str[1]);
    int luckyCount = 0;
    for (long num = startRange; num <= endRange; num++) {
        int[] longArray = { 1600, 1501 };
        if (set.contains(longArray[0]) && set.contains(longArray[1])) {
            luckyCount++;
        }

    }
    System.out.println(luckyCount);
}

It actually is a problem to find a lucky number - those numbers whose sum of digits and sum of square of digits are prime. I have implemented the Sieve of Eratosthenes for this.  To optimize it further, I commented my getDigitSum method, and I thought was heavy, so I replaced it with two hard-coded values, but it still takes minutes to solve one test case. Here is a reference to actual problem asked.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.TreeSet;

public class Solution {

    private static int[] getDigitSum(long num) {

        long sum = 0;
        long squareSum = 0;
        for (long tempNum = num; tempNum > 0; tempNum = tempNum / 10) {
            if (tempNum < 0) {
                sum = sum + tempNum;
                squareSum = squareSum + (tempNum * tempNum);
            } else {
                long temp = tempNum % 10;
                sum = sum + temp;
                squareSum = squareSum + (temp * temp);

            }
        }
        int[] twosums = new int[2];
        twosums[0] = Integer.parseInt(sum+"");
        twosums[1] = Integer.parseInt(squareSum+"");
        // System.out.println("sum Of digits: " + twoDoubles[0]);
        // System.out.println("squareSum Of digits: " + twoDoubles[1]);
        return twosums;
    }

    public static Set<Integer> getPrimeSet(int maxValue) {
        boolean[] primeArray = new boolean[maxValue + 1];
        for (int i = 2; i < primeArray.length; i++) {
            primeArray[i] = true;
        }
        Set<Integer> primeSet = new TreeSet<Integer>();
        for (int i = 2; i < maxValue; i++) {
            if (primeArray[i]) {
                primeSet.add(i);
                markMutiplesAsComposite(primeArray, i);
            }
        }

        return primeSet;
    }

    public static void markMutiplesAsComposite(boolean[] primeArray, int value) {
        for (int i = 2; i*value < primeArray.length; i++) {
            primeArray[i * value] = false;

        }
    }

    public static void main(String args[]) throws NumberFormatException,
            IOException {
        // getDigitSum(80001001000l);
        //System.out.println(getPrimeSet(1600));
        Set set = getPrimeSet(1600);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int totalCases = Integer.parseInt(br.readLine());
        for (int cases = 0; cases < totalCases; cases++) {
            String[] str = br.readLine().split(" ");
            long startRange = Long.parseLong(str[0]);
            long endRange = Long.parseLong(str[1]);
            int luckyCount = 0;
            for (long num = startRange; num <= endRange; num++) {
                int[] longArray = getDigitSum(num);
                if(set.contains(longArray[0]) && set.contains(longArray[1])){
                    luckyCount++;
                }
            }
            System.out.println(luckyCount);
        }
    }
}


texts: Return True if num is within 2 of a multiple of 10

texts:
Is there a way to make my code simpler/more pythonic?

  Given a non-negative number "num", return True if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. See also: Introduction to Mod

  near_ten(12) → True

  near_ten(17) → False

  near_ten(19) → True

def near_ten(num):

    a = num % 10
    if  (10 - (10-a)) <= 2 or (10 - a) <= 2:
        return True
    else:
        return False


texts:
I'm trying to make my ASP.net Web API methods asynchronous.  This method is in the Business Logic layer of my N-tier. I'm waiting for the result from my 1st task and use it on the 2nd task, but I think I'm doing it in a wrong way.  Can you please give me advice or feedback regarding my code?

public async Task<DTOUser> CreateUser(DTORegister source)
{
    var result = new DTOUser();

    try
    {
        var user = new DTOUser()
        {
            Active = (int)defaultNumber.One,
            Deleted = (int)defaultNumber.Zero,
            DateCreated = DateTime.Now,
        };

        result = await Task.Run(() =>_RepositoryUser.Add<DTOUser, DTOUser>(user));

        //This part is where I dont feel confident
        var login = new DTOLogin()
        {
            Email = source.Email,
            Password = source.Password,
            OwnerID = result.UserID, //using the result of my 1st task here.
            DateCreated = DateTime.Now

        };
        //use the login object to my 2nd task
        var task2 = await Task.Run(() =>_RepositoryLogIn.Add<DTOLogin, DTOLogin>(login));

        result.IsSuccessful = true;

    }
    catch (Exception ex)
    {
        result.ErrorMsg = "BL Error - " + ex.Message;
        result.IsSuccessful = false;
    }
    return result;
}

Both _RepositoryUser.Add and _RepositoryLogIn.Add are calling the same Generic Repository method from DAL:

public TOutPut Add<TOutPut, TInput>(TInput input)
        {
            var entityObj = MappingConfiguration.MapObjects<TInput, TType>(input); //Calling my automapper method to map my Entity object and DTO Object
            _entity.AddObject(this.GetEntitySetName(typeof(TType).Name), entityObj);
            _entity.SaveChanges();
            return MappingConfiguration.MapObjects<TType, TOutPut>(entityObj);

        }


texts:
I am new to object-oriented concepts. The following is my attempt at creating a basic calculator using class and operator overloading concepts. Please review it for improvements. Also, how do I make it more intuitive? I want to display: +,-,*,/ as options and use switch on them.

#include <iostream>
#include <conio.h>

using namespace std;

class calculator
{
    private:
        float val;

    public:
        calculator(): val(0)
        {}

        void getdata()
        {
            cout << "enter number: ";
            cin >> val;
        }

        void showdata()
        {
            cout << "value: " << val << endl;
        }

        calculator operator + (calculator) const;
        calculator operator - (calculator) const;
        calculator operator * (calculator) const;
        calculator operator / (calculator) const;
};

calculator calculator::operator + (calculator arg2) const
{
    calculator temp;
    temp.val = val + arg2.val;
    return temp;
}

calculator calculator::operator - (calculator arg2) const
{
    calculator temp;
    temp.val = val - arg2.val;
    return temp;
}

calculator calculator::operator * (calculator arg2) const
{
    calculator temp;
    temp.val = val * arg2.val;
    return temp;
}

calculator calculator::operator / (calculator arg2) const
{
    calculator temp;
    temp.val = val / arg2.val;
    return temp;
}

void main()
{
    calculator obj1, obj2, obj3;
    char ch;
    int choice;

    obj1.getdata();
    cout << "1st value entered: ";
    obj1.showdata();
    cout << endl;

    obj2.getdata();
    cout << "2nd value entered: ";
    obj2.showdata();
    cout << endl;

    cout << "Input choice as integer: 1: +,   2: -,   3: *,   4:/     ";
    cin >> choice;
    cout << endl;

    switch (choice)
    {
        case 1:
            obj3 = obj1 + obj2;
            break;
        case 2:
            obj3 = obj1 - obj2;
            break;
        case 3:
            obj3 = obj1 * obj2;
            break;
        case 4:
            obj3 = obj1 / obj2;
            break;
        default:
            cout << "Invalid choice! " << endl;
    }

    cout << "Result ";
    obj3.showdata();
    cout << endl;

}


texts: UNUSED() with teeth in C++11 debug builds

texts:
When you turn up the compiler warnings with -Wunused-variable, one tends to then employ an UNUSED() macro, to say something is intentionally not used at this time.

But that's not very binding, since it's generally just a void cast (or near-equivalent).  Hence if you get the warning, add an UNUSED(), and some time later actually do use the variable...it's misleading to to the reader of the code.

I got the odd idea of making C++11 give this some level of "enforcement", by seeing if it got in a POD lvalue it could trash it.  Obviously won't work for everything (unused constants, etc.)  But I kind of fiddled with it until it had the effect I wanted--while I can't say exactly why every variation I tried didn't work.

You could break it out in various ways to do something special for std::is_pointer<> or other types, or even have some kind of "trashme()" method detection for non-POD values.  But here's the core of the idea:

#if !defined(NDEBUG)

template<
    typename T,
    typename TRR = typename std::remove_reference<T>::type,
    typename std::enable_if<
        !std::is_lvalue_reference<T &&>::value
        || std::is_const<TRR>::value
        || !std::is_pod<TRR>::value
    >::type* = nullptr
>
void UNUSED(T && v) {
    static_cast<void>(v);
}

template<
    typename T,
    typename TRR = typename std::remove_reference<T>::type,
    typename std::enable_if<
        std::is_lvalue_reference<T &&>::value
        && !std::is_const<TRR>::value
        && std::is_pod<TRR>::value
    >::type* = nullptr
>
void UNUSED(T && v) {
    memset(&v, 0xBD, sizeof(TRR)); // or 0xDECAFBAD pattern, etc.
}

#endif

Anything cleaner/simpler to achieve the same effect, or ideas to make it better?


texts: C: Approxmation of Pi with stratified sampling

texts:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>

int m, inbound, g;
double pi;
double uncertainty;
double pi_exactly=3.14159265358979323846;

int main(void)
{
    srand(time(NULL));

    printf("Quantity of random points per square: \n");
    scanf("%d", &m);

    printf("Gridsize: \n");
    scanf("%d", &g);

    for(int i=0; i<g; i++)
    {
        for(int j=0; j<g; ++j)
        {

            if(pow((i+1) / g,2)+pow((j+1) / g,2) < 1){
                inbound+=m;
            }else if(pow(i,2)+pow(j,2)>1){
                break;
            }else{

                for(int k=1; k<=m; k++)
                {
                    double x = ((double)rand() / RAND_MAX + i) * 1 / (double) g;
                    double y = ((double)rand() / RAND_MAX + j) * 1 / (double) g;

                    if(pow(x,2)+pow(y,2)<=1){
                        inbound+=k;
                    }
                }
            }
        }
    }

    pi = (double) inbound / ((double) m *  pow(g,2))*4;
    uncertainty = pi - pi_exactly;

    printf("The approximation of pi is: %lf\n", pi);
    printf("Uncertainty: %e\n", uncertainty);
return 0;

}

I want to approximate \$\pi\$ with the Monte-Carlo-Simulation, so if the random points are inside the unit circle, then there are "inbound". Otherwise not. Pi can be randomize with the divison of the inbound points and the whole amount of random points. Unfortunately the code does not approximate \$\pi\$ very precisely. With \$m=100, g=1000\$ I get \$\pi = 3.991...\$ Is there something to improve? Thanks!


texts:
The javascript method Math.random() returns a (pseudo-)random float between 0 (inclusive) and 1 (exclusive).

In some use cases, I need both limits to be excluded, a random float between 0 (exclusive) and 1 (exclusive).

This is what I currently use to generate said random float:

do {
    var random = Math.random();
} while(random === 0);

But I have a feeling that the (possibly) multiple draws from the random pool somehow mess up the distribution of my random floats.

Is there any downside to using this snippet and if so, how could I generate random floats while excluding both the lower and the upper limits?


texts: Ruby splits text into matrix creating a hash of counts of column 2


texts:
I have a method that can take in a time string in one of the following formats:

HHmmss - e.g. 073055 = 07:30:55
HHmm - e.g. 0730 = 07:30:00
HHmm'H - e.g. 0730H = 07:30:30
a whitespace or empty string - return null

My current code is as follows:

private final static String timeFormatPattern = "HHmmss";
private final static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(timeFormatPattern);

private static LocalTime getLocalTime(String inputTime)
{
    if (inputTime.trim().equals(""))
    {
        return null;
    }
    else
    {
        char secondsIndicator = inputTime.charAt(4);

        if (secondsIndicator == ('H'))
        {
            // H = 30 seconds
            return LocalTime.parse(inputTime.substring(0, 4) + "30", timeFormatter);
        }
        else if (secondsIndicator == (' '))
        {
            // no H = 00 seconds
            return LocalTime.parse(inputTime.substring(0, 4) + "00", timeFormatter);
        }
        else // specific time provided
        {
            return LocalTime.parse(inputTime,timeFormatter);
        }
    }
}

Profiling shows that this method takes 16,439 milliseconds over 7.6 million invocations; and thus is the method with the highest self time in my program's startup.

I have tried splitting this into two methods (one to format the string, and one that simply contains return LocalTime.parse(formattedTime, timeFormatter);), to see whether it was the LocalTime.parse or my string manipulation that was slow. It turns out that 2/3 of the processing is from LocalTime.parse, and the other 1/3 from the string manipulation. This is with half the inputs being of the 4th type (and so not calling the LocalTime.parse at all); and half being of the 2nd or 3rd type.

Am I missing a more efficient way of getting the LocalTime here?


texts: Using PostgreSQL effectively with a banking app

texts:
I'm kind of newbie for these things but I did something and I want to know how I can do this effectively.

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Random;

public class BankingApp
{
    public static void main(String[] args)
    {
        Registeration myreg = new Registeration("vivian","stuff","root@root.org");
        myreg.setDatabaseInfo("JavaAppFirst","root","134679");
        myreg.beRegister();
    }
}

interface SQLConnection
{
    public boolean setConnection() throws Exception; // implement the sql connection
    // public void closeConnection(Connection c,Statement stmt) throws SQLException; // close connection
}

class Registeration implements SQLConnection
{
    private int id;
    private String usr,pwd,email;
    private Connection connect;
    private Statement state;
    private String dbName,dbUsername,dbPassword;

    private void tempRegister() throws Exception
    {
        connect.setAutoCommit(false);
        state = connect.createStatement();
        String sqlQuery = "INSERT INTO users (id,uname,upass,uemail) VALUES ('"+this.id+"','"+this.usr+"','"+this.pwd+"','"+this.email+"');";
        state.executeUpdate(sqlQuery);
        state.close();
        connect.commit();
        connect.close();
    }

    public void beRegister()
    {
        try
            {
                if( setConnection() != true )
                    {
                        System.err.println("[+] Connection Error");
                        return;
                    }
                tempRegister();
                System.out.println("[+] Registeration Successfully");
            }catch(Exception e)
            {
                System.err.println(e.getClass().getName()+": "+e.getMessage());
                System.exit(0);
            }
    }

    public boolean setConnection() throws Exception
    {
        connect = null;
        state = null;
        Class.forName("org.postgresql.Driver");
        connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"+this.dbName,this.dbUsername,this.dbPassword);
        if( connect == null ) return false;
        return true;
    }

    public void setDatabaseInfo(String a,String b,String c)
    {
        this.dbName = a;
        this.dbUsername = b;
        this.dbPassword = c;
    }

    public Registeration()
    {
        //Random random = new Random();
        id = 0; // random.nextInt(2000);
        usr = null;
        pwd = null;
        email = null;
    }
    public Registeration(String usr,String pwd,String email)
    {
        Random random = new Random();
        this.id = random.nextInt(1000);
        this.usr = usr;
        this.pwd = pwd;
        this.email = email;
    }
}

In my view this code is horrible. How can I develop this code?


texts:
I just wrote the code to evaluate a postfix expression and would like it if someone reviews it for me, it works perfectly fine but I'm having trouble adding the character "=" at the end.

 public static int evalPostfix(String exp) {

    int res = 0;

    myStack list = new myStack();
    int n1;     //result of 1st popping
    int n2;     // result of 2nd popping

    for (int i = 0; i < exp.length(); i++) {
        char ch = exp.charAt(i);

            if (ch == ' ') {
            } else {
                if (ch > '0' && ch < '9') {
                    list.push(ch);
                    //          list.printS();
                } else {
                    n1 = Integer.parseInt("" + list.pop());
                    n2 = Integer.parseInt("" + list.pop());

                    switch (ch) {
                        case '+':
                            list.push(n1 + n2);
                            break;
                        case '-':
                            list.push(n1 - n2);
                            break;
                        case '*':
                            list.push(n1 * n2);
                            break;
                        case '/':
                            list.push(n1 / n2);
                            break;

                        default:
                            System.out.println("Invalid operator order!");
                    }
                }
            }
        }

    res = Integer.parseInt("" + list.pop());

    return res;
}


texts:
Could you review my usart driver wrapper please?

It contains the C language Xilinx usart driver, but I write C++ programs and need to C++ usart driver. How it was designed correctly and what I have to chage or add in the one on your view?

I will be thankful for your the strictest appraisal.

Thank you.

//**********************************************************************
// name:           usart.hpp
//
// test:           non.
//
// description:    a usart driver wrapper.
//
// author:         Artyom Shimko
//
// contact:        soikadigital@gmail.com
//
// created:        28.12.19
//
// release:        28.12.19
//
// changes:        non.
//
#ifndef USART_HPP
#define USART_HPP

#include "platform.h"                      // Platform depending settings.
#include "xuartps_hw.h"                    // The Xilinx header file for XUartPs device.

namespace UsartSapce {

    enum usartNumber { usart0 = XPAR_PS7_UART_0_BASEADDR,
                       usart1 = XPAR_PS7_UART_1_BASEADDR};
}

template <typename T>
class Usart : public Platform {

private:
   u32 usartNumber;

public:
   Usart(u32 usartNumber);                 // The set usart number method.

   status transmit(T *pData, u32 dataValue);
   status receive (T *pData, u32 dataValue);

   void reset(void);
};

//**********************************************************************
// The class constructor definition, it sets the usart number.
//**********************************************************************
// id:             A required usart number.
//
template <typename T>
Usart<T>::Usart (u32 usartNumber ) {

   this->usartNumber = usartNumber;
}

//**********************************************************************
// The usart reset method.
//**********************************************************************
// parameters:     non.
//
// return:         non.
//
template <typename T>
void Usart<T>::reset(void) {

   XUartPs_ResetHw(usartNumber);
 }

//**********************************************************************
// The data transmit usart method.
//**********************************************************************
// pData:          The pointer to transmited data.
//
// dataValue:      Value of transmited data.
//
// return:         ok aka 0 or error aka -1. The error occurs then pData
//                 is equal to nullptr or/and dataValue is equal to null.
//
template <typename T>
status Usart<T>::transmit(T *pData, u32 dataValue) {

   u8 *pByteData = nullptr;

   if(parameterCheck_(pData,dataValue) != StatusSpace::ok) {

       return StatusSpace::error;
   }

   pByteData = reinterpret_cast<u8*>(pData);

   for(u32 byteCounter = 0; byteCounter < dataValue; ++byteCounter) {

       XUartPs_SendByte(usartNumber, *(pByteData + byteCounter));
   }

    return StatusSpace::ok;
}

//**********************************************************************
// The data receive usart method.
//**********************************************************************
// pData:          The pointer to an array for received data.
//
// dataValue:      Value of received data.
//
// return:         ok aka 0 or error aka -1. The error occurs then pData
//                 is equal to nullptr or/and dataValue is equal to null.
//
template <typename T>
status Usart<T>::receive(T *pData, u32 dataValue) {

   u8 *pByteData = nullptr;

   if(parameterCheck_(pData,dataValue) != StatusSpace::ok) {

       return StatusSpace::error;
   }

   pByteData = reinterpret_cast<u8*>(pData);

   for(u32 byteCounter = 0; byteCounter < dataValue; ++byteCounter) {

       *(pByteData + byteCounter) = XUartPs_RecvByte(usartNumber);
   }

   return StatusSpace::ok;
}

#endif


texts: CMakeList to compile and link an executable using Boost

texts:
I'm beginner with CMake and C++ compilation but it's seems that unlike Java I need to be very explicit with my CMakeList.txt in order to link src with correct header and libraries in my project.

Here is my CMakeList.txt

cmake_minimum_required(VERSION 3.4)
project(AwesomeScheduler)

include_directories(header)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/../bin)

find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})

set(SOCKET_SOUCE_FILES
        src/socket.cpp
        header/socket.h)

set(DISPTACHER_SOURCE_FILES
        src/dispatcher.cpp
        header/dispatcher.h
        header/util.h)

set(ENDUSER_SOURCE_FILES
        src/end-user.cpp
        header/end-user.h
        header/util.h)

set(TASKPROPERTIES_SOURCE_FILES
        src/task_properties.cpp
        header/task_properties.h)

add_executable(Dispatcher ${SOCKET_SOUCE_FILES} ${DISPTACHER_SOURCE_FILES})

add_executable(EndUser ${SOCKET_SOUCE_FILES} ${ENDUSER_SOURCE_FILES} ${TASKPROPERTIES_SOURCE_FILES})
target_link_libraries(EndUser ${Boost_LIBRARIES})

The compilation works well and I get my two executables but I wonder if there is a way less verbose to get the same result?


texts:
Started picking up D recently. I wrote an application to create journal entries (text files) based on user input.

//this program will write to files. It should be able to read them.
//implement a command interface?
import std.stdio;
import std.string;
import std.datetime;
import fileio = std.file;
import std.conv;

enum Commands {exit = "EXIT", create = "CREATE"};

string menuText(){
    return "\nType a command:\n\t- create\n\t- exit\n>";
}

void checkJournalEntriesFolder(){
    string path = "journalEntries/";
    if(fileio.exists(path) == 0){
        writeln("Creating a journalEntries folder for you.");
        fileio.mkdir(path);
    }
}

string getFileName(){
    return "entry_" ~ std.conv.to!string(stdTimeToUnixTime(Clock.currStdTime())) ~ ".txt";
}

int main(string[] argv)
{
    writeln("\nWelcome to myJournal.");
    checkJournalEntriesFolder();
    string mode = "COMMAND";
    char[] buf;
    Commands command;
    while (mode != "EXIT"){
        while (mode == "COMMAND"){
            string journalContent;
            write(menuText);
            stdin.readln(buf);
            switch(toUpper(buf[0..$-1])) // cut off the /n at the end of the buffer.
            {
                case command.exit:
                    {
                        mode = "EXIT";
                        writeln("Oh, I'll exit.");
                        break;
                    }
                case command.create:
                    {
                        writeln("create journal entry selected");
                        mode = "CREATE";
                        //create file
                        writeln("You are now typing in your journal.");
                        writeln("To exit this file, type #EOF");
                        writeln("----------------------------");
                        break;
                    }
                default:
                    {
                        writeln("\nunrecognized command");
                    }
            }

            while (mode == "CREATE") {
                stdin.readln(buf);
                if(buf[0..$-1] == "#EOF"){
                    writeln("----------------------------");
                    mode = "COMMAND";
                    checkJournalEntriesFolder(); // double check, in case the user deleted it.
                    string filename = "journalEntries/" ~ getFileName;
                    fileio.write(filename, journalContent[0..$-1]); //Dont include the blank line.
                    writeln("File Saved.");
                } else {
                    journalContent ~= buf;
                }
            }
        }
    }
    return 0;
}

Possible Improvements:

Maybe be able to move throughout the document once it is open (right now if you hit enter, you cannot move to the previous line).
Make command / insert mode more like vi.
Edit existing files.

I am very new to D, so I expect this code will be tore up. I've done some C++, but it has been a while.


texts: Repeatedly open and close a PDF document to perform various operations

texts:
I am trying to implement the Execute Around pattern described in Kent Beck's Smalltalk Best Practice Patterns. An example in Java could be found here.

Basically, I am repeatedly opening and closing a pdf document while performing various operations, something like,

public void Parse()
{
    // Open the document
    PdfLoadedDocument loadedDocument = new PdfLoadedDocument("plan.pdf");

    List<string> annotations = Build(loadedDocument);
    // work with annotations.

    // Close the document
    loadedDocument.Save();
    loadedDocument.Close();
}

I would like to move the opening and closing the document in a centralized place, as I have tens of similar methods. All these methods open the document, perform an action, and close the document, and it's easy to forget to close the document.

Here is what I tried:

public void BuildAnnotations()
{
    List<string> annotations = null;

    ExecuteAction("plan.pdf", (PdfLoadedDocument loadedDocument) =>
    {
        annotations = Build(loadedDocument);
        // work with annotations
    });
}

private void ExecuteAction(string path, Action<PdfLoadedDocument> perform)
{
    PdfLoadedDocument loadedDocument = new PdfLoadedDocument(path);

    try
    {
        perform(loadedDocument);
    }
    catch(Exception e)
    {
        Console.WriteLine($"An error occured. {e}");
    }

    loadedDocument.Save();
    loadedDocument.Close();
}

My question is, is passing a lambda to an Action delegate a good idea? I am not that familiar with delegates, Actions, and lambdas (other than using them in linq queries). Are there any other better alternatives?


texts:
This is a very simple sorting logic that I have written and it's working also.
But Is there anything wrong in the traversing of the array?
Or the code is not optimized?
The code is simply declaring an array of size N.
And then sorting is performed by traversing.

import java.util.Scanner;
import java.io.*;
class BubbleSort
{
    public static void main(String args[])throws IOException
    {
        int size,temp=0;
        System.out.println("Enter the size of the array");
        Scanner sc=new Scanner(System.in);
        size=sc.nextInt();
        int arr[]=new int[size];
        System.out.println("Enter the elements in the array");
        for(int i=0;i<size;i++)
        {
            arr[i]=sc.nextInt();
        }
        for(int i=0;i<size;i++)     //Here is the sorting logic
        {
            for(int j=i+1;j<size;j++)
            {
                if(arr[i]>arr[j])
                {
                    temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;

                }
            }
        }
        for(int i=0;i<size;i++)
        {
            System.out.print(arr[i]);
        }
     }
    }


texts:
I have taken a widget/ plugin that I wrote yesterday and just now it has been re-written in an object oriented format. It is certainly more code to write it the OO way, so please let me know also how to analyze the performance of each example of the same widget below:

Please keep in mind that I use data-attr selectors because of their descriptive nature and the fact that it separates style and functionality by not binding its functionality to .class selectors. Yes, I understand ID's are faster. I use a ~ before the = when querying these selectors because I like to leave the data-function or data -widget attr's open to the addition of new functionality (E.G. $('data-function="accordion jsondataset").. in this format javascript will not pick up the jsondataset attribute unless a ~ is added in the selector scripting resembling $('data-function~="jsondataset").

Here is the finished code:

var tabs = function(){
  var tabsWidgetEnvoked = $('[data-widget~="tabs"]');
  if (tabsWidgetEnvoked){ // if data-attr present in DOM
    var settings = [
      { // widget settings as an object
        tabs : $('[data-function="tabs"]'),
        content: $('[data-function="content"]'),
        tabShowing : '1',
        animated: true,
      }
    ]
    $.each(settings, function(){
      // event handling
      tabs = this.tabs;
      content = this.content;
      show = this.tabShowing;
      animated = this.animated;
    });
     if (animated === true){
        $('body').addClass('animated');
      }
      tabs.children().each(function(i){
        i = i + 1;
        $(this).attr('data-nav-order', i);
      });
      content.children().each(function(i){
        i = i+ 1;
        $(this).attr('data-content-order', i);
      });
      tabs.children(':nth-child('+show+')').addClass('active')
      content.children(':nth-child('+show+')').addClass('active')
      tabs.children().click(function(e){
        e.preventDefault();
        tabs.children().removeClass('active')
        $(this).addClass('active');
        requestedView = $(this).attr('data-nav-order');
        content.children().removeClass('active');
        content.children('[data-content-order="'+requestedView+'"]').addClass('active')
      });
  }
}
tabs();

I did add animation and a default view to the object oriented one as well but aside from this, the functionality is the same.

Here is the code for the standard spaghetti code version.

Here is the one I rewrote with an OO approach.


texts: excel-vba function to filter an array and return an array

texts:
I have a function to filter a 2-d array.
It works. But I am not sure if the following mechanism is a sensible concept.
The idea is:

loop over the input array which is received as input_arr(y,x)

store the values in temp_arr(x,y), since in order to resize the y-dimension it
needs to be last dimension, so I have to transpose the values as I
store them

once the loop is done, transpose temp_arr(x,y) which
becomes the return value
Public Function filter_arr(input_arr As Variant, col_index As Long, filter_value As Variant) As Variant

 'the input_arr might be indexed starting from 0 or 1
 Dim n1 As Long, n2 As Long
 n1 = LBound(input_arr, 2)
 n2 = UBound(input_arr, 2)

 Dim temp_arr() As Variant
 Dim y As Long, x As Long, count As Long
 count = 0

 If (LBound(input_arr, 1) = 0) Then
  For y = LBound(input_arr, 1) To UBound(input_arr, 1)
   If (input_arr(y, col_index) = filter_value) Then

    ReDim Preserve temp_arr(n1 To n2, 0 To count)
    For x = n1 To n2
     temp_arr(x, count) = input_arr(y, x)
    Next x
    count = count + 1

  End If
 Next y

 Else

 'if LBound(input_arr, 1) = 1
 For y = LBound(input_arr, 1) To UBound(input_arr, 1)

  If (input_arr(y, col_index) = filter_value) Then

   count = count + 1
   ReDim Preserve temp_arr(n1 To n2, 1 To count)
   For x = n1 To n2
    temp_arr(x, count) = input_arr(y, x)
   Next x

   End If
  Next y

 End If

 filter_arr = Application.Transpose(temp_arr)

End Function

Edit: adding some context
Imagine that I have a ws in an .xlam file that contains product information which I've added as an add-in.
I have a function like =getProductData() which returns an array containing that data
So excel has a SORT function which works great with this kind of thing. I can do =SORT(getProductData(), 2, 1) to return my product data sorted by the 2nd column
But excel's FILTER function needs me to specify the data itself as its second parameter, not just its index, like in SORT
I can use INDEX to do something like =SORT(FILTER(getProductData(),INDEX(getProductData(),,3)="red",""),2,1) to filter my product data by the 3rd column if the value = red, then sort by the 2nd column of the resulting array
But I was hoping to do something like
=SORT(filter_arr(getProductData(),3,"red"),2,1) to do the same
Naturally I'm still just playing around to determine what I can pull off - maybe using INDEX is the way to go and I'm trying to reinvent the wheel


texts: Would like advice on SOLID principles in my Unity C# script

texts:
I am working to understand SOLID, and want to know how my Unity C# script could be better formatted to align with the principles. I will provide the script and then an explanation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    public CharacterController controller;

    public float speed = 12f;
    public float gravity = -9.81f;
    Vector3 velocity;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    private bool isGrounded;

    void Update()
    {
        GroundCheck();
        Movement();
        Gravity();
    }

    private void GroundCheck()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }
    }

    private void Movement()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);
    }

    private void Gravity()
    {
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
    }
}

This is a script that handles movement of a character, but additionally performs ground checks and gravity of the player. I have seen interfaces used when adding new functionality, and new classes as well in the same script, but I thought for the purposes of this code it would be best to separate each functionality into a function and have them all call from update of the PlayerMovement class. I decided to use one class because I was wary of running three classes with three Update methods in this one script for performance reasons. Is there a better way I should approach the organization of this script from a SOLID point of view? My thought process was that if I wanted to extend these functionalities I would be able to do so in each function, and if I needed new functionality I could create more functions.


texts: Adding a list of brokers to a local SQLite database

texts:
I have this piece of Java (Android) code that adds a list of brokers to a local SQLite database as one single SQL instruction.

public void Add(List<Broker> brokers)
{
    if(brokers == null || brokers.size() == 0)
      return;

    String sql = "INSERT INTO " + TABLE_NAME + " SELECT " + brokers.get(0).getId() + " AS '" + COLUMN_BROKERID + "', "+ brokers.get(0).getOfficeId() + " AS '" + COLUMN_OFFICEID +  "', '"+ brokers.get(0).getName() + "' AS '" + COLUMN_NAME +  "', "+ brokers.get(0).getSuccessRate() + " AS '" + COLUMN_SUCCESSRATE +  "'";

    for(int i=1; i<brokers.size(); i++)
    {
        sql = sql + " UNION SELECT " + brokers.get(i).getId() + ", " + brokers.get(i).getOfficeId() + ", '" + brokers.get(i).getName() + "', " + brokers.get(i).getSuccessRate();
    }

    databaseManager.ExecuteNonQuery(sql);
 }

But what slows this down a lot is the change in the string 'sql'. The last line, which is a call to ExecuteNonQuery(), takes a millisecond, but the above takes a lot. How can I speed this up?

databaseManager is an interface that is implemented by a class of SQLiteOpenHelper and simply executes an SQL statement (but don't take this into account; it doesn't take any time as much as the rest of the code).


texts: Function declarations using macros to support multiple platforms

texts:
I wrote a C++ plugin that retrieves screen pixel. It works on Windows and Android. I noticed that dllexport is only required on Windows but not on Android and causes error on other platform other than Windows. I fixed that by using #if macro to make it use dllexport only on Windows.

Here is the fixed header code:

#ifndef ANDROIDSCREENSHOT_NATIVE_LIB_H
#define ANDROIDSCREENSHOT_NATIVE_LIB_H

#define DLLExport __declspec(dllexport)

extern "C"
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY)
DLLExport void initScreenPointPixel(void* buffer, int x, int y, int width, int height);
DLLExport void updateScreenPointPixelBufferPointer(void* buffer);
DLLExport void updateScreenPointPixelCoordinate(int x, int y);
DLLExport void updateScreenPointPixelSize(int width, int height);
int GetScreenPixels(void* buffer, int x, int y, int width, int height);

#else
void initScreenPointPixel(void *buffer, int x, int y, int width, int height);
void updateScreenPointPixelBufferPointer(void *buffer);
void updateScreenPointPixelCoordinate(int x, int y);
void updateScreenPointPixelSize(int width, int height);
int GetScreenPixels(void *buffer, int x, int y, int width, int height);
#endif
}
#endif //ANDROIDSCREENSHOT_NATIVE_LIB_H

It works and fixes the problem but I don't like the fact that I have to declare each of these functions twice. Once in the #if and another in the #else statement. I have many functions if not thousands and if I go this route, the code would be unnecessary long. The simple goal is to remove dllexport on non Windows platform without declaring the function twice like I am currently doing.

Is there a better way to do this with macro without having to declare each function again? Any solution without macros is also good as long as I don't have to declare each function multiple times.


texts: Generating all unique permutations of a string

texts:
Here is a plan for generating the permutations of S: For each item x
  in S, recursively generate the sequence of permutations of S - x, and
  adjoin x to the front of each one. This yields, for each x in S, the
  sequence of permutations of S that begin with x. Combining these
  sequences for all x gives all the permutations of S:

The plan to generate all the
permutations of a set S

I would like to use the process described above to generate the permutations of a string.

I used LinkedHashSet because I'd like to get rid of all the duplicate permutations if there are the same characters in the string. Besides, the add operation is constant.
I will have to remove a character from a string lots of times. But Syntactically, since this is recursive, I will only do the removing of characters once in the code definition (str.substring(0, i)+str.substring(i+1)). Do I still need to put this code to another method? The only advantage I can think of is clarity but this code seems too small for that to matter much.
I don't know much about how to analyze my code, but since we need to find the ways to order the set while removing every character and putting this character in front of each one, I think the running time is n factorial+n. For example, if we have a string with 3 characters, we would find the ways of ordering 3 subsets (the subsets where the first, second and third characters are removed). Each of those subsets results in two ways, that's why we get 3*2 ways after putting the removed character in the front of each. The +n part is the substring operations which is O(n). Is this all correct?
Regardless of if my code runs at n factorial or not, I think this is absolutely, horribly, extremely slow. How can I make it faster?
I found that java string's immutability is helpful to what my code is doing. But I still feel that I am wasting a lot of string objects because most of them will be trashed anyway when I append a character to it. How can I improve management of my strings??

Please review my code.

public class Permutation {

    public Set<String> permute(String str) {
        Set<String> res = new LinkedHashSet<>();
        if (str.isEmpty()) {
            res.add(str);
        } else {
            for (int i = 0; i < str.length(); i++) {
                for (String s : permute(str.substring(0, i)+str.substring(i+1))) {
                    res.add(str.charAt(i)+s);
                }
            }
        }
        return res;
    }

}


texts: Helper class for accessing blobs and mmap memory

texts:
This class was inspired from Microsoft's array_view.

It intended to use with mmap-ed memory for easily check bounds and so on.

I probably will need to throw exceptions, but this is not my usual way of working.

Any comments are welcome.

#include <cstring>

class BlobRef{
public:
    BlobRef(const void *mem, size_t const size) noexcept :
                mem_( (const char *) mem),
                size_(size){}

    // for test purposes
    BlobRef(const char *s) noexcept :
                BlobRef(s, strlen(s) + 1){}

    template<size_t N>
    BlobRef(const char(&mem)[N]) noexcept:
                BlobRef(mem, N){}

public:
    bool empty() const noexcept{
        return mem_ == nullptr || size_ == 0;
    }

    size_t size() const noexcept{
        return size_;
    }

    const void *data_() const noexcept{
        return mem_;
    }

public:
    const void *safeAccessMemory(size_t const pos, size_t const size) const noexcept{
        if (pos + size <= size_)
            return & mem_[pos];
        else
            return nullptr;
    }

    template <class T>
    const T *as(size_t const pos = 0, size_t const elements = 1) const noexcept{
        return (const T *) safeAccessMemory(pos, elements * sizeof(T));
    }

private:
    const char  *mem_ = nullptr;
    size_t      size_ = 0;
};

#include <cstdint>
#include <assert.h>
#include <endian.h>

int test_blobref(){
    constexpr size_t SIZE = 256;
    char mem[SIZE];

    for(int i = 0; i < SIZE; ++i)
        mem[i] = (char) i;

    BlobRef br{ mem };

    assert(*br.as<uint16_t>(0x00) == htobe16(0x0001)    );
    assert(*br.as<uint16_t>(0x0E) == htobe16(0x0E0F)    );
    assert(*br.as<uint32_t>(0x10) == htobe32(0x10111213)    );

    {
        const char *s = br.as<char>('a');
        assert(strncmp(s, "abcde", 5) == 0);
    }

    {
        struct TestStruct{
            uint16_t    i;
            char        c;
            char        s[4];
        }__attribute__((__packed__));

        const TestStruct *st = br.as<TestStruct>(0x50);
        assert(st->i == htobe16(0x5051)     );
        assert(st->c == 0x52            );

        const char *s1 = st->s;
        const char s2[] = { 0x53, 0x54, 0x55, 0x56, 0x57 };
        assert(strncmp(s1, s2, sizeof s2) == 0);
    }

    {
        size_t const pos = SIZE / sizeof(uint64_t);

        const uint64_t *u64 = br.as<uint64_t>(0, pos);
        assert(u64 != nullptr   );
        assert(u64[      0] == htobe64(0x0001020304050607)  );
        assert(u64[pos - 1] == htobe64(0xf8f9fafbFCFDFEFF)  );
    }

    {
        size_t const pos = SIZE / sizeof(uint64_t) ;

        const uint64_t *u64 = br.as<uint64_t>(0, pos + 1 );
        assert(u64 == nullptr   );
    }

    return 0;
}

int main(){
    test_blobref();
}


texts: Javascript Object Placement / String Parsing Method

texts:
This JS function is intended to retrieve or place a value into an object with the nested keys as a string.

For example

var obj = {a: {b: [4]}};
parse_obj_key(obj, "a.b.0") should equal 4.
parse_obj_key(obj, "a.c", 2) should add another element to "a" named "c" with value 2.

The method works, but I'd like to clean it up if possible (or a more polished implementation which is publicly available).  I'd also love to know of any edge-case failures which can be found.

function parse_obj_key(obj, loc, val){
    var _o = obj;
    while (true){
        var pos = loc.indexOf('.');

        if (!_o || typeof _o != 'object'){
            $.log("Invalid obj path: " + loc + "\n" + JSON.stringify(obj));
            return null;
        }

        if (pos === -1){
            if (val){
                _o[loc] = val;
                return obj;
            } else {
                if (!isNaN(parseInt(loc)))
                    loc = parseInt(loc);

                return _o[loc];
            }
        }
        var part = loc.substring(0, pos);
        var loc = loc.substring(pos + 1);

        if (!isNaN(parseInt(part)))
            part = parseInt(part);

        if (!(part in _o)){
            if (val)
                _o[part] = new object;
            else
                return null;
        }
        _o = _o[part];
    }
}


texts:
LeetCode 125 requires receiving a string and checking if it is a valid palindrome. I have done this and am confident with an int and a single word, but this question requires the use a of a sentence with non-alphanumeric characters. The function must ignore non-alphanumeric characters and whitespaces.
public bool isPalindrome(string s) {

    s = System.Text.RegularExpressions.Regex.Replace(s, @"\W|_", "");

    if (s == null || s == "" || s.Length == 1 || s == " ")
    {
        return true;
    }

    for (int i = 0, j = s.Length - 1; i <= s.Length / 2  && j >= s.Length /2;i--,j++)
    {
        if (Char.ToLower(s[i]) == Char.ToLower(s[j]))
        {
            continue;
        }
        return false;
    }

    return true;
}

It is my first time ever using Regex, maybe that gives my function a performance hit? Would it be better if I could implement this without Regex?
Example inputs are: "a man, a plan, a canal: Panama" -- returns true, "race a car" -- returns false, "a man, a plan, a canal -- Panama" -- returns true. The stats on this are: Runtime 136 ms, faster than 11.75% of c# submissions.


texts:
EDIT: Alternate answer on overflow: https://stackoverflow.com/questions/38487692/how-can-i-interpret-the-time-with-less-code/38492144#38492144

But I really want to keep Jonah's answer here too. Just let me know if I really have to close either this one or stackoverflow's question.

I really don't like sticking many ifs together. I think it looks like a child stacking. But if anyone knows how to do the same thing I'm doing with this code but with less lines, it would be great.

var time = data[i].data4;
                    var summary = '' + time + ' minutes since last login.
';
                    if(time >= 60) {
                        var hour= tiempo / 60;
                        summary = '' + Math.floor(hora) + ' hours since last login.
';
                        if(hour>= 24) {
                            var day = hour/ 24;
                            summary= '' + Math.floor(day) + ' days since last login.
';
                            if(dia >= 7) {
                                var week= day / 7;
                                summary = '' + Math.floor(week) + ' weeks since last login.
';
                                if(week >= 4) {
                                    var month = week / 4;
                                    summary = '' + Math.floor(mes) + ' months since last login.
';
                                }
                            }
                        }
                        s += summary;
                    } else {
                        s += summary;
                    }

For some context: data[i].data4 is from a column that is an operation of DATEDIFF(mi, someDate, getdate()).

As you can see, the returned results would be in minutes and from then on I start checking how many hours, days, and so on from that and I would even love to add between each line an (if it's greater than 1) so I can change the wording to singular instead of plural but I think that's too many lines just for a decision of whether to simply write 'minute' instead of 'minutes'.


texts:
I need to read databases which contain 44-50 tables, with around 5 million entries in total (~ 100k entries per table).

The data consists of positional tracking data in sports (players, refs and the ball) and match-events (shots, plays, tackles, ...):

Match-events are negligible regarding performance.

Table: PlayerXYZ or Ball
-------------------------------------------
|id (int Primary Key)| x | y | z | timekey |
--------------------------------------------

Right now, it takes 86 seconds to read the database and assign the content to a DataTable dictionary. That's a "speed" of 57000 entries per second.

private async void ProcessLoadMatch()
{
    var window = Application.Current.MainWindow as MetroWindow;
    var controller = await window.ShowProgressAsync("Please wait...", "Process message", false, new MetroDialogSettings());

    controller.SetTitle("Loading Match-Data...");
    await Task.Run(() => HandleLoadMatch(controller));
    await controller.CloseAsync();

}

static bool HandleLoadMatch(ProgressDialogController ProgCtrl)
{
    string DataBasePath = @"W:\data\sqlite";
    string DataBaseName = "db";
    string dbpath = @DataBasePath + @"\" + @DataBaseName + ".sqlite";

    SQLiteConnection con = new SQLiteConnection("Data Source=" + dbpath + ";Version=3;");
    con.Open();

    DataTable tables = con.GetSchema("Tables");
    double currentTable = 0;
    double Percentage = 0;
    foreach (DataRow row in tables.Rows)
    {
        currentTable++;
        Percentage = (100 / tables.Rows.Count) * currentTable;
        string tablename = (string)row[2];
        ProgCtrl.SetMessage("Loading Data\nCurrent Table ("+currentTable+" of "+tables.Rows.Count+"): " + tablename + " ...");
        ProgCtrl.SetProgress(Percentage / 100);

        string CmdString = "SELECT * FROM " + tablename;
        SQLiteCommand cmd = new SQLiteCommand(CmdString, con);
        SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);
        DataTable MatchDt = new DataTable();
        sda.Fill(MatchDt);

        CurrentDataSet.CurrentMatch.Data.Add(tablename, MatchDt);
    }
    con.Close();
    return true;

}

CurrentDataSet.CurrentMatch.Data:

class CurrentMatch
{
    public static Dictionary<string, DataTable> Data = new Dictionary<string, DataTable>();
}

My system:

Mac Mini (late 2012)
i5-3210m clone
16GB RAM
256GB SSD

Is there any performance potential left in my code? I load different databases on a regular basis, so any significant performance gains would be appreciated.


texts: Creating dynamic threads for a SMS text API

texts:
First, I want to say that this code works, but I want to make sure this is the right way of doing it. I am writing this for a SMS text API that loops through each phone number. I sometimes gets hung up on 1 number or just takes time. It roughly takes 6-8 sec per number. So I thought I would write something that would make it multitreaded. I wrote this to allow the number of threads at one time to go up depending on the workload.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestTreading
{
    class Program
    {
        static public BlockingCollection<int> Queue = new BlockingCollection<int>();
        static public BlockingCollection<int> Finished = new BlockingCollection<int>();
        static public BlockingCollection<Thread> Threads = new BlockingCollection<Thread>();
        static public int QUCount = 0;
        static public int THCount = 0;
        static public int FNCount = 0;

        static void Main(string[] args)
        {
            BuildList();
            DateTime StartTime = DateTime.Now;

            QUCount = Queue.Count;
            THCount = Threads.Count;
            FNCount = Finished.Count;

            while (QUCount > 0)
            {
                THCount = Threads.Count;
                if (THCount < 20)
                {
                    Thread th1 = new Thread(LoopMethod);
                    Threads.Add(th1);
                    THCount = Threads.Count;
                    th1.Start();
                }
            }

            DateTime EndTime = DateTime.Now;
            Console.WriteLine(StartTime);
            Console.WriteLine(EndTime);
            Console.WriteLine(EndTime - StartTime);
            Console.ReadLine();
        }

        static void LoopMethod()
        {
            int QueueItem = Queue.Take();
            QUCount = Queue.Count;
            for (long i = 0; i < 100000; i++)
            {
                long result = i / 2;
            }
            string Display = string.Format("ID:{0} Left In Queue:{1}  Finished:{2}  Threads Running:{3}", QueueItem, QUCount, FNCount, THCount);
            Console.WriteLine(Display);
            Thread.Sleep(10);

            Finished.Add(QueueItem);
            FNCount = Finished.Count;
            Thread CurTh = Thread.CurrentThread;
            Threads.TryTake(out CurTh);
        }

        static void BuildList()
        {
            for (long i = 0; i < 5000; i++)
            {
                Random RandomNum = new Random();
                int Num = RandomNum.Next(1, 2);
                Queue.Add(Num);
            }
        }

    }
}


texts:
Security is a huge complicated subject. What I'm looking for here is three things:

The password generating algorithm isn't reversible, meaning that when someone looks at the source code of this application, that won't help them to break passwords made by it other than the fact that they can see the possibilities as strings there.
Could I somehow remove those possibilities as strings to make it more secure?
Am I overlooking any potential memory issues e.g. should I be zeroing/wiping memory in areas where the password is stored after?

enum Password_Options
{
    ALPHANUM,
    ALL
}
private string CreatePassword(int length, Password_Options options)
{
    const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    const string valid_all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_-=+{}:;\\<>?|,./`~[]'";
    if (options == Password_Options.ALPHANUM){
        StringBuilder res = new StringBuilder();
        byte[] random = new byte[1];
        RNGCryptoServiceProvider rProvider = new RNGCryptoServiceProvider();
        while (0 < length--){
            rProvider.GetBytes(random);
            res.Append(valid[random[0] % (valid.Length - 1)]);
        }
        return res.ToString();
    }
    else{
        StringBuilder res = new StringBuilder();
        byte[] random = new byte[1];
        RNGCryptoServiceProvider rProvider = new RNGCryptoServiceProvider();
        while (0 < length--)
        {
            rProvider.GetBytes(random);
            res.Append(valid_all[random[0] % (valid_all.Length - 1)]);
        }
        return res.ToString();
    }
}

private void button1_Click(object sender, EventArgs e)
{
    Password_Options po;
    if (radioButton1.Checked){
        po = Password_Options.ALL;
    }
    else{
        po = Password_Options.ALPHANUM;
    }
    textBox1.Text = CreatePassword((int)numericUpDown1.Value,po);
}


texts: Problem in calculating prime numbers in python

texts:
I'm a noob in programming. I was asked to code a program that can calculate prime numbers. So i coded as provided below. But it prints all the Odd Numbers instead of Prime Numbers. I think the Value start is not being divided by all the integers in the range (2,Startnumber). It just prints all the odd numbers.

startnumber=int(raw_input("Enter a number: "))
start=2
while start<=startnumber:
    for divisor in range(2,startnumber):
        if start%divisor==0:
            break
        else:
            print start
            break
    start=start+1


texts:
List<string> difference tool for two input List<string> listA and listB

Output List<string>

both - in both listA and listB
listAonly - in listA only
listBonly - in listB only

Looking for speed, space, and style

.

//test
List<string> both;
List<string> both;
List<string> listAonly;
List<string> listBonly;
ListDiff( new List<string>() { "AAA", "BBB", "CCC", "DDD", "GGG", "FFF", "BBB", "GGG" }
        , new List<string>() { "AAA", "BBB", "DDD", "FFF", "EEE", "FFF", "EEE" }
        , false, out both, out listAonly, out listBonly );
Debug.WriteLine("both");
foreach (string s in both)
    Debug.WriteLine($"  {s}");
Debug.WriteLine("listAonly");
foreach (string s in listAonly)
    Debug.WriteLine($"  {s}");
Debug.WriteLine("listBonly");
foreach (string s in listBonly)
    Debug.WriteLine($"  {s}");
//end test

public static void ListDiff(List<string> listA, List<string> listB, bool ignoreCase, out List<string> both, out List<string> listAonly, out List<string> listBonly)
{
    both = new List<string>();
    listAonly = new List<string>();
    listBonly = new List<string>();

    IEnumerable<string> listAsorted = listA.OrderBy(x => x).Distinct();
    IEnumerable<string> listBsorted = listB.OrderBy(x => x).Distinct();

    var listAenumerator = listAsorted.GetEnumerator();
    var listBenumerator = listBsorted.GetEnumerator();

    bool listAcanmove = listAenumerator.MoveNext();
    bool listBcanmove = listBenumerator.MoveNext();

    while (listAcanmove | listBcanmove)
    {
        string valueA = listAenumerator.Current;
        string valueB = listBenumerator.Current;

        //Debug.WriteLine($"valueA = {valueA}");
        //Debug.WriteLine($"valueB = {valueB}");

        if (!listAcanmove && listBcanmove)
        {
            //Debug.WriteLine($"{valueB} in B not in A");
            listBonly.Add(valueB);
            listBcanmove = listBenumerator.MoveNext();
        }
        if (listAcanmove && !listBcanmove)
        {
            //Debug.WriteLine($"{valueA} in A not in B");
            listAonly.Add(valueA);
            listAcanmove = listAenumerator.MoveNext();
        }
        else
        {
            int comp = string.Compare(valueA, valueB, ignoreCase);
            if (comp == -1)
            {
                //Debug.WriteLine($"{valueA} in A not in B");
                listAonly.Add(valueA);
                listAcanmove = listAenumerator.MoveNext();
            }
            else if (comp == 1)
            {
                //Debug.WriteLine($"{valueB} in B not in A");
                listBonly.Add(valueB);
                listBcanmove = listBenumerator.MoveNext();
            }
            else
            {
                //Debug.WriteLine($"{valueA} {valueB} in B and A");
                both.Add(valueA);
                listAcanmove = listAenumerator.MoveNext();

                listBcanmove = listBenumerator.MoveNext();
            }
        }
        //Debug.WriteLine("");
    }
    //Debug.WriteLine($"done");
}


texts:
I have users uploading files sometimes as large as 100+ GB to a local web server.  The upload process works well and chunks come in at 50MB.  The problem seems to be after the file is uploaded, when the web server assembles the files and the server (24GB RAM), despite not showing any graphical signs of memory pressure, gets very sluggish.  I want to make sure my code isn't causing any unnecessary slow-downs.

Please suggest any more efficient way to do it.  If it is already ok, then I'll know to look at other aspects of the process.

# open the temp file to write into
with open(temp_filename, 'wb') as temp_file:
    # loop over the chunks
    for i in range(total_chunks):
        with open(os.path.join(get_chunk_filename(chunk_identifier, i + 1)), 'rb') as chunk_file:
            # write the chunk to the temp file
            temp_file.write(chunk_file.read())


texts:
I have a large file that I want to refactor.  My idea is to make helper classes with helper methods so that I can modularize methods.

Is that a good idea? For instance before refactoring:

public void collision(PhysicsCollisionEvent event) {
    if (event.getObjectA() instanceof BombControl) {
        final Spatial node = event.getNodeA();
        effect.killAllParticles();
        effect.setLocalTranslation(node.getLocalTranslation());
        BombControl bc = (BombControl) event.getObjectA();
        effect.emitAllParticles();
    } else if (event.getObjectB() instanceof BombControl) {
        final Spatial node = event.getNodeB();
        effect.killAllParticles();
        effect.setLocalTranslation(node.getLocalTranslation());
        effect.emitAllParticles();
    }
}

After refactoring:

public void collision(PhysicsCollisionEvent event) {
    CollisionHelper.collisionHelp(event, effect);
}

Is that a good idea or must I use a more elaborate recfactoring? I think it would work but I don't know of specific refactoring patterns.


texts: Validating an IP address and returning the reason it's invalid

texts:
I have a method that validates a user-written IP address in an Android application. If it's invalid, I need to know why and notify the user using a Toast.

I created an enum for this called Status that has a list of reasons for an IP address to be invalid and a value for when it's valid. The method isValid will return a Status value depending on whether or not it's invalid.

Android code

switch(IP.isValid(ip.getText().toString())) {
     case INVALID_NUMBER:
         Toast.makeText(MainActivity.this, "You have entered an invalid octect(s) value", Toast.LENGTH_SHORT).show();
         break;
     case INVALID_LENGTH:
         Toast.makeText(MainActivity.this, "You have entered an IP with an invalid length", Toast.LENGTH_SHORT).show();
         break;
     case NON_NUMERIC:
         Toast.makeText(MainActivity.this, "You have entered a non-numeric IP", Toast.LENGTH_SHORT).show();
         break;
}

ip is an EditText field.

Status enum

public enum Status {
    INVALID_NUMBER,
    INVALID_LENGTH,
    NON_NUMERIC,
    VALID
}

isValid() method

public static Status isValid(String ip) {
    String[] octets = ip.split("\\.");
    if(octets.length != 4) {
        return Status.INVALID_LENGTH;
    }

    for(String octet : octets) {
        if(StringUtils.isNumeric(octet)) {
            int val = Integer.parseInt(octet);
            if(val > 255 || val < 0) {
                return Status.INVALID_NUMBER;
            }
        } else {
            return Status.NON_NUMERIC;
        }
    }

    return Status.VALID;
}

StringUtils.isNumeric()

(StringUtils is a class I created, it's not from Apache)
https://stackoverflow.com/a/237204/4355066

public static boolean isNumeric(String str) {
    if (str == null) {
        return false;
    }
    int length = str.length();
    if (length == 0) {
        return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
        if (length == 1) {
            return false;
        }
        i = 1;
    }
    for (; i < length; i++) {
        char c = str.charAt(i);
        if (c < '0' || c > '9') {
            return false;
        }
    }
    return true;
}

Is this the best way to this?


texts: How to check list of environment variable in python?

texts:
I have requirement to check list of environment variable in Linux. Based on environment variable, exit code will be different. how to optimize the below code?

def check_mandatory_envs():
    if "ENVCONTEST_1" not in os.environ:
        exit(125)
    if "ENVCONTEST_2" not in os.environ:
        exit(126)
    if "ENVVIRTEST_3" not in os.environ
        exit(127)
    if "ENVVIRTEST_4" not in os.environ
        exit(128)
    if "ENVPATHTEST_5" not in os.environ
        exit(129)
    if "ENVPATHTEST_6" not in os.environ
        exit(130)


texts: Generic Doubly Linked-list implementation in C++

texts:
I am just learning about C++ templates and generic types, I decided it would be nice to try to create a generic container class as a challenge and test my knowledge in the process. Here is what I have come up with.

#include <iostream>
#include <cstdlib>
#include <cassert>

template <typename __T>

class List{
private:
    struct node{
        __T data;
        node* next;
        node* prev;
    };
    typedef long long unsigned int c_size;
    node* head;
    node* tail;
    node* current;
    c_size m_S;

public:
    List()
        :head{NULL},tail{NULL},current{NULL},m_S{0}
    {}

    List(std::initializer_list<__T> __l)
        :head{NULL},tail{NULL},current{NULL},m_S{0}
    {
        for(auto const& elem:__l){
            insert_back(elem);
        }
    }
    void insert_front(__T _d){
        ++m_S;
        node* new_node{new node};
        new_node->data = _d;
        new_node->next = head;
        new_node->prev = NULL;

        if (head != NULL){
            head->prev = new_node;
        }
        else
        {
            tail = new_node;
        }
        head = new_node;

    }

    void print(){
        if (m_S == 0) return;
        node *current = head;
        while (current->next != NULL){
            std::cout << current->data << ", ";
            current = current->next;
        }
        std::cout << current->data << '\n';
    }

    void insert_back(__T _d){
        ++m_S;
        node* new_node = new node;
        new_node->data = _d;
        new_node->next = NULL;
        node* last = head;

        if (head == NULL) {
            new_node->prev = NULL;
            head = new_node;
            tail = new_node;
        }
        else{
            tail->next = new_node;
            new_node->prev = tail;
            tail = new_node;
        }
    }

    constexpr __T first(){
        assert(head != NULL && "Calling .front() on an empty list");
        return head->data;
    }
    constexpr __T last(){
        assert(tail != NULL && "Calling. last() on an empty list");
        return tail->data;
    }

    constexpr c_size size(){return m_S;}

    void remove_all(){
        current = head;
        while(current->next != NULL){
            current = current->next;
            delete current;
        }
        head = NULL;
        tail = NULL;
        current = NULL;
    }

};

Thanks in advance !


texts:
Please give me any feedback regarding good coding standards and readability.

fun main(arg: Array<String>) {

    //do while user guess != Mersenne Prime.
    do {
        //initializing variable
        var number: Int = 3
        try {
            number = readLine()!!.toInt()

            if (isMersennePrime(number))
            println("${number} is a Mersenne Prime. Congratulations.")

            else
            println("${number} is not a Mersenne Prime.")
        }
        catch (e: NumberFormatException) {
            println(" is not a valid number. Exiting.")
        }
    } while (!isMersennePrime(number))
}

    // is Number both prime and 2^n - 1?
    fun isMersennePrime(Number: Int): Boolean =
    (twonminus1(Number.toDouble()) && isPrime(Number))

    // is x Prime?
    fun isPrime(x: Int): Boolean = (2..x-1).all{x % it != 0 && x != 2}

    // is x = 2^n - 1?
    fun twonminus1(x: Double): Boolean = Math.log(x + 1.0)/Math.log(2.0) % 1.0 == 0.0


texts:
I am inexperienced in C++.  I was able to get my LinkedList to be fully functional.  I was hoping to get some feedback as to whether or not I followed bad practices and if there are any risks associated with my code.

LinkedList.h

#pragma once

#include <string>

#include "Node.h"

class LinkedList
{
private:
    Node *head;
    int count;
public:
    LinkedList();
    ~LinkedList();
    int get_count();
    void AddNode(int);
    std::string GetList();
    bool Contains(int);
    void Remove(int);
    int GetValue(int);
};

LinkedList.cpp

#include <iostream>

#include "LinkedList.h"

LinkedList::LinkedList()
{
    head = new Node(0);
}

LinkedList::~LinkedList()
{
}

int LinkedList::get_count(){
    return count;
}

void LinkedList::AddNode(int _value){
    Node *node = new Node(_value);
    Node *previousNode = head;
    while (previousNode->next_node && previousNode->next_node->get_value() <= node->get_value()){
        previousNode = previousNode->next_node;
    }
    if (previousNode->next_node){
        node->next_node = previousNode->next_node;
    }
    previousNode->next_node = node;
    count++;
}

std::string LinkedList::GetList(){
    std::string list;
    Node *currentNode = head;
    while (currentNode->next_node){
        currentNode = currentNode->next_node;
        list += std::to_string(currentNode->get_value()) + " ";
    }
    return list;
}

bool LinkedList::Contains(int number){
    Node *currentNode = head;
    while (currentNode->next_node){
        currentNode = currentNode->next_node;
        if (currentNode->get_value() == number){
            return true;
        }
        if (currentNode->get_value() > number){
            return false;
        }
    }
    return false;
}

void LinkedList::Remove(int number){
    Node *previousNode = head;
    Node *currentNode = head;
    while (currentNode->next_node){
        previousNode = currentNode;
        currentNode = currentNode->next_node;
        if (currentNode->get_value() == number){
            previousNode->next_node = currentNode->next_node;
            delete currentNode;
            count--;
            return;
        }
    }
}

int LinkedList::GetValue(int index){
    Node *currentNode = head;
    int currentIndex = -1;
    while (currentNode->next_node){
        currentNode = currentNode->next_node;
        currentIndex++;
        if (index == currentIndex){
            return currentNode->get_value();
        }
    }
    return -1;
}

Node.h

#pragma once

class Node
{
private:
    int value;
public:
    Node(int);
    ~Node();
    Node *next_node;
    int get_value();
    void set_value(int);
};

Node.cpp

#include "Node.h"

Node::Node(int _value)
{
    value = _value;
}

Node::~Node()
{
}

int Node::get_value(){
    return value;
}
void Node::set_value(int _value){
    value = _value;
}


texts: Rust book chapter 8 department challenge

texts:
I am just starting my journey in to rust and will gladly accept any feedback you can give me. This is the third exercise in the Rust book chapter 8.

Exercise description

  Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.

src/main.rs

use std::collections::HashMap;
mod commands;

fn main() {
    let mut departments: HashMap<String, Vec<String>> = HashMap::new();
    println!("Welcome to Rust IFS");
    loop {
        commands::print_menu();
        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .expect("Invalid input");
        if input.to_lowercase().contains("q") && input.len() <= 5 {
            break;
        } else if input.to_lowercase().contains("add") && input.to_lowercase().contains("to") {
            println!("{}", commands::add_user(&mut input, &mut departments));
        } else if input.to_lowercase().contains("list") && input.len() == 5 {
            commands::print_users(&mut input, &mut departments);
        } else if input.to_lowercase().contains("list") && input.len() > 5 {
            commands::print_users_by_department(&input, &mut departments)
        } else {
            println!("\nInvalid input");
        }
        println!("Press Enter to continue...");
        commands::pause();
    }
}

src/commands.rs

use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::io::Read;

pub fn add_user(input: &mut String, departments: &mut HashMap<String, Vec<String>>) -> String {
    let split: Vec<&str> = input.split_whitespace().collect();

    if split.len() == 4 && split[0].contains("add") && split[2].contains("to") {
        if departments.contains_key(split[3]) {
            match departments.entry(String::from(split[3])) {
                Entry::Vacant(e) => {
                    e.insert(vec![String::from(split[1])]);
                }
                Entry::Occupied(mut e) => e.get_mut().push(String::from(split[1])),
            }

            String::from("Success!")
        } else {
            departments.insert(String::from(split[3]), vec![String::from(split[1])]);

            String::from("Success!")
        }
    } else {
        String::from("Invalid input")
    }
}

pub fn print_menu() {
    println!("Type: add [name] to [department] to add an employee to a department");
    println!("Type: list users to list all users");
    println!("Type: list [department] to list all users in department");
    println!("Type Quit to quit");
}

pub fn pause() {
    std::io::stdin().read(&mut [0]).expect("Invalid input");
}

pub fn print_users(input: &mut String, departments: &mut HashMap<String, Vec<String>>) {
    let split: Vec<&str> = input.split_whitespace().collect();
    if split.len() == 1 {
        for department in departments {
            department.1.sort();
            println!("{}:", department.0);
            for name in department.1 {
                println!("{}", name)
            }
        }
    }
}

pub fn print_users_by_department(input: &String, departments: &mut HashMap<String, Vec<String>>) {
    let split: Vec<&str> = input.split_whitespace().collect();
    if split.len() == 2 {
        for department in departments {
            department.1.sort();
            if department.0 == split[1] {
                println!("{}:", department.0);
                for name in department.1 {
                    println!("{}", name)
                }
            }
        }
    }
}
```


texts:
Please excuse my potentially noob-ish question.  I haven't touched strings in C (or C in general) in a while, and I seem to recall there being different ways you can return a C string from a function (as discussed here).

I am currently implementing a weird driver API that I inherited. Long story short, I get passed in a "device index", and then return the device name that will be used to open() the device.

Here is my implementation:

static const char* getDeviceName(uint8_t device_index) {
  static const char* const device_names[] =
    {"", "/dev/some_device", "/dev/some_other_device", "", "", "", "", "", ""};
  if (device_index > 8) {
    return "";
  } else {
    return device_names[device_index];
  }
}

Long story short, I am provided an index (as a uint8_t for some reason) and then need to convert it to a string.  As such, I create a constant array of constant strings, which is static.  Note that many of these indexes are empty since they currently do not map to a device, but may in the future.

If the device index is out of bounds, I return the empty string.  If the index is in bounds, I index into my constant array and return that value.

Since my C is rusty, I'm wondering if any of the above is UB, or if there are better ways of doing this.  I know I can have the function return void and have the caller pass in a char* for me to populate, but I think the above is the cleanest way, since I can do things like "open(getDeviceName(index));".

In addition to my questions about UB, I also wanted to make sure that the code is const correct.

At any rate, let me know your thoughts.  Thanks in advance for the help.


texts:
I am uploading an array of photos to the server (using Alamofire):

func uploadImages() {
  for card in cards! {
        let photo = card.media
        func onSuccess(jsonData: Any?) {
            photoCount += 1
            SVProgressHUD.dismiss()
            if let jsonData = jsonData { // unwrapping
                let json = JSON(jsonData)
                let photoAttr = photoAttributes(from: json)
                var photoStoryAttrElement = [String : AnyObject]()
                photoStoryAttrElement["photos_attributes"] = photoAttr as AnyObject
                photoStoryAttrElement["name"] = "Photo : \(photoCount)" as AnyObject
                if let placeID = card.location?.placeId {
                    let locationAttr = ["place_id" : placeID]
                    photoStoryAttrElement["location_attributes"] = locationAttr as AnyObject
                }

                if let caption = card.caption {
                    photoStoryAttrElement["description"] = caption  as AnyObject
                }
                photoStoryArray.append(photoStoryAttrElement)
            }

            if photoCount <= cards!.count {
                SVProgressHUD.show(withStatus: "Uploading Photo \(photoCount) of \(String(describing: cards!.count))")
            } else {
                uploadArticle(photoStories: photoStoryArray)
            }

            if jsonData != nil { // Unwrapping
            } else { // no value returned from response
                //                no value returned
            }

        }
        func onFailure(err: Error) {
            SVProgressHUD.dismiss()
            print("Failed to Upload image. Error: \(err)")
        }
        if photoCount == 1 {
            SVProgressHUD.show(withStatus: "Uploading Photo 1 of \(String(describing: cards!.count))")
        }
        uploadImage(image: photo!, imageKey: "photos[photo]", imageName: "filename", location_id: nil, location_place_id: nil, urlString: Constants.URL.kUploadPhoto, method: .post, param: nil, onSuccess: onSuccess, onFailure: onFailure)
    }

}

This function keeps counting till all photos are uploaded successfully and then calls another function uploadArticle(). Is there a better way to do it?


texts: What are the drawbacks of DRY input validation configuration?

texts:
I have designed the following input validation implementation with one goal: DRY. I'd like to know whether it is intuitive and what are the possible shortcomings.

$vlad = new \ay\vlad\Vlad();

$test = $vlad->test([ // Test script
    [ // Group of selectors and validators. Each selector is assessed against each validator.
        [ // Selectors
            'foo',
            'bar',
            'baz'
        ],
        [ // Validators/ validation options
            ['fail' => 'break'],
            // Define Validator failure scenario:
            // * 'silent' exclude input from the current validator chain.
            // * 'soft' record an error and progress to the next Validator.
            // * 'hard' (default) record an error and exclude the selector from the rest of the Test.
            // * 'break' record an error and interrupt the Test.
            'required',
            'not_empty',
            ['fail' => 'hard'], // Reset default Validator failure scenario.
            'email',
            ['length', 'max' => 10] // Length Validator with 'max' option.
        ]
    ],
    [
        ['qux', 'quux'],
        [
            // Validate email only if it is non-empty string.
            ['fail' => 'silent'],
            'not_empty',
            ['fail' => 'hard'],
            'email'
        ]
    ],
    [
        ['password'],
        [
            // 'password' selector value must match 'password_confirm' selector
            ['match', 'selector' => 'password_confirm']
        ]
    ]
]);

$result = $test->assess($dummy_input);

The entire library documentation and examples are avaiable at http://anuary.com/vlad.


texts:
A coding challenge to write a function sortStack that receives a stack of integers into ascending order (with largest integers on top) and returns another stack with sorted integers. At most one additional stack may be used to hold items; no other data structures may be used to copy or hold the elements.

Stack Class:

class Stack {
  constructor() {
    this.storage = [];
  }

  push(item) {
    this.storage.push(item);
  }

  pop() {
    return this.storage.pop();
  }

  peek() {
    return this.storage[this.storage.length-1];
  }

  isEmpty() {
    return this.storage.length === 0;
  }

  printContents() {
    this.storage.forEach(elem => console.log(elem));
  }
}

Stack:

const s = new Stack();
s.push(4);
s.push(10);
s.push(8);
s.push(5);
s.push(1);
s.push(6);

My solution:

const sortStack = (stack) => {
  sorted = new Stack();
  while (stack.storage.length) {
    tmp = stack.pop();
    if (tmp >= sorted.peek()) {
      sorted.push(tmp);
    } else {
      while (tmp < sorted.peek()) {
        stack.push(sorted.pop());
      }
      sorted.push(tmp);
    }
  }
  return sorted;
}

sortedStack = sortStack(s);
sortedStack.printContents(); // correctly outputs 1, 4, 5, 6, 8, 10

This iterative solution returns the correct output on multiple test cases, and there are no missing edge cases or other logical flaws that I can see, however I don't like the nested while-loop.

I want to keep the solution iterative, so how could I go about not having to use the nested while-loop?


texts: A simple functional F# wrapper for EasyNetQ

texts:
This is my first attempt at creating a small module to wrap the .NET library EasyNetQ in F# to make it more functional.

I am pretty new to F# and I would like to get feedbacks on everything: types, naming conventions, functional thinking, etc.

RabbitMQ.fs:

module RabbitMQ
    open EasyNetQ
    open System

    type BusConnection = {
        Address: string
        Port: uint16
        Username: string
        Password: string
    }

    type NamingConventions = {
        RetrieveQueueName: Type -> string -> string
        RetrieveExchangeName: Type -> string
        RetrieveErrorQueueName: MessageReceivedInfo -> string
        RetrieveErrorExchangeName: MessageReceivedInfo -> string
    }

    type Subscription<'T> = {
        Id: string
        OnMessageReceived: 'T -> unit
    }

    let private buildConnectionString (busConnection: BusConnection) =
        sprintf "host=%s:%d;username=%s;password=%s"
               busConnection.Address
               busConnection.Port
               busConnection.Username
               busConnection.Password

    let createBus (connection: BusConnection) =
        let connectionString = buildConnectionString connection
        RabbitHutch.CreateBus(connectionString)

    let publishAsync<'T> (bus: IBus) (message: 'T) = bus.PubSub.PublishAsync<'T>(message)
                                                     |> Async.AwaitTask

    let subscribeAsync<'T> (bus: IBus) (subscription: Subscription<'T>) = bus.PubSub.SubscribeAsync<'T>(subscription.Id, subscription.OnMessageReceived).AsTask()
                                                                          |> Async.AwaitTask

    let setNamingConventions (bus: IBus) (namingConventions: NamingConventions) =
        bus.Advanced.Conventions.QueueNamingConvention <- new QueueNameConvention(namingConventions.RetrieveQueueName)
        bus.Advanced.Conventions.ExchangeNamingConvention <- new ExchangeNameConvention(namingConventions.RetrieveExchangeName)
        bus.Advanced.Conventions.ErrorQueueNamingConvention <- new ErrorQueueNameConvention(namingConventions.RetrieveErrorQueueName)
        bus.Advanced.Conventions.ErrorExchangeNamingConvention <- new ErrorExchangeNameConvention(namingConventions.RetrieveErrorExchangeName)

Program.fs:

open RabbitMQ

type Message = {
    Text: string
}

[<EntryPoint>]
let main argv =
    let busConnection = {
        Address = "localhost"
        Port = 5672 |> uint16
        Username = "guest"
        Password = "guest"
    }
    let namingConventions = {
        RetrieveQueueName = fun messageType subscriptionId -> "Queue: " + (messageType.FullName + subscriptionId)
        RetrieveExchangeName = fun messageType -> "Exchange: " + messageType.FullName
        RetrieveErrorQueueName = fun messageReceivedInfo -> messageReceivedInfo.Queue + " - Error"
        RetrieveErrorExchangeName = fun messageReceivedInfo -> messageReceivedInfo.Exchange + " - Error"
    }
    use bus = createBus busConnection
    setNamingConventions bus namingConventions

    let subscription = {
        Id = "subscription_id"
        OnMessageReceived = fun (message: Message) -> printfn "%A" message
    }

    async {
        let! result = subscribeAsync<Message> bus subscription
        do! publishAsync<Message> bus {Text = "1"}
        do! publishAsync<Message> bus {Text = "2"}
        do! publishAsync<Message> bus {Text = "3"}
    } |> Async.RunSynchronously

    Console.waitPressKey

    0

Console.fs

module Console
    open System
    let waitPressKey = Console.ReadKey() |> ignore


texts: Design issues, tendency to write custom methods

texts:
I seem to have this tendency to write custom methods, i.e. code that isn't reusable. The following seems to be one example of trying to do too much in a single method.
But the point I'm not sure about is, in order to split it up, I'd have to redo the for loop each time. Is that acceptable?

Any general pointers on how this should be structured would really be appreciated.

public static void ShowInputs(DataTable dtSProcList, List<Label> inputLabels,
    ComboBox cbSProcList, List<TextBox> inputTxtboxes,
    List<TextBox> selectedSProcInputs,
    List<String> selectedSprocDataTypes, List<string> selectedSprocParamterNames)
{
    int counter = 0;

    for (int i = 0; i < dtSProcList.Rows.Count; i++)
    {
        if (dtSProcList.Rows[i][0].ToString() == cbSProcList.SelectedItem.ToString())
        {
            string temp = dtSProcList.Rows[i][0].ToString();
            if (dtSProcList.Rows[i][1] != DBNull.Value)
            {
                inputLabels[counter].Text = dtSProcList.Rows[i][1].ToString().Remove(0, 1);
                inputLabels[counter].Visible = true;
                inputLabels[counter].Enabled = true;
                inputTxtboxes[counter].Visible = true;
                inputTxtboxes[counter].Enabled = true;

                selectedSProcInputs.Add(inputTxtboxes[counter]);
                selectedSprocDataTypes.Add(dtSProcList.Rows[i][2].ToString());

                counter++;
            }
            else
            {
                //Returns control to calling method if the parameter name is null.
                return;
            }
        }
    }
}

EDIT: I had originally posted this on SO and was asked to report it here.


texts: Counting the triangles that can be formed from segments of given lengths

texts:
Problem Statement:

  Given an unsorted array of positive integers. Find the number of
  triangles that can be formed with three different array elements as
  lengths of three sides of triangles.

  Input:  The first line of the input contains T denoting the number of testcases. First line of test case is the length of array N and
  second line of test case are its elements.

  Output: Number of possible triangles are displayed to the user.

  Constraints:

  \$1 \le T \le 200\$
  \$3 \le N \le 10^7\$
  \$1 \le \mathrm{arr}[i] \le 10^3\$

  Example:

  Input:

  2
3
3 5 4
5
6 4 9 7 8

  Output:

  1
10

Algorithm:

The efficient \$O(n^2)\$ algorithm for solving this problem has been explained here.

  Let \$a\$, \$b\$ and \$c\$ be three sides. The below condition must
  hold for a triangle (Sum of two sides is greater than the third side)
  i) \$a + b > c\$ ii) \$b + c > a\$ iii) \$a + c > b\$

  Following are steps to count triangle.

  Sort the array in non-decreasing order.
  Initialize two pointers i and j to first and second elements respectively, and initialize count of triangles as 0.
  Fix i and j and find the rightmost index k (or largest arr[k]) such that arr[i] + arr[j] > arr[k]. The number of
  triangles that can be formed with arr[i] and arr[j] as two sides
  is k – j. Add k – j to count of triangles.

  Let us consider arr[i] as \$a\$, arr[j] as \$b\$ and all
  elements between arr[j+1] and arr[k] as \$c\$. The above mentioned
  conditions (ii) and (iii) are satisfied because arr[i] < arr[j] <
  arr[k]. And we check for condition (i) when we pick k.
  Increment j to fix the second element again.

  Note that in step 3, we can use the previous value of k. The reason is simple, if we know that the value of arr[i] + arr[j-1] is
  greater than arr[k], then we can say arr[i] + arr[j] will also be
  greater than arr[k], because the array is sorted in increasing
  order.
  If j has reached end, then increment i. Initialize j as i + 1, k as i+2 and repeat the steps 3 and 4.

Code Implementation (in C++):

This is my implementation of the algorithm in C++ (using vectors instead of raw arrays):

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;
int triangles (vector<int> &V, int N);

int main () {
    int T;
    cin >> T;
    vector<int> V;
    for (int i = 0; i < T; i++)
    {
        int N;
        cin >> N;
        for (int j = 0; j < N; j++)
        {
           int temp;
           cin >> temp;
           V.push_back(temp);
        }
        cout << triangles (V, N) << endl;
        V.clear();
    }
    return 0;
}

int triangles (vector<int> &V, int N)
{
    int sum = 0;
    sort(V.begin(), V.end());
    for (int i = 0; i <= N-3; i++)
    {
        int k = i + 2;
        for (int j = i + 1; j <= N-2; j++)
        {
            while (k < N && V[k] < V[i] + V[j])
                k++;
            sum += k-j-1;
        }
    }
    return sum;
}

Problem:

The code gives the perfectly correct output for any input, however, when I submit the code on GeekForGeeks Practice, it says

  Your program took more time than expected (Time Limit Exceeded).
  Expected Time Limit < 2.656sec. Hint: Please optimize your code and submit again.

At this point, I'm not sure how to optimize my code. Any ideas? Do I necessarily need to use an array instead of a vector in order to speed up the program?


texts:
I have a search function on my website. In addition, elsewhere I have a place where users can submit categories for their posts. I want the categories to have an uppercase first letter and the rest lower case. I know there far more complex ways to secure a user input string, but do you think that as a fairly basic function, this is relatively secure?

    function purify_string($string){
       $script_tags = "/\<script +(.+)<\/script>+/i";
       $string = strip_tags(addslashes($string));
       $string = preg_replace($script_tags, '', $string);
       $string = trim($string);
       $string = strtolower($string);
       $string = ucfirst($string);
       return $string;
     }