texts:
I created a PHP script which will be running 24/7 as a TCP socket server and will send data from the DB back to clients. The code is working, and so far, I see no problems.

However, I can only test it with one client. The info I need is, what will happen when there will be 100+ clients? Can any of you see any weaknesses in the code? Can I test it somehow?

include('db_con.php');
include('db_functions.php');
error_reporting(E_ALL);

// Allow the script to hang around waiting for connections
set_time_limit(0);

// Turn on implicit output flushing so we see what we're getting as it comes in
ob_implicit_flush();

$address = '10.4.1.6';
$port = 4950;

$failed = 0;

try {
    // Create a socket (AF_INET = IPV4, SOCK_STREAM=TCP stream)
    $failed = 1;
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    // Bind connection to IP/port
    $failed = 2;
    socket_bind($sock, $address, $port);

    $failed = 3;
    socket_listen($sock, SOMAXCONN);

    while (true) {
        // Accept connection
        $failed = 4;
        $client = socket_accept($sock);

        $failed = 6;
        $rec = socket_read($client, 1024);
        $id_d = substr($rec, 0, 1);
        $id = intval(substr($rec, 1, 1));

        // Connect to database and get results
        $failed = 7;

        $failed = 8;
        $data = "ok\r\n";

        if (strcmp($id_d, 'o') == 0) {
            $in_O = returnResultsForTCP_O($db, $id);
            foreach ($in_O as $r) {
                $data .= 'o'
                        . $r['ring_time'] . ' '
                        . ((int) $r['duration'] < 100 ? '0' : '')
                        . $r['duration'] . ' '
                        . $r['bell_mode'] . '\r\n';
            }
        } else {
            $in_D = returnResultsForTCP_D($db, $id);
            $in_W = returnResultsForTCP_W($db, $id);
            foreach ($in_D as $r) {
                $data .= 'd'
                        . $r['ring_time'] . ' '
                        . ((int) $r['duration'] < 100 ? '0' : '')
                        . $r['duration'] . ' '
                        . $r['bell_mode'] . '\r\n';
            }

            foreach ($in_W as $r) {
                $data .= 'w'
                        . $r['ring_time'] . ' '
                        . ((int) $r['duration'] < 100 ? '0' : '')
                        . $r['duration'] . ' '
                        . $r['day'] . ' '
                        . $r['bell_mode'] . '\r\n';
            }
        }

        $failed = 5;
        socket_write($client, $data);
        socket_close($client);
    }
} catch (Exception $e) {
    if ($failed < 6) {
        $causes = array('create', 'bind', 'listen', 'accept', 'write');
        echo 'socket_' . $causes[$failed - 1] . '() failed. Reason: '
                . socket_strerror(socket_last_error($sock)) . '\n';
    } else {
        echo 'Failed at ' . $failed . '\n' . $e . '\n';
    }

    socket_close($sock);
}

The $failed part is just for testing; I'll remake it later (change it so the logs will be written to file - logging).


texts: What is better for the code segment, sockets or multiple processes?

texts:
I am trying to fetch information out of SHOUTcast for mutiple users at the same time. Here is my current code:

<?php
    header("Access-Control-Allow-Origin:*");

    function failOut($http, $text) {
        header('HTTP/1.x ' . $http);
        die(htmlspecialchars($text));
    }

    $params = $_GET;
    $user = 'root'; // Change this to username
    $password = ''; // Put your password here. My home database doesn't have any password (is empty).

    $con = mysql_connect('localhost',$user,$password) or die('Could Not Connect..');

    $context = stream_context_create(
        array(
            'http' => array(
                //Required To fool ShoutCast or it will flood with the stream instead
                'user_agent' => "GET / HTTP/1.0\r\n"
                            ."Host:117.200.149.48\r\n"
                            ."User-Agent: Mozilla/5.0 (compatible; ShoutCastInfoClass/0.0.2; ".PHP_OS.")\r\n"
                            ."\r\n",
            ),
        )
    );

    if($params['act'] == 'st'){
        mysql_select_db('radio',$con);
        $count = mysql_query("select * from info where ID='".$params['id']."'")or die('Error In Query'.mysql_error());

        $content = null;
        $rows = mysql_num_rows($count);
        if( $rows > 0 ){
            $res = mysql_fetch_assoc($count);

            if($res['TIMESTAMP'] + 30 < time()){
                if($res['version'] == '1'){
                    $base = $res['IP'].'/admin.cgi?mode=viewxml&user=admin&pass='.$res['PASS'];
                    // Well i will change this crazy method with something non password secured pretty soon
                }else{
                    $base = $res['IP'].'/stats?sid=1';
                    // As per shoutcast v2 APIs !! :D
                }
                $content = file_get_contents($base, false, $context)or die("Unable to Load resourse");
                $dom = new DOMDocument();
                $dom->loadXML($content);
                $res['SERVERTITLE'] =  htmlspecialchars($dom->getElementsByTagName('SERVERTITLE')->item(0)->textContent);
                $res['SONGTITLE'] = htmlspecialchars( $dom->getElementsByTagName('SONGTITLE')->item(0)->textContent );
                $res['BITRATE'] = $dom->getElementsByTagName('BITRATE')->item(0)->textContent;
                $res['GENRE'] = $dom->getElementsByTagName('SERVERGENRE')->item(0)->textContent;
                $res['CONTENT'] = $dom->getElementsByTagName('CONTENT')->item(0)->textContent;

                if(strpos($res['CONTENT'],'mpeg')){
                    $res['CONTENT'] = 'MP3';
                }else if(strpos($res['CONTENT'],'aac')){
                    $res['CONTENT']= 'AAC';
                }else{
                    $res['CONTENT'] = 'OGG';
                }
                $query='update INFO SET SERVERTITLE="'.$res['SERVERTITLE'].
                '", SONGTITLE="'.$res['SONGTITLE'].
                '", BITRATE="'.$res['BITRATE'].
                '", GENRE="'.$res['GENRE'].
                '", CONTENT="'.$res['CONTENT'].
                '" , TIMESTAMP='.time().' where ID=\''.$params['id']. '\';';
                mysql_query($query,$con)or die(mysql_error());
                mysql_close($con);
            }
            unset( $res['IP'] );
            unset( $res['PASS'] );
            echo json_encode($res);
        }
    }else if($_params['act']== 's'){
        // To search for a specific keyword
        $queryString = $params['q'];
    }else if($_params['act'] == 'l'){
        // To feed list to the applet
        $cat = $params['c'];
        // Categories are various lists depending on genre languages etc...
    }
?>

I was wondering if making a phpSocket server would be better for this purpose as sockets will reduce the demand of required MySQL connections to be opened.

Or

Is my current method the best solution?


texts: Dependency Inversion Principle and Dependency Injection in C#

texts:
I was doing some sample example which were perfectly fine. But, when I read about SOLID design principle, I had to change my code.

I have implemented DIP and DI (Constructor Injection) in my code. Please let me know whether I have implemented successfully or not.

Old code before SOLID design principlss:

class Program
{
    static void Main(string[] args)
    {
        Higherclass obj = new Higherclass("Female");
        obj.CallLowerClass();
        Console.ReadLine();
    }

}

public class Higherclass
{
    public readonly string sex;
    lowerClass_Male objLowerClass_Male = null;
    lowerClass_Female objLowerClass_Female = null;

    public Higherclass(string _sex)
    {
        sex = _sex;
    }

    public void CallLowerClass()
    {
        if (sex == "Male")
        {
            objLowerClass_Male = new lowerClass_Male();
            objLowerClass_Male.DoSomeAction();
        }
        else
        {
            objLowerClass_Female = new lowerClass_Female();
            objLowerClass_Female.DoSomeAction();
        }

    }
}

public class lowerClass_Male
{
    public void DoSomeAction()
    {
        Console.WriteLine("Hey It's Male. Do Some Action");
    }
}

public class lowerClass_Female
{
    public void DoSomeAction()
    {
        Console.WriteLine("Hey It's FeMale. Do Some Action");
    }
}

Newly modified code:

class Program
{
    static void Main(string[] args)
    {
        //Now, It depends on my requirement to call any sex class.Let's Say, I want to call Female Class.
        lowerClass_FeMale objLowerfemale = new lowerClass_FeMale();
        Higherclass obj = new Higherclass(objLowerfemale);
        obj.CallLowerClass();
        Console.ReadLine();
    }

}

public interface ISex
{
    void DoSomeAction();
}

public class lowerClass_Male : ISex
{
    public void DoSomeAction()
    {
        Console.WriteLine("Hey It's Male. Do Some Action");
    }
}

public class lowerClass_FeMale : ISex
{
    public void DoSomeAction()
    {
        Console.WriteLine("Hey It's FeMale. Do Some Action");
    }
}

public class Higherclass
{
    public ISex MySexInterface = null;
    public Higherclass(ISex objISex)
    {
        this.MySexInterface = objISex;
    }

    public void CallLowerClass()
    {
        MySexInterface.DoSomeAction();
    }

}


texts: Rounding a time to its lowest quarter-hour

texts:
I calculate the lowest quarter-hour using the following code:

public Date getQuarter() {
    Calendar calendar = Calendar.getInstance();
    int mins = calendar.get(Calendar.MINUTE);

    if (mins < 15) {
        mins = 0;
    } else if (mins < 30) {
        mins = 15;
    } else if (mins < 45) {
        mins = 30;
    } else {
        mins = 45;
    }

    calendar.set(Calendar.MINUTE, mins);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}

How can this become better / more elegant?


texts: Use filter_var_array on whole array, or inside iteration

texts:
I have a MySQL result set in a PHP multidimensional array.

I want to iterate through it and output it sanitized. Considering the two alternatives below, are there any performance differences?

filter_var_array on the whole result set before iterating:

$sql_rows = filter_var_array($sql_rows, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
foreach ($sql_rows as $sql_row) {
    print '
' . $sql_row['first_name'] . $sql_row['last_name'] . '
';
}

filter_var_array on each row inside the iteration:

foreach ($sql_rows as $sql_row) {
    $sql_row = filter_var_array($sql_row, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    print '
' . $sql_row['first_name'] . $sql_row['last_name'] . '
';
}


texts:
I am trying to eliminate unwanted namespaces, and I know there's a better way to do this.  This code works, but it's remedial and redundant.

string sPattern = "xmlns:d5p1=\"http://www.w3.org/2001/XMLSchema-instance\" d5p1:nil=\"true\"";
string sPattern2 = "d5p1:nil=\"true\" xmlns:d5p1=\"http://www.w3.org/2001/XMLSchema-instance\"";
string sPattern3 = "xmlns:d2p1=\"http://www.w3.org/2001/XMLSchema-instance\" d2p1:nil=\"true\"";

string[] fString = new string[sentences.Count()];
//foreach (string str in sentences)
for(int i=0; i < sentences.Count(); i++)
{
    Console.WriteLine("{0,24}", sentences[i]); // lines 0-24.
    if(System.Text.RegularExpressions.Regex.IsMatch(sentences[i], sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
    {
        Console.WriteLine(" (match for '{0}' found)", sPattern);
        eString = sentences[i].Replace(sPattern, "");

    }
    else if(System.Text.RegularExpressions.Regex.IsMatch(sentences[i], sPattern2, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
    {
        Console.WriteLine(" (match for '{0}' found)", sPattern2);
        eString = sentences[i].Replace(sPattern2, "");
    }
    else if (System.Text.RegularExpressions.Regex.IsMatch(sentences[i], sPattern3, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
    {
        Console.WriteLine(" (match for '{0}' found)", sPattern3);
        eString = sentences[i].Replace(sPattern3, "");
    }
    else
    {
        Console.WriteLine();
        eString = sentences[i];
    }

    fString[i] = eString;
}

// ok, let's look at the end result
foreach(string s in fString)
{

    Console.WriteLine(s);
}

// stop the app from shutting down before seeing results
Console.ReadLine();


texts:
This class is helping to manipulate by output streams stderr, stdout, and file. Are there any cons and errors in this code?

class OutSplitter(object):
""" splitter """

def __init__(self, out_splitter):
    self.__pipes=None
    if isinstance(out_splitter, OutSplitter):
            self.__pipes = Set(out_splitter.pipes)
    elif out_splitter:
        if hasattr(out_splitter,"__iter__") : #
            for pn in out_splitter:
                self.add_pipe(pn)
        else:
            self.add_pipe(out_splitter)

@property
def pipes(self):
    return self.__pipes

def add_pipe(self, pn):
    if isinstance(pn, basestring):
        if pn == 'stderr': x = sys.stderr
        elif pn == 'stdout': x = sys.stdout
        else:
            p = os.path.dirname(pn)
            if p and not os.path.exists(p):
                os.makedirs(p)
            x = open(pn,'w+')
    else: x = pn

    if hasattr(x, 'write') and hasattr(x, 'flush'):
        if self.__pipes is None:
            self.__pipes=Set()
        self.__pipes.add(x)

def write(self,s):
    if self.__pipes:
        for p in self.__pipes:
            p.write(s)

def flush(self):
    if self.__pipes:
        for p in self.__pipes:
            p.flush()


texts:
I need to read a range of bytes from a file and return it as a std::vector<std::byte>.

My current code looks like this:

#include <cstdint>
#include <fstream>
#include <string>
#include <vector>

using bytes = std::vector<std::byte>;
using namespace std;

bytes read_block(uint32_t offset,
                 uint32_t length,
                 const string& filename) {
  ifstream is(filename, ios::binary);
  is.seekg(offset);
  byte data[length];
  is.read(reinterpret_cast<char*>(data), length);
  return bytes(data, data + length);
}

But as can be seen I read it into a byte array and then create the vector by copying the bytes in the constructor. I have some issues with this implementation:

Copying of bytes when creating output variable.
Use of C style array.
Use of casts.

I have left out error handling for now to focus on the specific issues above.


texts:
I have a cycle which goes from -55 to -1, then from 1 to 55 before going back to -55 again. I want to make a loop going from an arbitrary point in this loop to another arbitrary point, but never as far as a full cycle.
Since the end value of the counter might be either a larger or smaller than the start value, I initially made the exit condition for the loop that fra equals til.
However, I also want to do something when fra = til, so in the end my loop ended up looking like what you can see below, with a helper-variable triggering the exit.
I am not all that happy with how this ended up looking though, feeling the logic is a bit clunky. Is there some way to improve the code below?
Option Explicit

Dim første_økt_anodeskift(1 To 10, 1 To 2) As Long

Const farge_anodeskift_1 As Long = 14395790 ' RGB(142, 169, 219)

Sub main()
    Dim syklus As Long

    syklus = 1

    Call legg_inn_verdier
    Call fargelegg(første_økt_anodeskift(syklus, 1), første_økt_anodeskift(syklus, 2), farge_anodeskift_1)
End Sub

Private Sub fargelegg(fra, til, farge)
    Dim exit_on_next As Boolean

    exit_on_next = False

    Do
        ' Do stuff

        If exit_on_next Then Exit Do

        fra = fra + 1

        If fra = 0 Then
            fra = 1
        ElseIf fra = 56 Then
            fra = -55
        End If

        If fra = til Then exit_on_next = True
    Loop While True
End Sub

Private Sub legg_inn_verdier()
    første_økt_anodeskift(1, 1) = -11: første_økt_anodeskift(1, 2) = 6
End Sub
```


texts:
I have a method that iterate a list of maps if a certain element is found then set value of certain variables and break the loop.
I'm trying to revamp this into Java 8. And further if it can be improved, please suggest.

public static void doAction(List<Map<String, String>> decisionTree, String code, StringBuilder destination) {
    boolean conditionFound = false;
    boolean decisionFound = false;
    for (int i = 0; i < 100; i++) {
        if (null != decisionTree) {
            for (Map<String, String> decisionMap : decisionTree) {
                if (null != decisionMap && code.equalsIgnoreCase(decisionMap.get("code"))) {
                    decisionFound = true;
                    String decision = decisionMap.get("is_success");
                    String decisionAction = decisionMap.get("action");

                    BiPredicate<String, String> isApplicable = (d, a) -> "N".equalsIgnoreCase(d) && "Z".equalsIgnoreCase(a);

                    if (isApplicable.test(decision, decisionAction)) {
                        destination.append(decisionMap.get("destination"));
                        conditionFound = Boolean.TRUE;
                    }
                    break;
                }
            }
            if(decisionFound){
                if(conditionFound){
                    // do something
                    break;
                }
            }
        }
    }
}


texts:
I built the Set Matrix Zeroes algorithm in JavaScript. I have a lot of loops in my code, so was wondering if there is a better way to implement this algorithm.
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
I loop through the matrix and when I find a 0, I set its entire row and column to a flag ('X'). I do not set 'X' if the position is a 0 because I might need to check this position in the future. At the end I replace all the 'X' to 0.

var setZeroes = function(matrix) {
    if(matrix === null || matrix.length === 0)
        return [];

    for(let i=0; i<matrix.length; i++){
        for(let j=0; j<matrix[i].length; j++){
            if(matrix[i][j] === 0){
                setFlag(matrix, i, j);
            }
        }
    }

    for(i=0; i<matrix.length; i++){
        for(j=0; j<matrix[i].length; j++){
            if(matrix[i][j] === 'X')
                matrix[i][j] = 0;
        }
    }
};

const setFlag = function(matrix, i, j) {
    matrix[i][j] = 'X';
    let tempI = i+1;
    while(tempI < matrix.length){
        if(matrix[tempI][j] !== 0)
            matrix[tempI][j] = 'X';
        tempI++;
    }
    tempI = i-1;
    while(tempI >= 0){
        if(matrix[tempI][j] !== 0)
            matrix[tempI][j] = 'X';
        tempI--;
    }
    let tempJ = j+1;
    while(tempJ < matrix[i].length){
        if(matrix[i][tempJ] !== 0)
            matrix[i][tempJ] = 'X';
        tempJ++;
    }
    tempJ = j-1;
    while(tempJ >= 0){
        if(matrix[i][tempJ] !== 0)
            matrix[i][tempJ] = 'X';
        tempJ--;
    }
}
```


texts:
So I've been looking for examples on the internet for a while now and this seems the most common way everyone is suggesting, but now I ask is there a better way to make a new jframe pop up on click than this.

The code :

JLabel prevention = new JLabel("Prevencija");
    prevention.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 100));
    prevention.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            JFrame jf = new JFrame("Prevencija");
            jf.setContentPane(new PreventionPanel());
            jf.setSize(new Dimension(400, 400));
            jf.setVisible(true);
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    });
    bottom.add(prevention);


texts:
Intro
We have some old(in my eyes) software at the place I work at the moment,
Some stuff needs to be done manually, for instance we need to insert a XML file into a Oracle table, which will trigger... stuff
I got annoyed by having to do this manually all the time,
So I decided to automate the process a bit with powershell and Oracle's sqlldr
My knowledge of Oracle is limited hence the asking for a review,
What I did

I have created a separate table, to which I am inserting my file.
That table has a trigger, to get the specified information, and insert it into the correct table (which is not up for review)
Created a powershell script to be able to load files in bulk into the table

Code
The sql script for creating the table
CREATE TABLE mckdev.ogd_xml_table (
  id        NUMBER(10),
  xml       XMLTYPE,
  "IN_CON_LOG" NUMBER(1,0),
  "ZIS_EVENT" VARCHAR2(35 BYTE),
);

ALTER TABLE mckdev.ogd_xml_table ADD (
  CONSTRAINT ogd_xml_table_pk PRIMARY KEY (id)
);

CREATE SEQUENCE mckdev.ogd_xml_table_seq;

The load_data.ctl
load data
infile ''
append
into table ogd_xml_table
fields
(
    filename FILLER CHAR(100),
    xml lobfile( filename) terminated by eof
)

The bulkloader.ps1
$dataFiles = @(
    "filelist21.dat"
    "filelist22.dat",
    "filelist23.dat",
    "filelist25.dat",
    "filelist121a.dat",
    "filelist121b.dat",
    "filelist122a.dat",
    "filelist122b.dat"
)
$ctlFile = "$PSScriptRoot\load_data.ctl"

foreach ($f in $dataFiles) {
    (Get-Content $ctlFile) -Replace "infile '[^']*'", "infile '$($PSScriptRoot)\$($f)'" | Out-File $ctlFile -Encoding ASCII
    sqlldr mckdev@$SecretDatabase/$SecretPassword control=$ctlFile
}

An example filelist.dat only holds a reference to another XML file.
Questions

Currently I need to have multiple .dat file to be able to load them in bulk.
One for each XML file I want to load into the table. Is there any way around this?

Is this a correct approach or would you have done things differently?


texts: Optimizing Miller-Rabin Primality Test in Python

texts:
I'm writing a Miller-Rabin primality test in Python. While I've briefly looked at how others approached the problem, I decided to try solving the problem on my own. Aside from my choice of language, how could I go about optimizing this code? Any suggestions are welcome and don't hesitate to be brutally honest.

def miller_rabin_primality_test(n):

    def mr_check_one(n):
        m = n - 1
        n = n - 1
        k =  1

        while n % 2**k == 0:
            m = n / 2**k
            k = k + 1

        return(m)

    def mr_check_two(n, m, a = [2, 3]):

        for i in range(0, len(a)):
            a = a[i]
            b = pow(a, m, n)
            i = 0

            if(b == n - 1 or b == 1):
                return True

            while(b != n - 1 and i < 7):
                b = pow(b, 2, n)
                i = i + 1

            if(b != n - 1):
                return False
            else:
                return True

    m =  mr_check_one(n)
    r = mr_check_two(n, m)

    return(r)


texts: Loop to copy values from one sheet and paste the values 68 times in another, time efficiency

texts:
I have created a large VBA program to automate creation of a data table that is needed to run slicers in an Excel file.
While the loop works well in creating what I need, the main loop take an hour to create the list of company names that I need. I was wondering if there is a way to improve the time it takes for the loop to complete.
I have 191 rows that need to be copied and then pasted 68 times each into the new sheet. I have tried a few different approaches to improve the time and have only reduced the time required to about 50 minutes. Any help would be much appreciated. I know that using select is horrible for time efficiency but all the other options I have tried have not worked well.

Application.ScreenUpdating = False

Dim rng As Range, cell As Range
For Each cell In rng

    Sheets("Input Data").Select
    cell.Select
    cell.Copy
    Sheets("TrialSheet").Select
    For i = 1 To 68
        LastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
        Range("A" & LastRow).Select
        ActiveSheet.Paste
    Next i

    Sheets("Input Data").Select

Next cell

Application.ScreenUpdating = True


texts: A program that reads 8763x2 values from a CSV file and initialises an array and few other variables

texts:
Relatively new to Python. Have some experience in C++.

I have written a small program that reads a CSV file (SAMPLE) and initialises two arrays and few values. There are 2 values in each line, and there are 8763 such lines. The first value of each line is put into one array and the second value is put into the second array. The last three values of each array (total 6) are then given to another variable.

I want further calculations as accurate as possible hence I've tried the decimal.Decimal approach for Float Point Arithmetic, but for some reason, it's not that accurate. I think I'm using it wrong. It is still in an acceptable tolerance.

Also, would like to know if there is a better/efficient way to initialise the array and/or variables.

Here is code:

    alpha = np.zeros(8763, dtype='float32')  # Edited in later for clarity
    gamma = np.zeros(8763, dtype='float32')  # Edited in later for clarity
    rf = 100
    counter = 0
    with open('CSVData.csv', 'r') as csv_file_in:
        csv_reader = csv.reader(csv_file_in)
        for line in csv_reader:
            alpha[counter] = (float(decimal.Decimal(line[0])))  # Alpha Angle Initialized
            gamma[counter] = (float(decimal.Decimal(line[1])))  # Gamma Angle Initialized
            if counter == 8762:
                break
            counter = counter + 1
    csv_file_in.close()

    # Initializing last 6 parameters
    C_NSX = rf * alpha[8760]
    C_NSY = rf * gamma[8760]
    C_EWX = rf * alpha[8761]
    C_EWY = rf * gamma[8761]
    NSC = int(alpha[8762])
    EWC = int(gamma[8762])

Here the value of C_NSX should be 2790 but is 2789.9999185. (Debug Image)

EDIT: ADDED INFO ON THE PURPOSE OF THIS CODE

Following is my problem statement:

There is a matrix of octagons, for example, 4 octagons in a row and 3 such rows. So 4 columns and 3 rows of octagons. But they are not arranged in a perfect rectangle form.

Case1:

The first Octagon, O(0,0) has coordinates(0,0), while the one at its right and the one at the bottom are at a bit offset. So O(0,1) has coordinates (15,50) and O(1,0) has coordinates (30,15). This information is enough to define the whole array of octagons. Now next requirement is to find how much is the net visible area of these octagons. In the first example, as the coordinates are far away, there would be no overlapping and total visible area is simply...

Total_Visible_Area = Area_of_Single_Octagon * No_Of_Rows * No_Of_Columns

But when the coordinates are a bit complex, for example, Case 2:

Here, the distance between the adjacent octagons is less than their width and hence they are overlapping. Coordinates also are negative (which does not matter much actually, just something to note). Now to determine the visible area for this I wrote the following function.

The piece of code that I have written above is the first step to calculate all these. Each case is defined using Alpha, Gamma, C_NSX, C_NSY, C_EWX, C_EWY, NSC and EWC. Among these Alpha and Gamma have 8760 different values (mostly zeroes) and all others (capitals) are constants. I have to find the overlapping area in each of the 8760 cases. The code for finding those I had discussed here earlier, and thought won't be necessary to bring out again. After that last question, I have moved to python from CPP and started learning OpenCV.


texts:
Problem Statement
  Write a JavaScript program that prints the mouse coordinates in a text area when the mouse cursor is moved over the HTML document.

  Expected Output

Solution

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Track mouse coordinates</title>

Above code is written using deprecated API captureEvents.MDN says, captureEvents is deprecated.

Code still works fine with this deprecated API.

Can this code be improved, by replacing captureEvents with a better standard API?


texts: Checking for palindromes using dynamic memory allocation

texts:
This is a homework assignment, but it's already done and it's not for a grade; it's meant as a refresher for the rest of the course. I've never done anything with dynamic memory allocation in C before, so I'm assuming I've done at least something wrong.

The goal is to write a program that takes a string from a user and checks to see if it's a palindrome. All non-letter characters are ignored, and dynamic memory allocation is required.

It works fine and I'm pretty happy with it, but I have no way of knowing if I've done things the "right" or "wrong" way. So, could anyone look over it really quickly and point out all the stupid things I've done?

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

int main(void)
{
    //str holds raw input
    //str_san holds sanitized input
    char *str = (char *)malloc(50), *str_san;
    //i and k are the index counters
    //len is the length of the sanatized string
    int i = 0, k = 0, len;

    //get a string from the user
    printf("Enter a message: \n");
    //store it in str
    scanf("%s", str);

    //make str_san as small as possible
    str_san = (char*)malloc(strlen(str) + 1);

    //copy only letters into the sanitized string
    while (str[i] != '\0') {
        if (str[i] >= 'A' && str[i] <= 'Z') {
            str_san[k] = str[i] + 32; //changes uppercase to lowercase
            k++;
        }

        if (str[i] >= 'a' && str[i] <= 'z') {
            str_san[k] = str[i];
            k++;
        }

        i++;
    }

    //str is no longer needed
    free(str);

    //terminate sanitized string
    str_san[k] = '\0';

    //set len to the length of str_san
    len = strlen(str_san);

    //check for palindrominess
    for (i = 0; i < len; i++) {
        //if the first letter does not equal the last letter then it's not a palindrome
        if (str_san[i] != str_san[len - i - 1]) {
            printf("Not a palindrome");
            return 0;
        }
    }

    //it is now safe to free str_san
    free(str_san);

    //if we've made it this far, it's a palindrome
    printf("Palindrome");

    return 0;
}


texts: Project Euler #2: sum of even Fibonacci numbers, using generators

texts:
I am currently working on Project Euler problem #2 which requires you to print the sum of all even fibonacci numbers below 4 million.

I just recently learned about generators and from my understanding they are used to decrease memory consumption by generating values on the fly (and not storing them in a huge list).

Does this still work when used in a for loop or will it just generate all values, store them in a list and then loop through them?

for n in some_generator(): pass

In my specific case the code looks like this:

def fibonacci(n): # yields all fibonacci numbers below n
    second_last_n = 0
    last_n = 1
    while (last_n < n):
        current_n = second_last_n + last_n
        second_last_n = last_n
        last_n = current_n
        yield current_n

def filter_even(nums): # yields all numbers in nums (a generator) which are even
    for n in nums:
        if (n % 2 == 0):
            yield n


texts: Vectorize a function that, once per row, updates multiple rows in data.table

texts:
Requirements

I have a table of the different diagnoses a patient has received, with the date the diagnosis was first recorded. It so happens that in medicine, diagnoses are recorded as codes from a huge list called ICD10, and sometimes several different codes are related to a single disease, for example a patient will get two separate rows with code A for a cataract and code B for impaired vision. A domain expert I am working with wants to see the table displayed by combinations, and has supplied me with a list of pairwise valid combinations.

I am interested in the code having good performance, since this whole thing is wrapped in a function that gets called repeatedly for many thousands of patients. I also want to solve it with data.table, since I am using it heavily in other parts of my code, and I prefer to keep everything consistent. Also, I think that the lookup table with code pairs should be "clean" in the sense of never having a rule twice, even if the order is inverted (such as containing both the A, B and the B, A combinations), but I would prefer a solution that is robust and works even if such repeated rules occur.

MWE test case

To give you an MWE where the codes are replaced with capital letters, I am starting with a table like this:

    code       earliest.year
    A          2001
    B          2002
    C          2003
    D          2004
    E          2005
    F          2006
    G          2007
    H          2008

and a table to look up valid combinations:

  first second
     A      B
     A      C
     C      H
     D      G
     E      I

and want the output to look like this:

   code.combination earliest.year
         A, B, C, H          2001
               D, G          2004
                  E          2005
                  F          2006

My solution

I first tried doing it with vectorization, but got a list-formatted output from apply and couldn't convert the results back to a usable data.table. So I repeated it with a for loop and it worked.

library(magrittr)
library(data.table)

codes <- data.table(code=LETTERS[1:8], earliest.year=c(2001:2008), group=0)
setkey(codes, code)
valid.combinations <- data.frame(first=c("A", "A", "C", "D", "E"), second=c("B", "C", "H", "G", "I"))

# solution A - vectorized
codes.a <- copy(codes)
codes.a <- sapply(codes.a$code, function(current.code) {
  if(codes.a[current.code, group==0]) codes.a <- codes.a[current.code, group:=max(codes.a$group)+1]
  codes.a <- codes.a[code %in% valid.combinations[valid.combinations$first==current.code, "second"], group:=codes.a[current.code, group]]
  return(codes.a[current.code,])
}) %>% t %>% data.table # First, the need for transposing it feels wrong. Second, this gives me a data.table whose columns are all lists, and I get all kinds of errors when trying to work with it.

# Solution B - loop
codes.b <- copy(codes)
for(current.code in codes.b$code) {
  if(codes.b[current.code, group==0]) codes.b[current.code, group:=max(codes.b$group)+1]
  codes.b <- codes.b[code %in% valid.combinations[valid.combinations$first==current.code, "second"], group:=codes.b[current.code, group]]
}

codes.combined <- codes.b[,.(code.combination=paste(code, collapse=", "), earliest.year=min(earliest.year)),by=group]

Questions

How do I get the vectorized solution to work properly (codes.a should be the same as codes.b)?
Generally, vectorization is supposed to have better performance in R. Can I also expect it to give me better performance in this case, or does the casting into lists and re-casting into data.table negate the performance advantages?
Is there a better solution to the problem as a whole, and if yes, what is it?

(I am interested to hear answers to 1 and 2 even if the answer to 3 is "yes")


texts: Add dash between more than two consecutive numbers and comma between other numbers in array

texts:
I have an ordered array of integer values: 10, 11, 12, 13, 15, 16, 19
and I need to write a dash between first and last consecutive values when there are more than two consecutive values (10-13). Between other values I need to write a comma and whitespace.
Output for this input must be 10-13, 15, 16, 19.
I wrote a method that implements this:

class Program
{
    private static string AddDashesBetweenConsecutiveNumbers(int[] orderedArray)
    {
        if (orderedArray.Length == 0 || orderedArray == null)
        {
            return string.Empty;
        }
        var groupedArray = orderedArray.Select((x, i) => new { Difference = i - x, Value = x })
                .GroupBy(x => x.Difference)
                .Select(group => group.Select(a => a.Value))
                .Select(arr => arr.Count() > 2
                            ? $"{arr.First()}-{arr.Last()}"
                            : string.Join(", ", arr));
        return string.Join(", ", groupedArray);
    }
    static void Main(string[] args)
    {
        int[] array = { 10, 11, 12, 13, 15, 16, 19 };

        Console.WriteLine(AddDashesBetweenConsecutiveNumbers(array)); // Output: "10-13, 15, 16, 19"
    }
}

What I wrote seems to work, but this code has some disadvantages, especially in  readability of the LINQ expression. So if you have any ideas how to improve this method or have better or alternative solution, that would be great to find out.


texts:
I wrote the following piece of code and want to hear your opinion, in this snippet I have a vector called aggregateFeaturesForML which has elements of Class with 3 fields: sourceip, key, value. what I want is to collect all the key-value pairs that have the same sourceip and form a nice histogram (for each IP the keys are unique), for that purpose I collect the key-value pairs in a map called histogram and then use its toString function to print a {key=value, key=value} formation. I store the histograms inside another map called aggregator.

Any comments on the readability, writing manner, other stuff will be appritiated.

Definition:

private HashMap<String, HashMap<String, String> > aggregator;
protected Vector<SingleResult> aggregateFeaturesForML = new Vector<SingleResult>(); //Single result has 3 fields: IP, key, value

Code:

        String previousIp = aggregateFeaturesForML.get(0).getSourceip();
        if(!aggregator.containsKey(previousIp))
        {
            aggregator.put(previousIp, new HashMap<String, String>());
        }

        HashMap<String, String> histogram = new HashMap<String, String>();
        for(int iterator=0;iterator<aggregateFeaturesForML.size();iterator++)
        {
            SingleResult sr = aggregateFeaturesForML.get(iterator);
            String ip = sr.getSourceip();

            if(ip != previousIp)
            {
                HashMap<String, String> mapForIP = aggregator.get(previousIp);
                mapForIP.put(key, histogram.toString());
                aggregator.put(previousIp, mapForIP);

                if(!aggregator.containsKey(ip))
                {
                    aggregator.put(ip, new HashMap<String, String>());
                }

                histogram.clear();
                previousIp = ip;
            }

            histogram.put(sr.getKey(), sr.getValue());
        }
        HashMap<String, String> mapForIP = aggregator.get(previousIp);
        mapForIP.put(key, histogram.toString());
        aggregator.put(previousIp, mapForIP);


texts:
I would like to get some code review for my recursive implementation of python flatten array method.

  Write a piece of functioning code that will flatten an array of
  arbitrarily nested arrays of integers into a flat array of integers.
  e.g. [[1,2,[3]],4] -> [1,2,3,4].

I'm particularly looking for some feedback on the following:

Is usage of TypeError exception justified?
Did I miss some valid edge cases in my tests?
Here is my solution including unit tests:

def flatten(input_array):

    result_array = []
    for element in input_array:
        if isinstance(element, int):
            result_array.append(element)
        elif isinstance(element, list):
            result_array += flatten(element)
    return result_array

it has passed all of the following tests

from io import StringIO
import sys

# custom assert function to handle tests
# input: count {List} - keeps track out how many tests pass and how many total
#        in the form of a two item array i.e., [0, 0]
# input: name {String} - describes the test
# input: test {Function} - performs a set of operations and returns a boolean
#        indicating if test passed
# output: {None}
def expect(count, name, test):
    if (count is None or not isinstance(count, list) or len(count) != 2):
        count = [0, 0]
    else:
        count[1] += 1

    result = 'false'
    error_msg = None
    try:
        if test():
            result = ' true'
            count[0] += 1
    except Exception as err:
        error_msg = str(err)

    print('  ' + (str(count[1]) + ')   ') + result + ' : ' + name)
    if error_msg is not None:
        print('       ' + error_msg + '\n')

# code for capturing print output
#
# directions: capture_print function returns a list of all elements that were
#             printed using print with the function that it is given. Note that
#             the function given to capture_print must be fed using lambda.
class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self

    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        sys.stdout = self._stdout

def capture_print(to_run):
    with Capturing() as output:
        pass
    with Capturing(output) as output:  # note the constructor argument
        to_run()
    return output

def test():
    results = flatten([1, [2, 3, [4]], 5, [[6]]])
    return (len(results) == 6 and
            results[0] == 1 and
            results[1] == 2 and
            results[2] == 3 and
            results[3] == 4 and
            results[4] == 5 and
            results[5] == 6)

expect(test_count, 'should return [1,2,3,4,5,6] output for [1, [2, 3, [4]], 5, [[6]]] input', test)

def test():
    results = flatten([])
    return len(results) == 0

expect(test_count, 'should return [] output for [] input', test)

def test():
    results = flatten([1, [2, 3, [4], []], [], 5, [[], [6]]])
    return (len(results) == 6 and
            results[0] == 1 and
            results[1] == 2 and
            results[2] == 3 and
            results[3] == 4 and
            results[4] == 5 and
            results[5] == 6)

expect(test_count, 'should return [1,2,3,4,5,6] output for [1, [2, 3, [4], []], [], 5, [[], [6]]] input (note the empty arrays)', test)

print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')


texts:
The input consists of an integer, N, that determines the no. of km of the cyclist's route and an integer, K, that determines the number of bus tickets the cyclist has.  One bus ticket is valid for only one station (one km).

Following are N numbers determining the strength of the rain in each kilometer. The result (output) should be K numbers, determining the kilometers in which the cyclist should take the bus so that he will be the least wet. The order of the numbers does not matter.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int N, K;
    cin >> N;
    cin >> K;
    vector<int> stip;
    for (int i = 0; i < N; i++) {
        int z;
        cin >> z;
        stip.push_back(z);
    }
    do {
        int max = stip[0];
        for (int i = 0; i < stip.size(); i++) {
            if (stip[i] > max) {
                max = stip[i];
            }

        }

        int pos = find(stip.begin(), stip.end(), max) - stip.begin();
        stip.at(pos) = 0;
        cout << pos + 1 << endl;
        K--;
    } while (K > 0);

    return 0;
}

However, the time and memory limits are 1 second and 64 MiB respectively, and the memory I am currently using is 128 KiB (2.704 seconds and 110 MiB for compilation). How can I make the following program more efficient? I have tried using array instead of vector for the rain strengths, but I cannot make an array of size N (the array size should be constant).


texts: A way to automatically reorder struct fields by their sizes in descending order

texts:
Using constexpr and preprocessor magic it is possible to cook a struct which have a minimal size between all possible sizes, keeping all the data members properly aligned.

#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/repetition/enum.hpp>

#include <utility>

#include <cstddef>

namespace details
{

template< std::size_t /*index*/, typename /*tag*/ >
struct member;

struct pair
{
    std::size_t k, v;
    constexpr bool operator < (pair const & r) const { return r.k < k; }
};

constexpr void swap(pair & l, pair & r) { pair m = r; r = l; l = m; }

template< int N >
constexpr
void qsort(pair (&a)[N], int const l, int const r)
{
    int i = l, j = r;
    pair pivot = a[l + (r - l) / 2];
    while (!(j < i)) {
        while (a[i] < pivot) ++i;
        while (pivot < a[j]) --j;
        if (!(j < i)) {
            swap(a[i], a[j]);
            ++i;
            --j;
        }
    }
    if (l < j) qsort(a, l, j);
    if (i < r) qsort(a, i, r);
}

template< int N >
struct map
{
    pair a[N];
};

template< int N, std::size_t ...indices >
constexpr
map< N > make_map(pair (&a)[N], std::index_sequence< indices... >)
{
    return {{a[indices]...}};
}

template< int N >
constexpr
map< N > qsort(pair (&&a)[N])
{
    if (1 < N) {
        qsort< N >(a, 0, N - 1);
    }
    return make_map< N >(a, std::make_index_sequence< N >{});
}

}

#define GEN0(z, tag, index, type_name) template<> struct member< index, tag > \
{ using type = BOOST_PP_SEQ_HEAD(type_name); type BOOST_PP_SEQ_HEAD(BOOST_PP_SEQ_TAIL(type_name)); };

#define GEN2(z, ignored, index, type_name) {sizeof(BOOST_PP_SEQ_HEAD(type_name)), index},

#define GEN3(z, index, tag) details::member< tag::a.a[index].v, tag >

#define GEN(ns, tag, members) namespace details { \
namespace tags::ns { struct tag; } \
BOOST_PP_SEQ_FOR_EACH_I(GEN0, tags::ns::tag, members) \
namespace tags::ns { \
struct tag \
{ \
    static constexpr auto a = qsort({BOOST_PP_SEQ_FOR_EACH_I(GEN2, %%, members)}); \
}; \
} \
} \
namespace ns { \
using tag = struct : BOOST_PP_ENUM(BOOST_PP_SEQ_SIZE(members), GEN3, details::tags::ns::tag) {};\
}

struct T { char c[3]; };

GEN(user::u2, S, ((char)(c))((int)(i))((T)(t)))

#include <cassert>

int main()
{
    using namespace details;
    void(member< 0, tags::user::u2::S >{}.c);
    void(member< 1, tags::user::u2::S >{}.i);
    static_assert(tags::user::u2::S::a.a[0].k == 4);
    static_assert(tags::user::u2::S::a.a[1].k == 3);
    static_assert(tags::user::u2::S::a.a[2].k == 1);
    user::u2::S s{4, {{'a', 'b', 'c'}}, 'd'};
    assert((void *)&s.i == (void *)&s);
    assert((void *)&s.t < (void *)&s.c);
    static_assert(sizeof(s) == 8);
}

Live example (works for both clang and gcc).

Here is mapping of sizeof to indidces sorted by former, then type alias in desired namespace is created.

As you can see the code is dirty. Don't know what is optimal way to use BOOST_PP_* macro family and how to elaborate a better design (optional namespace, templated, allow to define struct not only in global namespace, etc (obvious things)).


texts:
I have a nested state which is needed to set its state by a key's value:

state = {
    income_source: {
        type: 'text', label_name: 'Income Source', value: '', helper: 'dropdown',
    },
    employment_status: {
        type: 'text', label_name: 'Employment Status', value: '', helper: 'dropdown',
    },

...

I'm getting a huge list from a get_financial_assessment object and the code becomes messy when I tried to setState in componentDidMount():

async componentDidMount() {
    let { get_financial_assessment } = await DAO.getFinancialAssessment()
    if( get_financial_assessment ) {
        const {
            account_turnover,
            cfd_score,
            education_level,
            employment_industry,
            employment_status,
            estimated_worth,
            financial_information_score,
            income_source,
            net_income,
            occupation,
            source_of_wealth,
            total_score,
            trading_score,
        } = get_financial_assessment;

        this.setState(prevState => ({
            anticipated_account_turnover: {...prevState.anticipated_account_turnover, value: account_turnover},
            occupation: {...prevState.occupation, value: cfd_score},
            level_of_education: {...prevState.level_of_education, value: education_level},
            source_of_wealth: {...prevState.source_of_wealth, value: employment_industry},
            net_annual_income: {...prevState.net_annual_income, value: employment_status},
            estimated_net_worth: {...prevState.estimated_net_worth, value: estimated_worth},
            source_of_wealth: {...prevState.source_of_wealth, value: financial_information_score},
        }));
    } else {
        console.log('nope');
    }
}

Any better way? One possible approach might be, once we get the data, we can make an object and setState the object to the state. Would it be the best possible answer?


texts: Different payment details in a common list, to be casted

texts:
I need to be able to access a number of different payment methods in a common list. They can be different methods - credit card, cheque, direct debit etc. The only common attributes are the payment method id and PaymentMethodEnum. I would then be casting the payment method to it's appropriate type to get the extended properties. Is this code arrangement the best way to achieve that?

Update:
I've added the enums. The usage for this is an MVC Website, and these payment details are effectively read only. The website shows different options based on the current payment method, and the other available methods that belong to a customer.

public class PaymentDetailBase
{
    public PaymentDetailBase(string id, PaymentMethodEnum paymentMethod)
    {
        this.Id = id;
        this.PaymentMethod = paymentMethod;
    }

    public string Id { get; }

    public PaymentMethodEnum PaymentMethod { get; }
}

public class CardDetail : PaymentDetailBase
{
    public CardDetail(string id, PaymentMethodEnum paymentMethod, string last4, DateTime expiry, PaymentCardTypeEnum cardType) : base(id, paymentMethod)
    {
        this.Last4 = last4;
        this.Expiry = expiry;
        this.CardType = cardType;
    }

    public string Last4 { get; }

    public DateTime Expiry { get; }

    public PaymentCardTypeEnum CardType { get; }
}

public class DirectDebitDetail : PaymentDetailBase
{
    public DirectDebitDetail(string id, PaymentMethodEnum paymentMethod, string accountName, string routingNumber, string bankAccount, DirectDebitAccountTypeEnum accountType) : base(id, paymentMethod)
    {
        this.AccountName = accountName;
        this.RoutingNumber = routingNumber;
        this.BankAccount = bankAccount;
        this.AccountType = accountType;
    }

    public string AccountName { get; }

    public string RoutingNumber { get; }

    public string BankAccount { get; }

    public DirectDebitAccountTypeEnum AccountType { get; }
}

[Flags]
public enum PaymentMethodEnum
{
    [Description("NONE")]
    None        = 0,

    [Description("Credit Card")]
    CreditCard  = 1 << 0,

    [Description("Direct Debit")]
    DirectDebit = 1 << 1,

    [Description("Check")]
    Cheque      = 1 << 2,

    [Description("Invoice")]
    Invoice     = 1 << 3,

    [Description("Money Order")]
    MoneyOrder  = 1 << 4,

    [Description("Paper Invoice")]
    PaperInvoice = 1 << 5
}

public enum PaymentCardTypeEnum
{
    [Description("Unknown")]
    Unknown,

    [Description("AMEX")]
    Amex,

    [Description("MASTERCARD")]
    MasterCard,

    [Description("DISCOVER")]
    Discover,

    [Description("VISA")]
    Visa
}

public enum BillingFrequencyEnum
{
    [Description("Unknown")]
    Unknown,

    [Description("Annual")]
    Annual,

    [Description("Semi-annual")]
    SemiAnnual,

    [Description("Quarterly")]
    Quarterly,

    [Description("Bi-monthy")]
    BiMonthly,

    [Description("Ten months")]
    TenMonths,

    [Description("Monthly")]
    Monthly
}

public enum DirectDebitAccountTypeEnum
{
    [Description("Unknown")]
    Unknown,

    [Description("Checking Account")]
    Checking,

    [Description("Savings Account")]
    Savings
}


texts: Depth First Search & Breadth First Search implementation

texts:
I've implemented DFS and BFS implementations.  I want to check if the code is readable, contains any issues, and can be improved.

GraphImplementation

package graphs;

import java.util.*;
import graphs.State;
public class GraphImplementation
{
    public void dfs(Node root)
    {
        //Avoid infinite loops
        if(root == null) return;

        System.out.print(root.getVertex() + "\t");
        root.state = State.Visited;

        //for every child
        for(Node n: root.getChild())
        {
            //if childs state is not visited then recurse
            if(n.state == State.Unvisited)
            {
                dfs(n);
            }
        }
    }

    public void bfs(Node root)
    {
        //Since queue is a interface
        Queue<Node> queue = new LinkedList<Node>();

        if(root == null) return;

        root.state = State.Visited;
         //Adds to end of queue
        queue.add(root);

        while(!queue.isEmpty())
        {
            //removes from front of queue
            Node r = queue.remove();
            System.out.print(r.getVertex() + "\t");

            //Visit child first before grandchild
            for(Node n: r.getChild())
            {
                if(n.state == State.Unvisited)
                {
                    queue.add(n);
                    n.state = State.Visited;
                }
            }
        }

    }

    public static Graph createNewGraph()
    {
        Graph g = new Graph();
        Node[] temp = new Node[8];

        temp[0] = new Node("A", 3);
        temp[1] = new Node("B", 3);
        temp[2] = new Node("C", 1);
        temp[3] = new Node("D", 1);
        temp[4] = new Node("E", 1);
        temp[5] = new Node("F", 1);

        temp[0].addChildNode(temp[1]);
        temp[0].addChildNode(temp[2]);
        temp[0].addChildNode(temp[3]);

        temp[1].addChildNode(temp[0]);
        temp[1].addChildNode(temp[4]);
        temp[1].addChildNode(temp[5]);

        temp[2].addChildNode(temp[0]);
        temp[3].addChildNode(temp[0]);
        temp[4].addChildNode(temp[1]);
        temp[5].addChildNode(temp[1]);

        for (int i = 0; i < 7; i++)
        {
            g.addNode(temp[i]);
        }
        return g;
    }

    public static void main(String[] args) {

        Graph gDfs = createNewGraph();
        GraphImplementation s = new GraphImplementation();

        System.out.println("--------------DFS---------------");
        s.dfs(gDfs.getNode()[0]);
        System.out.println();
        System.out.println();
        Graph gBfs = createNewGraph();
        System.out.println("---------------BFS---------------");
        s.bfs(gBfs.getNode()[0]);

    }

}

Graph.java:

package graphs;

public class Graph {

    public int count; // num of vertices
    private Node vertices[];

    public Graph()
    {
        vertices = new Node[8];
        count = 0;
    }

    public void addNode(Node n)
    {
        if(count < 10)
        {
            vertices[count] = n;
            count++;
        }
        else
        {
            System.out.println("graph full");
        }
    }

    public Node[] getNode()
    {
        return vertices;
    }
}

Node.java:

package graphs;
import graphs.State;
public class Node {

    public Node[] child;
    public int childCount;
    private String vertex;
    public State state;

    public Node(String vertex)
    {
        this.vertex = vertex;
    }

    public Node(String vertex, int childlen)
    {
        this.vertex = vertex;
        childCount = 0;
        child = new Node[childlen];
    }

    public void addChildNode(Node adj)
    {
        adj.state = State.Unvisited;
        if(childCount < 30)
        {
            this.child[childCount] = adj;
            childCount++;
        }
    }

    public Node[] getChild()
    {
        return child;
    }

    public String getVertex()
    {
        return vertex;
    }

}

State.java:

package graphs;

public enum State {

    Unvisited,Visiting,Visited;

}


texts:
Find the number occuring only once in a vector.
Given a vector A, containing N pairs (1, 1, 2, 3, 3 ... etc.) and one unique number, find and return the one unique number.

I wrote the following code for this problem.

As I don't have a lot of experience I would be grateful for any kind of feedback regarding my solution so it can be improved.

#include <iostream>
#include <unordered_map>
#include <vector>

uint32_t find_unique(std::vector<uint32_t> &A)
{
    std::unordered_map<uint32_t, uint32_t> seen;

    for (const auto &it : A)
    {
        if (++seen[it] > 1)
        {
            seen.erase(it);
        }
    }

    return seen.begin()->first;
}

int main()
{
    std::vector<uint32_t> v{1, 1, 6, 2, 2, 3, 3, 4, 4, 5, 5};

    std::cout << find_unique(v) << "\n";

    return 0;
}


texts: Function to get current timestamp in node

texts:
I have this code to get the current timestamp so that I can save it as a part of the key in leveldb database.

export default function timestamp() {
  var [seconds, nanoseconds] = process.hrtime()
  return seconds * 1000000000 + nanoseconds
}

I am wondering are there any downsides to use this function. Or are there any better alternatives to get current timestamp in node.


texts:
I'm practicing for a contest by doing some of the older problems, and I was wondering if there are more efficient ways of doing this or if I'm not following any coding conventions. Most importantly, I would like to know if I am using ArrayList correctly in this code, since I learned how to use it off of a brief tutorial on another website.

  Problem S2: Bridge transport

    A train of railway cars attempts to cross a bridge. The length of each car is 10m but their weights can differ. The bridge is 40m long. The cars are numbered starting at 1, going up to N, and they cross the bridge in that order. Your job is to find the largest number of railway cars that can safely cross the bridge.

      Sample Input

      100

      6

      50

      30

      10

      10

      40

      50

      Sample Output

      5

    Explanation for input/output

    The first number indicates the maximum weight that the bridge can hold (100), the second number tells us how many railway cars there are in total (6), and the next N (6) lines are the weights of those respective railway cars (in order, so car 1 has a weight of 50 and so on). The first four railway cars have total weight of 100, which is not greater than what the bridge can hold. When the first railway car leaves, and the next comes on, we have a total weight of $$30 + 10 + 10 + 40 = 90$$ This is also fine because it's not greater than what the bridge can hold. The last four cars would cause the bridge to break, since $$10 + 10 + 40 + 50 = 110$$ which is greater than the bridge can hold. Therefore, to get the maximum number of railway cars, you would need to disengage the last car, and let the first five go.

My solution:

public class BridgeTransport {

public static void main(String args[]) {

    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(
                System.in));

        int maxWeight = Integer.parseInt(input.readLine());
        int totalCars = Integer.parseInt(input.readLine());
        int crossedCars = 0;
        int massOnBridge = 0;

        ArrayList<Integer> cars = new ArrayList<Integer>();
        ArrayList<Integer> carsOnBridge = new ArrayList<Integer>();

        // to get a list of all the weights of cars
        for (int i = 0; i < totalCars; i++) {
            cars.add(Integer.parseInt(input.readLine()));
        }

        for (int i = 0; i < totalCars; i++) {

            // put the cars on the bridge one by one, if there are more than 4
            // cars, then remove the first car
            carsOnBridge.add(cars.get(i));
            if (carsOnBridge.size() > 4) {
                carsOnBridge.remove(0);
            }

            // gets the sum of the masses on the bridge
            for (int j = 0; j < carsOnBridge.size(); j++) {
                massOnBridge += carsOnBridge.get(j);
            }

            // if the masses are less than the max weight for the bridge,
            // then they can successfully cross
            if (massOnBridge <= maxWeight) {
                crossedCars++;
            } else {
                break;
            }

            //reset the sum of the masses on the bridge back to zero
            massOnBridge = 0;

        }

        System.out.println(crossedCars);

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

Am I using ArrayList correctly here?
Are there better ways to accomplish this task?
I feel guilty for resetting the mass on the bridge to 0 each iteration. Is that okay, or is there a better way to do it?


texts:
I'm taking my first programming course so please pardon if questions are too naive. I'm using Python Boto3 module and 'Click' library to build a Command Line Interface that manages EC2 instances. Code:
@click.group()
@cli.group('instances')
def instances():
    pass
@instances.command('list')
@click.option('--project', default=None,help='List instances by project tag, e.g. -project = <project name>')
def list_instances(project):
    'List EC2 instances'
    instances = filter_project_instances(project)
    for i in instances:
            print(', '.join((
            i.id,
            i.instance_type,
        )))
        return

@cli.group('volumes')
#Details of this 'volumes' command are omitted for simplification

Basically, 'Click' allows me to wrap my functions with commands (e.g. instances, volumes), subcommands(list) and option (--project).
Such a command line:
shotty.py instances list --project Valkyrie
can list instances that are tagged with the name 'Valkyrie'
Now, I'm required to add an option to this command line to specify the AWS profile I want to use to log in. The profile was created with 'aws configure --profile [profile name]' command (profile names can be Dan, Kyle, etc.):
shotty.py --profile [profile name] instances list
Initially, I hardcoded the profile name and used session and ec2 as global variables that any other functions can use.
import boto3
import botocore
import click

session = boto3.Session(profile_name='Dan')
ec2 = session.resource('ec2')

Though implementing the above requirement, based on 'Click' documents, I had to do the following to add such a '--profile' option:
@click.group()
@click.option('--profile', default=None,help='Select the AWS profile')
def cli(profile):
   session = boto3.Session(profile_name=profile)
   ec2 = session.resource('ec2')

But now, session and ec2 are not available to other functions any more. This cli() function is like an entry point of the script and is revoked in the main() function:
if __name__ == '__main__':
    cli()

My only approach I could think of was creating a separate function
def session(profile):
        session = boto3.Session(profile_name=profile)
        ec2 = session.resource('ec2')
        return ec2

But now this brings an issue that I have to add profile as a parameter to all other functions, e.g.
def filter_project_instances(project, profile):
        'Filter EC2 instances'
        ec2 = session(profile)
        instances = ec2.instances.all()
        return instances

This means I have to define profile again somehow in this filter_project_instances function.
It does not make much sense to me. Any help would be appreciated!
Update: I had a look at the global keyword before posting but most searches told me that having global variable was mostly a sign of a bad design so I was thinking that I was lacking something pythonically to make it work here


texts: std::ostream wrapper for network logging device

texts:
I want to be able to write logging data out to a network device with the same ease as using std::cout, so I implemented an ostream wrapper. The wrapper uses the C file IO functions to simulate writing to the device. I am looking for feedback on whether or not I have implemented the ostream API correctly.

device_ostream.hpp:

#ifndef DEVICE_OSTREAM_HPP__
#define DEVICE_OSTREAM_HPP__

#include <ostream>

#define BUF_SIZE 100

class device_buffer : public std::streambuf
{
public:
  device_buffer();
  ~device_buffer();
  int overflow(int ch = EOF);
  int sync();

private:
  char buffer_[BUF_SIZE];
  FILE* fp_;

};

class device_ostream : public std::ostream {
public:
  device_ostream() : std::ostream(new device_buffer) {}

  ~device_ostream() {
    delete rdbuf();
  }
};

#endif // DEVICE_OSTREAM_HPP__

device_ostream.cpp:

#include "device_ostream.hpp"

device_buffer::device_buffer() : fp_(0) {
  memset(buffer_, 0, sizeof(buffer_));
  setp(buffer_, buffer_+BUF_SIZE-1);
  fp_=fopen("test.bin","wb");  // simulate our device
}

device_buffer::~device_buffer() {
  if(fp_)
    fclose(fp_); // simulate disconnection from device
}

// ostream fwk notification that buffer is now full
// so write out data now
int device_buffer::overflow(int ch) {
  if(ch != EOF) {
    *pptr() = ch;
    pbump(1);
  }
  return sync();
}

// function to sync up with hardware device.  ie we actually write out data here
int device_buffer::sync() {
  if(fp_) {
    fwrite(buffer_, 1, size_t(pptr() - pbase()), fp_);
    // reset put ptr
    setp(pbase(), epptr());
    return 0;  // success
  }
  else
    return EOF; // return EOF on device failure
}

Code to exercise:

#include "device_ostream.hpp"

int main () {

  device_ostream os;
  os.write("WRITE", 5);

  os << "Hi there, how are you today???" << "\n";
  os << "Number: " << 33 << std::endl;  // std::endl causes sync to be called even if buffer not full yet
  os << "ABCDEFGHIJKLMNOPQRSTUVWXYZ" << std::endl;
  os << "abcdefghijklmnopqrstuvwxyz" << std::endl;
  os << "ABCDEFGHIJKLMNOPQRSTUVWXYZ" << std::endl;

  if(os)
    os << "abcdefghijklmnopqrstuvwxyz" << std::endl;

  return 0;
}


texts: Array view adaptor class for static polymorphism over network header parsing

texts:
Some context: I have some existing code to populate network header structs from istreams. A motivating excerpt:

struct l2_eth_frame {
    using mac_address_t = std::array<std::uint8_t, 6>;
    mac_address_t dest, src;
    std::uint16_t type;
    std::uint32_t vlan;
};

template<typename StreamLike, typename T>
void read_ntoh(StreamLike &is, T &t){
    static_assert(std::is_integral<T>::value, "fixed width integer required");
    is.read(reinterpret_cast<char*>(&t), sizeof(T));

    uint8_t *p = reinterpret_cast<uint8_t*>(&t);
    std::reverse(p, p + sizeof(T));
}

template<class StreamLike>
l2_eth_frame read_l2_eth_frame(StreamLike &i)
{
    l2_eth_frame e;
    i.read(reinterpret_cast<char*>(&e.dest), sizeof(e.dest));
    i.read(reinterpret_cast<char*>(&e.src), sizeof(e.src));
    read_ntoh(i, e.type);
    if(e.type == 0x8100){
        i.read(reinterpret_cast<char*>(&e.vlan), sizeof(e.vlan));
    }
    return e;
}

int main() {
     std::ifstream ifs("test.pcap");
     auto eth = read_l2_eth_frame(ifs);
}

I'm now trying to reuse this code to also be able to generate network structs from live data (e.g. from a raw socket). To achieve this I wrote a simplistic array_view class and also an adaptor class that gives it read and ignore methods (like an istream) so that it can utilise static polymorphism in the read_{header_type} methods.

array_view

#pragma once

#include <cassert>
#include <memory>
#include <array>

template <class T>
class basic_array_view {

private:
    const T* array;
    std::size_t len;

public:
    static constexpr std::size_t npos = -1;

    basic_array_view() noexcept :
        array(nullptr),
        len(0)
    {}

    basic_array_view(const T* array, std::size_t len) noexcept :
        array(array),
        len(len)
    {}

    template<std::size_t N>
    basic_array_view(const T (& a)[N]) noexcept :
        array(std::addressof(a[0])),
        len(N)
    {}

    template<std::size_t N>
    basic_array_view(const std::array<T, N> &a) noexcept :
        array(a.data()),
        len(N)
    {}

    basic_array_view(const basic_array_view &other) = default;
    basic_array_view& operator=(const basic_array_view &other) = default;

    constexpr std::size_t size() const noexcept {
        return len;
    }

    const T& operator[](std::size_t pos) const noexcept {
        assert(pos < len);
        return *(array + pos);
    }

    const T* data() const noexcept {
        assert(len > 0);
        return array;
    }

    basic_array_view<T> subview_right(std::size_t pos=0, std::size_t count=npos){
        assert(pos <= len);
        return { array + pos, std::min(count, len - pos) };
    }
};

using array_view = basic_array_view<char>;

StreamLikeArrayView

#include "array_view.h"

class StreamLikeArrayView {

public:
    array_view av;

    template<class... Args>
    StreamLikeArrayView(Args&&... args) :
        av(std::forward<Args>(args)...) {}

    void read(char *dest, std::size_t len){
        std::copy(av.data(), av.data() + len, dest);
        av = av.subview_right(len, array_view::npos);
    }

    void ignore(std::size_t len){
        av = av.subview_right(len, array_view::npos);
    }
};

usage

std::array<char, 4096> buf;
const auto bytes_read = ::recv(sd, buf.data(), buf.size(), 0); //assume we have set up some raw socket sd
StreamLikeArrayView slav{buf.data(), bytes_read};
const auto eth = read_l2_eth_frame(slav);

I'm particularly interested in a review of the StreamLikeArrayView abstraction, and whether there's some superior way to reuse the parsing code across istreams and arrays.


texts: Object can throw exception on construction, but I don't want it to stop everything

texts:
I have a factory that loads configuration from an xml file, and uses the configuration to be able to create objects of an appropriate type with appropriate settings. My application does a number of different tasks, and I don't want a broken or missing xml file to interfere with the other tasks the application does.

The factory is a Guice-provided dependency, however, if I make the constructor throw an exception, then I will just get a ProvisionException, which could cause unpredictable results or crash the application, neither of which are acceptable.

Currently, I have the factory swallow the exception on creation, and then throw it when the make method is called. Alternatively, I have a makeUnchecked method, if you call the ready() method first. Are there any problems with this approach, or is there potentially a better way to do it?

SSCCE:

public class FooFactory {
    private Exception ex = null;

    @Inject
    public FooFactory(@FooSettings String filename) {
        loadSettings(filename);
    }

    public void loadSettings(String filename) {
        try {
            // stuff
            this.ex = null;
        } catch(Exception e) {
            this.ex = e;
        }
    }

    public Foo make(InputObj input) throws Exception {
        if(ex != null) throw ex;
        makeUnchecked(input);
    }

    public Foo makeUnchecked(InputObj input) {
        if (ex != null) throw new IllegalStateException(ex);
        // factory stuff
    }

    public boolean ready() {
        return ex == null;
    }
}


texts:
Realized I have never implemented heap sort.

So here is my first attempt:

#include <iterator>
#include <tuple>

/*
0   => 1 2
1   => 3 4
2   => 5 6
3   => 7 8
4   => 9 10
5   => 11 12
6   => 13 14

P   => P*2 + 1, P*2 + 2
C   => (C-1)/2
*/

template<typename I>
class HeapSorter
{
    I getParent(I root, I child)
    {
        std::size_t dist = std::distance(root, child);
        return root + (dist - 1) / 2;
    }

    std::tuple<I, I>  getChildren(I root, I parent)
    {
        std::size_t dist = std::distance(root, parent);
        I left  = root + (dist * 2 + 1);
        I right = root + (dist * 2 + 2);
        return {left, right};
    }

    bool swapLargestValueWithRoot(I& root, I left, I right)
    {
        using std::swap;
        if (*root >= *left && *root >= *right) {
            return true;
        }
        I& swapSrc = (*left >= *right) ? left : right;

        swap(*root, *swapSrc);
        root = swapSrc;
        return false;
    }

    void siftDown(I root, I begin, I end)
    {
        I parent    = begin;
        I left;
        I right;
        std::tie(left, right) = getChildren(root, parent);
        while(left < end) {

            if (swapLargestValueWithRoot(parent, left, right == end ? left : right)) {
                break;
            }
            std::tie(left, right) = getChildren(root, parent);
        }
    }

    void heapify(I begin, I end)
    {
        I child   = end - 1;
        if (child == begin) {
            return;
        }
        I parent  = getParent(begin, child);
        for(;parent != begin;--parent) {
            siftDown(begin, parent, end);
        }
        siftDown(begin, begin, end);
    }
    public:
        void operator()(I begin, I end)
        {
            static_assert(std::is_same<typename std::iterator_traits<I>::iterator_category, std::random_access_iterator_tag>::value, "For efficiency; Only support random access Iterator");
            if (begin == end) {
                return;
            }
            heapify(begin, end);
            for(auto loop = end - 1;loop != begin; --loop) {
                std::iter_swap(begin, loop);
                siftDown(begin, begin, loop);
            }
        }
};

template<typename I>
void heapSort(I begin, I end)
{
    HeapSorter<I>  sorter;
    sorter(begin, end);
}

Usage Example:

#include <algorithm>
#include <iostream>

int main()
{
    int data[] = { 5,6,3,8,9,1,4,0,2,3,6,1,7,8,9};

    heapSort(std::begin(data), std::end(data));

    std::copy(std::begin(data), std::end(data),
              std::ostream_iterator<int>(std::cout, ","));
}


texts:
I have this snippet, which computes on two columns, and if I get some increasing pattern then I will consider it a valid Key. How can I optimize this in pandas?
Sample Code
Here there is only one group of track_id. However, I will have many track_id groups, I need to apply the same for all groups.
import pandas as pd
import numpy as np

tid = [5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.,
       5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.]

j = [ 0.,  0.,  0.,  0.,  0.,  1., 52., 53., -1., -1., -1., -1., -1.,
       -1., -1., -1., -1.,  1., -1., -1., -1., -1., -1., -1., -1., -1.,
       -1., -1.]

k = [ 0.,  0.,  0.,  0.,  0., -1., -1., -1., -1., -1., 56., 57., 58.,
       59., 60., 61., 62., 63., -1., -1., -1., -1., -1., -1., -1., -1.,
       -1., -1.]
rules = ['rule_1_start', 'rule_1_end']
data = {'rule_1_start': j, 'rule_1_end': k, 'track_id': tid }
df = pd.DataFrame.from_dict(data)
for r in range(0, len(rules), 2):
    track_groups = df.groupby('track_id')
    for key, item in track_groups:
        _min = np.argmin(item[rules[r]].values)
        _max =  np.argmax(item[rules[r+1]].values)
        if _min < _max:
            print(f"{key}")

The pattern
I am trying to find is something like this. If you see these two columns, there is increasing value pattern. Col 1 has 77, 78,79 and col 2 has 82-91. The pattern should be increasing from col1 to col2 but not vice versa.


texts: Properly structuring a TypeScript library

texts:
This question is more architecture than code related.
Context
I'm currently working on a fairly large web-targeted library, which I'm writing using TypeScript for my own convenience during development. Now that I'm close to wrapping up a release, I'm wondering what the ideal way to structure the library is, to best allow customer consumption. I'll start with the current structure, and will go over what the current methodology is later on.
The library is split up into components, systems, utilities and containers.

Components are custom types like vectors, shapes, etc.
Systems are exported functions that mostly operate on the previously mentioned components.
Utilities are various functions used commonly across the library.
Behaviours are library-specific behaviour types, used for internal functionality.

The goal is to do most of the processing internally, but expose the entirety of types and utilities to the user, to allow maximum customizeability.
Current Method
Currently, I'm using an index-like pattern (if it's even called that?), meaning that for most folders I use a wildcard export of all other files in an index.ts file, for example components/index.ts:
export * from "./componentA";
export * from "./componentB";
// ...

Then, inside the top-level index.ts I import all of the library's parts and build one big object to export.
import * as components from "./components/";
import * as math from "./systems/math";

export default {
    ...components,
    math,
    // others to follow
}

This is to allow users to import the library in node-like environments with ...
import library from "the-library";

// use methods
new library.ComponentA();
library.math.myMathMethod();

... but also to export them into a global using UMDs ...
// "library" is global
new library.ComponentA();
library.math.myMathMethod();

Release Strategy
The library can be used in all browser-like environments, so I'm using tsc to export for Node.js and webpack to bundle it as an UMD.
Questions
I'm curious about the following points:

Is the splitting of the library mentioned at the beginning logical?
Is the "index-pattern" good here? Would namespaces be better?
Is there a better way to export the library's API, that's friendlier for consumption?
Does it make sense to seperate type definitions (not classes, but interfaces and types) into their own directory, without nesting?

I'm probably overthinking this, but I haven't found a good guide on developing a TypeScript library for the web yet, and would like to properly organize everything. I'm thankful for any input!


texts:
This is a C++ program that rotates a point initially located at origin by a given angle A (degree) counterclockwise and L translate its x-coordinate (sum L to it).

Here is my program:

Firstly it reads the number of test cases.
Each test case has 2 real numbers and 1 integer that represents a rotation, translation and how many times the operation of rotate and translate must be applied.

#include <cstdio>
#include <utility>
#include <cmath>

#define gc getchar_unlocked()
inline double getDouble() {
    double v;
    scanf("%lf",&v);
    return v;
}

#define CONST 0.01745329251994329576922 //3.14159265358979323846/180 = 0.01745329251994329576922
std::pair<double, double> rotate(std::pair<double, double> p, double a){
    double rad = a*CONST;
    return std::make_pair(p.first*std::cos(rad) - p.second*std::sin(rad), p.first*std::sin(rad) + p.second*std::cos(rad));
}

int main(void){
    int t = (int) getDouble();

    for (int i = 0; i < t; ++i) {
        double a = getDouble(),l = getDouble();
        int v = (int) getDouble();

        std::pair<double, double> p(0,0);
        while (v--) {
            p = rotate(p, a);
            p.first += l;
         }
        //for cases like 30 1.5 121... the printf just put -0.00
        if(std::abs(p.first) < 0.005)
            p.first = 0;
        if(std::abs(p.second) < 0.005)
            p.second = 0;
        printf("%.2lf %.2lf\n",p.first,p.second);
    }

    return 0;
}

Sample input:

  4
  90 10 1
  90 10 2
  90 10 3
  30 1.5 1000000000

Sample output:

  10.00 0.00
  10.00 10.00
  0.00 10.00
  3.55 3.55

How to make it faster ?


texts: Integer Factorization using the Trial Division Algorithm

texts:
I am trying to factor integers using the trial division algorithm (Wikipedia: http://en.wikipedia.org/wiki/Trial_division).

I reviewed the Wikipedia entry for trial division and multiple other sources but I don't completely understand the trial division algorithm.

I wrote the code below based on my findings and it finds all of the prime factors of a number.

For example, input 20 and you get its prime factors 2 2 5. I would like to know if it can be simplified or better written (I want to stick with the trial division algorithm --- I don't plan on inputting numbers any larger than 9,999)?

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Prime Number Checker</title>


texts:
So my code is done it outputs exactly what it needs to I'm just wondering if it is possible to make this code a lot more simple using objects. If so could someone tell me what I would need member-wise and I will try and implement it. When I tried it got way too complex and it ended up looking easier to just write functions and a whole ton of for loops with if statements.

The purpose of the code is to analyze 2 inputs (base and template) and then see if the template matches any chunks on the base. Also called Gattaca, but A goes to T, C goes to G, and vice versa.

Here is my code:

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

bool AT(char a, char b)  {
    return ((a == 'A' && b == 'T') || (b == 'A' && a == 'T'));
}
bool CG(char a, char b)  {
    return ((a == 'C' && b == 'G') || (b == 'C' && a == 'G'));

}
bool match(char a, char b) {

    return (AT(a, b) || CG(a, b));
}

int main() {
int case_count = 0;
string base;
string temp;
int base_size;
int temp_size;
int count;
cin >> case_count;

for (int i = 0; i < case_count; ++i) {
    cout << "Case " << i << ":\n";
    bool check = false;
    cin >> base;
    cin >> temp;
    base_size = base.size();
    temp_size = temp.size();

    if (base_size < temp_size) {
        cout << "None";
        continue;
    }
    if (base_size == temp_size) {
        count = 0;
        for (int index = 0; index < base_size; ++index) {
            if (!(match(base[index], temp[index]))) {
                cout << "None\n";
                break;
            }
            else
                count++;

        }
        if (count == temp_size) {
            cout << "0\n";
        }
        continue;
    }
    for (int j = 0; j < base_size - (temp_size+1); ++j) {
        count = 0;
        for (int k = j; k < j + temp_size - 1; ++k) {
            if (!(match(base[k], temp[count]))) {
                break;
            }
            else
                count++;
        }
        if (count == temp_size - 1) {
            check = true;
            cout << j << " ";
        }

    }
    if (check == false) {
        cout << "None \n";
    }
    else if (check == true) {
        cout << "\n";

    }
}
return 0;
}

I'm new to C++ programming so the best I can think is using a class to make this look simple. I'm not looking for a full written program just an idea/pseudo code or just the member functions I could use to make this simple.


texts: Python compare every line in file with itself

texts:
I am implementing a statistical program and have created a performance bottleneck and was hoping that I could obtain some help from the community to possibly point me in the direction of optimization.

I am creating a set for each row in a file and finding the intersection of that set by comparing the set data of each row in the same file. I then use the size of that intersection to filter certain sets from the output. The problem is that I have a nested for loop(\$O(n^2)\$) and the standard size of the files incoming into the program are just over 20,000 lines long. I have timed the algorithm and for under 500 lines it runs in about 20 minutes but for the big files it takes about 8 hours to finish.

I have 16GB of RAM at disposal and a significantly quick 4-core Intel i7 processor. I have noticed no significant difference in memory use by copying the list1 and using a second list for comparison instead of opening the file again(maybe this is because I have an SSD?). I thought the with open mechanism reads/writes directly to the HDD which is slower but noticed no difference when using two lists. In fact, the program rarely uses more than 1GB of RAM during operation.

I am hoping that other people have used a certain datatype or maybe better understands multiprocessing in Python and that they might be able to help me speed things up. I appreciate any help and I hope my code isn't too poorly written.

import ast, sys, os, shutil
list1 = []
filterValue = 3
end = 0

# creates output file with filterValue appended to name
with open(arg2 + arg1 + "/filteredSets" + str(filterValue) , "w") as outfile:
    with open(arg2 + arg1 + "/file", "r") as infile:
        # create a list of sets of rows in file
        for row in infile:
            list1.append(set(ast.literal_eval(row)))

            infile.seek(0)
            for row in infile:
                # if file only has one row, no comparisons need to be made
                if not(len(list1) == 1):
                    # get the first set from the list and...
                    set1 = set(ast.literal_eval(row))
                    # ...find the intersection of every other set in the file
                    for i in range(0, len(list1)):
                        # don't compare the set with itself
                        if not(pos == i):
                            set2 = list1[i]
                            set3 = set1.intersection(set2)
                            # if the two sets have less than 3 items in common
                            if(len(set3) < filterValue):
                                # and you've reached the end of the file
                                if(i == len(list1) - 1):
                                    # append the row in outfile
                                    outfile.write(row)
                                    # increase position in infile
                                    pos += 1
                            else:
                                break
                    else:
                        outfile.write(row)

Sample input would be a file with this format:

[userID1, userID2, userID3]
[userID5, userID3, userID9]
[userID10, userID2, userID3, userID1]
[userID8, userID20, userID11, userID1]

The output file if this were the input file would be:

[userID5, userID3, userID9]
[userID8, userID20, userID11, userID1]

...because the two sets removed contained three or more of the same user IDs.


texts: Query performance of a SELECT statement using WHERE and NOT IN

texts:
Can anyone help improve the performance of my query?  When I run it, it locks the database for 5 to 10 minutes.

SELECT
    u.username,
    u.email,
    u.created_at,
    p.firstname,
    p.lastname,
    p.address,
    p.address_2,
    p.city,
    p.country,
    p.state,
    p.zip,
    p.phone,
    p.phone_2,
    u.last_ip,
    u.last_login_at,
    u.auto_login,
    u.registration_page,
    s.product_name
    FROM
    users AS u
        Left Join subscriptions AS s ON u.id = s.user_id
        Left Join profiles AS p ON u.id = p.user_id
    where u.registration_page='Chris_Cleanse' and
        u.id not in (select user_id from goal_sheets) and
        u.id not in(select user_id from sheet_user_popup_not_adam) and
        s.expired=TRUE ORDER BY u.id DESC;

Here is the output of EXPLAIN SELECT:


texts: Change the navigation ul li based on the clicked country

texts:
I'm trying to create a very simple jQuery plugin in the object-oriented way. Now, I'm not sure whether the code I produced is correct and efficient OO programming. The plugin's aim is to change the navigation ul  li based on the clicked country.

jsFiddle

// Widget container
(function($) {
// Widget container plugin
    $.fn.myWidget = function () {
        this.each (function () {
            // Vars
            var item = $ (this);

            // Set events
            item.click (function (e) {
                if (e) e.preventDefault ();
                combine_all(item);
            });
        });
    };

    //uk navigation
    var uk_navigation = '
'
        +'
UK stuff
'
        +'
UK phones
'
        +'
';

    //global navigation
    var global_navigation = '
'
        +'
EU stuff
'
        +'
EU phones
'
        +'
';

    //italy navigation
    var italy_navigation = '
'
        +'
Italy stuff
'
        +'
Italy phones
'
        +'
';

    //germany
    var germany_navigation = '
'
        +'
Germany stuff
'
        +'
Germany phones
'
        +'
';

    this.get_region = function(item){
        my_region = $ (item).attr ('id');
        return my_region;
    };

    this.make_active = function(item){
        item.each(function(){
            item.siblings().removeClass('flag-active');
        });
        item.addClass('flag-active');
    }

    this.update_navigation = function(my_region){
        var old_navigation = $('#navigation').find('ul');
        var new_navigation;
        if(my_region==='europe_flag'){
            new_navigation = global_navigation;
        }else if(my_region==='uk_flag'){
            new_navigation = uk_navigation;
        }else if(my_region==='germany_flag'){
            new_navigation = germany_navigation;
        }else{
            new_navigation = italy_navigation;
        }

        $(old_navigation).hide().html(new_navigation).fadeIn(800);

    };

    this.combine_all = function(item){
        this.get_region (item);
        this.update_navigation(my_region);
        this.make_active(item);
    };

})(jQuery);

// Main
$(function() {
    $('#flags').find('div').myWidget();
});


texts:
Motivation

I typically try to avoid using ! in if-statements, because (to me) it seems easy to overlook. So, I'll usually just spell it out instead, ex: if (done == false) instead of if (!done). While that makes the intention more obvious, it doesn't read very fluidly.

Macro code

For those cases I wrote the following macro:

#define NOT(x) ((x) == false)

The outer parentheses make it possible to use NOT(cond) without additional parentheses in if and make it less error prone:

if NOT(condition) {
    ...
}

Complete example of macro usage

#include <iostream>

#define NOT(x) ((x) == false)

bool successful() {return false;}

int main(int argc, char **argv)
{
    if NOT(successful()) {
        std::cout << "Warning! Self-destruction activated...\n";
    }

    const bool this_is_true = true;

    if NOT(this_is_true) {
        std::cout << "True is false.\n";
    }

    return EXIT_SUCCESS;
}

Concerns

While this works, I have some concerns:

From a best-practices or clean code perspective, is this frowned upon?
How are macros generally viewed, or reported on, in code analysis tools? We are considering employing a system called CAST-AIP for code analysis and, while I am strongly in favor of doing so, I am wondering how many volumes of practice violations my reports are going to be.


texts:
In order to learn a bit more of Prolog, I implemented the echo command for SWI-Prolog.

I want a correct implementation, that is, it satisfies the following requirements:

It makes only one I/O call so that messages will not be garbled if multiple processes write to the same file.
If it is called without arguments, it just prints an empty line (newline).
It does not print any additional spaces. Only spaces between the arguments. No leading space. No trailing space.

Here's  the Prolog code that I came up with.

main(Argv) :-
    echo('', Argv).

echo(S, []) :-
    string_concat(S, '\n', S1),
    write(S1).
echo(S, [Last]) :-
    string_concat(S, Last, S1),
    echo(S1, []).
echo(S, [H|T]) :-
    string_concat(S, H, S1),
    string_concat(S1, ' ', S2),
    echo(S2, T).

I compile and test with the following Makefile (GNU make on Linux):

SHELL:=/bin/bash

.PHONY: all
all: echo

%: %.pl
    swipl -q -t main -o $@ -c $^

.PHONY: clean
clean::
    $(RM) echo

.PHONY: test
test:: echo
    diff (</bin/echo) <(./echo)
    diff (</bin/echo foo) <(./echo foo)
    diff (</bin/echo foo bar) <(./echo foo bar)

It can be run like this: ./echo foo bar.


texts: Animation loop for a sliding puzzle game

texts:
I'm building a "sliding puzzle" game. This is the animation code for when you click a Tile.

This "loop" function is running all the time.

When you click a tile, if it's available to move, I set the "isAnimating" property to true and then set the target left position, and the step (calculated with the starting and end position). The step is just an integer (negative or positive, depending on if the movement is to the left or to the right).

procedure TForm3.Loop(sender: tobject);
var
  i : integer;
begin
  for I := 0 to Tiles.Count - 1 do
  begin
    if(tiles[i].isAnimating) then
    begin
      if(tiles[i].animateProperty = 'left') then
      begin
        if(tiles[i].step > 0) then
        begin
          if tiles[i].left < tiles[i].animateTo - tiles[i].step then
          begin
            tiles[i].Left := tiles[i].Left + tiles[i].step;
          end else begin
            emptyTile.Left := tempX;
            emptyTile.Visible := true;
            tiles[i].isAnimating := false;
            tiles[i].Left := tiles[i].animateTo;
          end;
        end else begin
          if tiles[i].left > tiles[i].animateTo - tiles[i].step then
          begin
            tiles[i].Left := tiles[i].Left + tiles[i].step;
          end else begin
            emptyTile.Left := tempX;
            emptyTile.Visible := true;
            tiles[i].isAnimating := false;
            tiles[i].Left := tiles[i].animateTo;
          end;
        end;
      end else begin
        if(tiles[i].step > 0) then
        begin
          if tiles[i].top < tiles[i].animateTo - tiles[i].step then
          begin
            tiles[i].top := tiles[i].top + tiles[i].step;
          end else begin
            emptyTile.top := tempY;
            emptyTile.Visible := true;
            tiles[i].isAnimating := false;
            tiles[i].top := tiles[i].animateTo;
          end;
        end else begin
          if tiles[i].top > tiles[i].animateTo - tiles[i].step then
          begin
            tiles[i].top := tiles[i].top + tiles[i].step;
          end else begin
            emptyTile.top := tempy;
            emptyTile.Visible := true;
            tiles[i].isAnimating := false;
            tiles[i].top := tiles[i].animateTo;
          end;
        end;
      end;
    end;
  end;
end;

This is how it works:

Go through each tile, and check if the isAnimating property is true;
If it is, check if the animation is a left or top one.
If it's left, check if the step is greater than 0 (move to the right) or less than 0 (move to the left).
If it's less than 0, check if the current left position is lower than the target (animateTo) position.
If it is, then keep animating, if not, then stop the animation (and do a couple more things.

The problem is there's a lot of repeating code but I can't seem to find a way to refactor it so that I avoid repeating myself.

Of course I could use procedures for the same actions but I feel like there's a better way to do it than the way I do it (the animation).


texts:
I'm a student, and most of my lab work includes writing programs (usually .cpp) run them, copy the source code and output to a word file and either mail a pdf to the concerned teacher or submit in print.
(I still don't get the point of submitting a program in print or pdf file, but this is what we're asked to do)

So I wrote a little shell script to help me automate this stuff.

The packages I'm using are:

enscript
ps2pdf
pdftk

Here is the script code:

#!/bin/bash

TARGET='/home/angg/code'
cd $TARGET

find . -type f -name '*.cpp' | while read CPPFILE
do
    TITLE=$(basename $CPPFILE .cpp)

    g++ $TITLE.cpp

    echo $CPPFILE | xargs enscript --color=1 -C -Ecpp -B -t $TITLE -o - | ps2pdf - $TITLE.pdf

    ./a.out > $TITLE.txt && enscript -B $TITLE.txt -o - | ps2pdf - $TITLE.output.pdf

    pdftk $TITLE.pdf $TITLE.output.pdf cat output $TITLE.final.pdf

    rm $TITLE.output.pdf
    rm $TITLE.pdf

done

today=`date +%j-%M`

pdftk *.pdf cat output $today.pdf

I referred this link to convert all cpp files to pdf files, to add output at the end of each cpp file, I created a separate pdf for output of each program and merged the two pdfs together using pdftk
and then removing pdfs not needed now

I need a review regarding the code and if I can shorten it. Also, I'm new to all these packages used and would want to know if there's any redundancy I could avoid.


texts:
I worked on a dynamic programming problem. Here is its link. I have to find the number of ways respecting the constraint that user doesn't go to the Gym for two consecutive days.

public int numWays(int n) {
        int[] DP = new int[n + 1];
        DP[0] = 0;
        DP[1] = 2;
        DP[2] = 3;
        for (int i = 3; i <= n; i++) {
            DP[i] = DP[i - 1] + DP[i - 2];
        }
        return DP[n];
    }

My solution works, however in case of n is very large, my solution won't perform good as its time complexity is exponential. I want to use matrix multiplication like the one for Fibonacci solution but Then I thought that it won't work exactly like that.

How can I improve my solution to have time complexity O(logn)?


texts: Retrieving data to be displayed on a dashboard

texts:
I created a dashboard that uses CanvasJS graphs to show data collected by embedded devices. My problem is to get the last ten documents from a cloudant DB for each one of the devices. I've already made a question to solve this problem by using a view, but looks like it isn't possible to do so.

The function getDeviceList() uses a cloudant view to get the device list and then calls init() to make a query for each one of the devices, then push the data to an object that stores all the device data. The code works with 10 devices, but I don't know if it will for more devices.

function getDeviceList() {
    //first, get the device names
    sensordb.view("name", "countDevice?group=true", function(err, body) {
        if (err) {
            console.log(err);
            return;
        }
        //clear device array before pushing new values
        let devices = [];
        body.rows.forEach(function(id) {
            devices.push(id.key);
        });
        console.log("Device list:" + JSON.stringify(devices));
        init(devices);
    });
}

function init(deviceArray) {
    //for each device, make a cloudant query to retrieve the last ten docs
    for (let i = 0; i < deviceArray.length; i++) {
        sensordb.find({
                "selector": {
                    "deviceID": deviceArray[i],
                    "timestamp": { "$gt": 0 }
                },
                "limit": 10,
                "sort": [{ "timestamp": "desc" }]
            },
            function(err, data) {
                if (err) {
                    console.log("Error while fetching data");
                    console.log(err);
                    return;
                } else {
                    console.log("Done fetching data for " + deviceArray[i]);
                    //revert array for CanvasJS graph
                    data.docs.reverse();

                    var key = deviceArray[i];
                    var obj = {};
                    deviceData[key] = data.docs;
                    // deviceData.push(obj);
                }
            });
    }
}

What could be done better about this code? It looks very costly and unstable, even if it works with 10 devices.

This is how the object that stores all the data looks like:

{"firstDevice":[{first doc},{second doc}... {tenth doc}],
"secondDevice":[{first doc},{second doc}... {tenth doc}],
...
"tenthDevice":[{first doc},{second doc}... {tenth doc}]}

And the device data is accessed using deviceDataArray[deviceName].