texts: Selecting employees and updating a DataGridView

texts:
I've been reading up on different design patterns, mainly MVP and different adaptions of this design pattern / architecture.

Now, I've decided to have a little play with my own ideas, the main outcome separating the user view, from the actual modelling which does all the data changes.

The example is simple, the user is given three radio buttons to select from

Employee One
Employee Two
Employee Three

When these radio buttons are selected it changes a datagrid view with three columns

Firstname
Lastname
Age

My form code has three event driven functions, radioButton_checkChanged.

To start with, I programatically make some new employees: (Ignore the spelling mistake!)

string[] employeeArray = new string[3];
employeeData emplyeeOne = new employeeData("Bob", "Smith", "21");
employeeData emplyeeTwo = new employeeData("John", "Brown", "56");
employeeData emplyeeThree = new employeeData("Andy", "Guy", "28");

 private void employeeOne_CheckedChanged(object sender, EventArgs e)
        {
            updateEmployee(emplyeeOne);
            dataGridView1.Rows.Add(employeeArray);
        }

        private void employeeTwo_CheckedChanged(object sender, EventArgs e)
        {
            updateEmployee(emplyeeTwo);
            dataGridView1.Rows.Add(employeeArray);
        }

        private void employeeThree_CheckedChanged(object sender, EventArgs e)
        {
            updateEmployee(emplyeeThree);
            dataGridView1.Rows.Add(employeeArray);
        }

employeeData class (I've tried to go for encapsulation on this):

public class employeeData
    {
        private string classFirstName { get; set; }
        private string classLastName { get; set; }
        private string classAge { get; set; }

        public employeeData(string firstname, string lastname, string age)
        {
            classFirstName = firstname;
            classLastName = lastname;
            classAge = age;
        }

        public string[] updatePerson()
        {
            string[] data = new string[3];
            data[0] = classFirstName;
            data[1] = classLastName;
            data[2] = classAge;
            return data;
        }
    }

updateEmployee function as seen earlier:

 private void updateEmployee(employeeData who)
    {
        dataGridView1.Rows.Clear();
        dataGridView1.Refresh();
        employeeArray = who.updatePerson();
    }

Am I on to the beginning of any major software design patterns here? Any adaptations and or improvements you can see to make my code a more robust?


texts: Mysql PDO Wrapper that throws Unique Constraint Exception

texts:
The main reasoning behind this PDO wrapper, is that I find myself using unique constraints quite frequently in my designs, and I have if ($ex->errorInfo[1] == 1062) littered throughout my code, and I thought there has to be a better way.
<?php

class PDOMysql extends \PDO {

    public function __construct($dsn, $username = null, $passwd = null, $options = null)
    {
        parent::__construct($dsn, $username, $passwd, $options);
        $this->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
    }

    public function prepareAndExecute($statement, array $params = []): \PDOStatement
    {
        try {
            $stmt = $this->prepare($statement);
            $stmt->execute($params);
            return $stmt;
        } catch (\PDOException $ex) {
            if ($ex->errorInfo[1] == 1062) {
                throw new PDOMysqlUniqueConstraintException($ex);
            } else {
                throw $ex;
            }
        }
    }

}

class PDOMysqlUniqueConstraintException extends \PDOException {

    public function __construct(\PDOException $ex)
    {
        parent::__construct($ex->getMessage(), $ex->getCode(), $ex->getPrevious());
    }

}

// example usage
$user = 'vps';
$pass = 'vps';
$db = new PDOMysql("mysql:host=localhost;dbname=testdb", $user, $pass);

// create table
$sql = "create table if not exists `mytable` (col1 varchar(100) null, constraint idx_u unique (col1) )";
$db->prepareAndExecute($sql);

// insert first row

$params = ['col1' => uniqid('')];
$sql = "insert into mytable (col1) values (:col1)";
$db->prepareAndExecute($sql, $params);

// select row
$sql = "select * from mytable where col1 = :col1";
$stmt = $db->prepareAndExecute($sql, $params);
var_dump($stmt->fetchAll());

// insert duplicate row
try {
    $sql = "insert into mytable (col1) values (:col1)";
    $db->prepareAndExecute($sql, $params);
} catch (\PDOMysqlUniqueConstraintException $ex) {
   die('Unique Constraint Detected');
}


texts:
I've wrote this code and it does what is expected.
However, I'm thinking if there are better ways to write this, specially if is useful to wrap it in a class, or other ways to make it less loosen.
I'll be glad and grateful for any others corrections or suggestions.

interest_list = [0.5,  0.4,  0.3,  0.5,  0.7, 0.4,  -0.2,  -0.5,  0.3,
            0.7,  0.9,  1.0]

def get_unitary(interest_list):
    unit_list = []
    for i in range(len(interest_list)):
        unit_list.append(1+ interest_list[i]/100)
    return unit_list

# I've tested on some lists and found this faster than using reduce()
def prod(uni_list):
    p = 1
    for i in uni_list:
        p *= i
    return p

def get_accrued(prod):
    sub_1 = prod -1
    return sub_1 * 100

accrued = get_accrued(prod(get_unitary(interest_list)))


texts:
I've a User and Notification Entity relationship as:

@Entity
public class Notification implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String notification;
    @Temporal(TemporalType.TIMESTAMP)
    private Date sentDate;

    @ManyToMany(mappedBy = "notifications", cascade = {CascadeType.MERGE})
    private List<User> users;
    // setter - getters methods are omitted
}

and

@Entity
public class User implements Serializable {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private long userId;
        private String userName;
        @Temporal(TemporalType.TIMESTAMP)
            private Date userJoinedAt;
        @ManyToMany(cascade = { CascadeType.PERSIST })
        @JoinTable
        private List<Notification> notifications;
        // setter - getters methods are omitted
}

I've to add messages to a new user record, who should only see the admin sent messages that are sent after his sign-up time.

I've tried:

Approach 1

public void addNotification(Notification notification) throws Exception {
      notification.setNotificationSentDate(new Date());
      notificationService.save(notification);
      List<Notification> notifications = notificationService.getAll();
      List<User> registeredUsers = userService.getAll();
      for (User user : registeredUsers) {
          List<Notification> afterJoinedNotifications = new CopyOnWriteArrayList<Notification>();
          for (Notification savedNotification : notifications) {
              if(user.getUserJoinedAt().before(savedNotification.getNotificationSentDate())){
                  afterJoinedNotifications.add(savedNotification);
                    user.setNotifications(afterJoinedNotifications);
                    userService.save(user);
                  }
          }
      }
  }

Approach 2

public void addNotification(Notification notification) throws Exception {
      notification.setNotificationSentDate(new Date());
      notificationService.save(notification);
      List<Notification> notifications = notificationService.getAll();
      List<User> registeredUsers = userService.getAll();
      for (User user : registeredUsers) {

          for (Notification savedNotification : notifications) {
              if(user.getUserJoinedAt().before(savedNotification.getNotificationSentDate())){
                    user.addNotification(savedNotification);
                    userService.save(user);
                  }
          }
      }
  }

and added a new method to User Entity in the case of Approach 2 as:

public void addNotification(Notification notification) {
        notifications.add(notification);
    }

Note: this app is a very complex system, which is working mostly on real-time notifications. I want to have a best suite approach for that system. Which one I should take from above? Or is there another approach which best suites the scenario?


texts:
I am making a website which should host a lot of PDFs. These PDFs are stored on the HDD. There are DossierIds in the database which correspondent with the folder name. In these folders there is 1 layer of folders and in those layers are the PDFs.

To make the structure clear:

- ABC
    - Dossier1
        -File1.pdf
        -File2.pdf
    - Dossier2
        -File1.pdf
        -File2.pdf
        -File3.pdf
-DEF
    - Dossier1
        -File1.pdf
    - Dossier2
        -File1.pdf
        -File2.pdf
    - Dossier3
        -File1.pdf

The layer which contains the most folders it the root layer (so in the example: ABC, DEF, etc).

I wrote the following code but I'm not sure if it's optimal and if it can handle concurrent access:

public List<Folder> getFolders(String dossierId) {
    //Going right to the correct folder. Not sure how heavy this operation is.
    File file = new File(String.format("%s\\%s",
        propertyService.getProperties().get("folderLocation"), dossierId));

    //Retrieving all folders in that directory.
    File[] directories = file.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return new File(dir, name).isDirectory();
        }
    });

    List<Folder> folders = new ArrayList<>();

    //Going through the folders to check for files
    for (File f : directories) {
        File folder = new File(f.getPath());
        File[] listOfFiles = folder.listFiles();
        List<String> fileNames = new ArrayList<>();
        for (File childfile : listOfFiles) {
            fileNames.add(childfile.getName());
        }

        folders.add(new Folder(f.getName(), fileNames));
    }

    return folders;
}


texts: Deleting temporary rows and columns from 21-sheet workbook

texts:
I've created a VBA code to delete extra rows and columns that were needed for initial calculations but are required to be removed before converting/importing a csv into a database. The code loops through 21 sheets and runs for about 4 minutes. Is this a decent run time or can it be shortened?

Public Sub Test()

Dim xWs As Worksheet
Set xWs = ActiveSheet
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long

'SETTING DEPENDENT VALUES TO ABSOLUTE VALUES============================='

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    xWs.DisplayPageBreaks = False
    xWs.UsedRange.Value = xWs.UsedRange.Value
Next

'DELETING ROWS BASED ON COLUMN B VALUES=================================='

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    xWs.DisplayPageBreaks = False
    Firstrow = xWs.UsedRange.Cells(1).Row
    Lastrow = xWs.UsedRange.Rows(xWs.UsedRange.Rows.count).Row
    For Lrow = Lastrow To Firstrow Step -1
        With xWs.Cells(Lrow, "B")
            If Not IsError(.Value) Then
                If .Value = "0" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
Next

'DELETING DUPLICATE IP ADDRESSES=========================================='

With Sheets("IP-Unassigned")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Firstrow = .UsedRange.Cells(1).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.count).Row
    For Lrow = Lastrow To Firstrow Step -1
        With .Cells(Lrow, "H")
            If Not IsError(.Value) Then
                If .Value = "1" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
End With

'DELETING EXTRA COLUMNS========================================================'

With Sheets("IP-FSW")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-2070")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-MNTR")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-BBS")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-DET")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-TTR")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-CCTV")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-Unassigned")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(16).EntireColumn.Delete
    Columns(15).EntireColumn.Delete
    Columns(14).EntireColumn.Delete
    Columns(13).EntireColumn.Delete
    Columns(12).EntireColumn.Delete
    Columns(11).EntireColumn.Delete
    Columns(10).EntireColumn.Delete
    Columns(9).EntireColumn.Delete
    Columns(8).EntireColumn.Delete
End With

'=========================================================================='

End Sub


texts: Neatest way of including a header and footer on every page

texts:
I just got into Object Oriented Programming, and it made me think about certain code how I can make them as efficient as possible.

Right now I am just including my header and footer like the following:

PHP

require_once 'core/init.php';

require_once 'includes/header.php';

//Big block of content goes here

require_once 'includes/footer.php';

I wonder if this is the neatest / most efficient way of doing that?


texts: Random value generation for uncertainty analysis

texts:
I am a beginner in coding, writing my first bigger C++ project (aircraft initial sizing program). This code should be able to analyze the design in a probabilistic manner by using Monte Carlo Simulation. Hence, I have to generate random values for several independent random variables.

As I want to learn, how to program good code, I would be thankful for reviewing the simplified 'random number generation'-part of my code:

settings.h

#ifndef SETTINGS_H
#define SETTINGS_H

#include <iostream>
#include <string>
#include <vector>

class settings
{

public:
    struct distInput
    {
        std::string distName;
        double paramA;
        double paramB;
        double paramC;
    };

    std::vector<distInput> distInputs;

    settings();
};

settings.cpp

#include "settings.h"

settings::settings()
{
    //Read input from file, here simplified
    distInput input1 =
    {
        "Normal Distribution",
        100.,
        1.,
        0.
    };

    distInput input2 =
    {
        "Triangular Distribution",
        80.,
        100.,
        109.
    };

    distInputs.push_back(input1);
    distInputs.push_back(input2);
}
//here are more functions

uncertainty.h

#ifndef UNCERTAINTY_H
#define UNCERTAINTY_H

#include <iostream>
#include <string>
#include <random>
#include <vector>

class uncertainty
{
public:
    void generateRN();

    std::vector<std::mt19937_64> randomNumberGenerators;
    std::vector<std::vector<double>> randomNumbers;
    settings *mySettingsPt;
    std::vector<settings::distInput> *inputData;

    uncertainty(settings &mySettings, double numbersRV);
};

uncertainty.cpp

#include "uncertainty.h

uncertainty::uncertainty(settings &mySettings, double numbersRV)
    :
    mySettingsPt(&mySettings),
    inputData(&mySettingsPt->distInputs)
{
    for(unsigned int i = 0; i < numbersRV; ++i)
    {
        std::random_device rd;
        std::mt19937_64 mt_tmp(rd());
        randomNumberGenerators.push_back(mt_tmp);
        randomNumbers.resize(numbersRV);
    }
}

void uncertainty::generateRN()
{
    unsigned int numRV = inputData->size();

    for(unsigned int i = 0; i < numRV; ++i)
    {
        std::string name = inputData->at(i).distName;
        double a = inputData->at(i).paramA;
        double b = inputData->at(i).paramB;
        double c = inputData->at(i).paramC;

        if(name == "Normal Distribution")
        {
            std::normal_distribution<> dist(a, b);
            randomNumbers.at(i).push_back(dist(randomNumberGenerators.at(i)));
        }
        else if(name == "Triangular Distribution")
        {
            std::uniform_real_distribution<> dist(0, 1);
            double F = (b - a) / (c - a);
            double U = dist(randomNumberGenerators.at(i));
            if (U <= F)
                randomNumbers.at(i).push_back(a + sqrt(U * (c - a) * (b - a)));
            else
                randomNumbers.at(i).push_back(c - sqrt((1 - U) * (c - a) * (c - b)));
        }
    }
};

main.cpp

#include "settings.h"
#include "uncertainty.h"
#include <iostream>
#include <string>
#include <vector>
#include <random>

int main()
{
    // Initialize objects for computation
    settings mySettings;
    uncertainty myUncertainty(mySettings, mySettings.distInputs.size());

    // Start Computation
    for(unsigned int i = 0; i < 100; ++i)
    {
        myUncertainty.generateRN();
        // Other code, that uses the random values
    }
}

The code works fine, but I never had somebody reviewing my code skills. Improvement suggestions of any kind (How to structure .cpp and h. files, how to write that code more efficient, use of data structures and objects, etc.) are very welcome!


texts: PHP code to update database record sort order

texts:
I wrote this PHP method to update database record sort order after moving a specific record with jQuery UI Sortable in a website. That sort order is stored in a column named order.

I'd like to know if this is SOLID approved or should I split it in more methods, maybe separating the logic that searches for previous, current and next record? I don't know, I'm open for suggestions, thanks!

This code is meant for PHP 5.* and Zend Framework 2.

/**
 * Update records sort order inside a specific Job, after a specific row is moved with jQuery Sortable
 *
 * @param  integer $idJob
 * @param  integer $idPrevious id of previous record after moving $current
 * @param  integer $idCurrent  id of moved record
 * @param  integer $idNext     id of next record after moving $current
 *
 * @return void
 */
public function sort($idJob, $idPrevious, $idCurrent, $idNext)
{
    if (!$idPrevious && !$idNext) {
        throw new BadMethodCallException('Didn\'t send previous neither next record');
    }

    if (!$idCurrent) {
        throw new BadMethodCallException('Didn\'t send moved record');
    }

    $currentEntity = $this->findById($idCurrent);

    if (!$currentEntity) {
        throw new DomainException('Moved record not found');
    }

    $currentOrder    = $currentEntity->getOrder();
    $currentWentDown = false;
    $currentWentUp   = false;

    // Searches for previous record after moving and identifies if the moved record went down
    if ($idPrevious) {
        $previousEntity = $this->findById($idPrevious);

        if (!$previousEntity) {
            throw new DomainException('Previous record not found');
        }

        $currentWentDown = $previousEntity->getOrder() > $currentOrder;
    }

    // Searches for next record after moving and identifies if the moved record went up
    if ($idNext) {
        $nextEntity = $this->findById($idNext);

        if (!$nextEntity) {
            throw new DomainException('Next record not found');
        }

        $currentWentUp = $nextEntity->getOrder() < $currentOrder;
    }

    // logic to update only the affected records instead of the entire list
    if ($currentWentDown) {
        $currentNewOrder = $previousEntity->getOrder();

        // update all affected records except the moved one
        $this->updateWith(
            ['order' => new Predicate\Expression('order - 1')],
            [
                'id_campanha' => $idJob,
                new Predicate\Between('order', $currentOrder + 1, $previousEntity->getOrder())
            ]
        );

        // update moved record
        $currentEntity->setOrder($currentNewOrder);
        $this->update($currentEntity);

    } elseif ($currentWentUp) {
        $currentNewOrder = $nextEntity->getOrder();

        // update all affected records except the moved one
        $this->updateWith(
            ['order' => new Predicate\Expression('order + 1')],
            [
                'id_campanha' => $idJob,
                new Predicate\Between('order', $nextEntity->getOrder(), $currentOrder - 1)
            ]
        );

        // update moved record
        $currentEntity->setOrder($currentNewOrder);
        $this->update($currentEntity);
    }
}

Briefly explaining about things

The class in the example above is a Model, all Models extends AbstractModel
findById method is inside AbstractModel, and if not found returns false or if found returns a Entity that is a class used to map a table, so each database column is a property
*Entity->getOrder() returns integer


texts: Which one is more readable for mutually exclusive but mandatory command line parameters validation?

texts:
I have a small validation code that needs to make sure that exactly one of two parameter is
set

I consider two options, the "Naive" that has some repetitions and might look "clumsy" but is very clear, and a second that is a bit more "DRY" but I'm not sure it's as readable / convincing in it's correctness.

Option one

if(param1==null && param2==null){
  throw new RuntimeException("Either param1 or param2 must be specified");
}

if(param1!=null && param2!=null){
  throw new RuntimeException("Only one of param1 or param2 must be specified");
}

if(param1!=null){
  //do something with param1
}
if(param2!=null){
  //do something with param2
}

Option two

if(param1!=null){
  if(param2!=null){
    //only runs if both are not null
    throw new RuntimeException("Only one of param1 or param2 must be specified");
  }
  //do something with param1
} else if(param2!=null){
  //do something with param2
} else{
  //only runs if both are null
  throw new RuntimeException("Either param1 or param2 must be specified");
}

Which one is more readable? which one would you keep? do you see any issue with Option 2?

Edit:

Based on feedback, I think there is a bit nicer option

Option three

boolean isParam1Valid = param1!=null;
boolean isParam2Valid = param2!=null;

if(isParam1Valid == isParam2Valid ){ //e.g. either both are null or both are not null
  throw new RuntimeException("param1 or param2 must be specified exactly once");
}

if(isParam1Valid){
  //do something with param1
}

if(isParam2Valid){
  //do something with param2
}

Option four shorter, but a bit less readable IMHO than option three (one needs to go up and read the code to understand why author is so sure that the else block means that param2 is valid

boolean isParam1Valid = param1!=null;
boolean isParam2Valid = param2!=null;

if(isParam1Valid == isParam2Valid ){ //e.g. either both are null or both are not null
  throw new RuntimeException("param1 or param2 must be specified exactly once");
}

if(isParam1Valid){
  //do something with param1
}else{ //must be true, as isParam1Valid is false, and they are not equal
  //do something with param2
}


texts:
I want to find the first and second highest number in an array. I could come up with one solution, but I want to know the optimum solution to do the same. Can someone help me with some alternative solution to this?

int main()
{

    int arr[10] = {0,1,2,13,4,5,9,8,11,6};
    int first = arr[0];
    int second = arr[0];
    int i;

    for(i=0;i<10;i++)
    {
        if(first < arr[i])
        {
            second = first;
            first = arr[i];
        }
        else if(second < arr[i])
        {
            second = arr[i];
        }

    }

    printf("First = %d\n", first);
    printf("Second = %d\n", second);

    return 0;
}

Output:

First = 13
Second = 11


texts:
I've written this code to read CSV files written in a specific format. I would like to gather some feedback on where it could be improved. I'm trying to get into the Test-Driven-Development ideology so any way I could make the code play better with unit tests would be of particular interest to me.

An aspect I am not overly pleased with is the switch statement in the MatchHeaders function. I did try using enum representing the property names but I ran into an issue with not having constant value, and frankly it did not make the code read cleaner.

I am more interested in being pointed at what to look at and where, rather than being given code.

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string FullAddress { get; set; }
    public string PostCode { get; set; }
    public string TelephoneNumber { get; set; }
    public string EmailAddress { get; set; }
}

public interface ICsvReader
{
    List<Contact> ParseCsv(string filePath);
}

public class Reader : ICsvReader
{
    public List<Contact> ParseCsv(string filePath)
    {
        List<String[]> rows = GetRows(filePath);
        string[] headers = rows[0];

        return MakeContacts(headers, rows);
    }

    private List<String[]> GetRows(string filePath)
    {
        List<Contact> users = new List<Contact>();
        string[] lines = File.ReadAllLines(filePath);
        var csv = from line in lines
                    select (line.Split(',')).ToArray();

        return csv.ToList();
    }

    private List<Contact> MakeContacts(string[] headers, List<string[]> rows)
    {
        List<Contact> contacts = new List<Contact>();
        // If we didn't know the headers we could contain values with their properties in a collection
        // List<List<Dictionary<string, object>>> csv = new List<List<Dictionary<string, object>>>();
        for (int i = 1; i < rows.Count; i++)
        {
            string[] row = rows[i];
            Contact contact = new Contact();
            for (int e = 0; e < row.Length; e++)
            {
                string header = headers[e];
                string value  = row[e];

                contact = MatchHeader(contact, header, value);
            }
            contacts.Add(contact);
        }
        return contacts;
    }

    private Contact MatchHeader(Contact user, string header, string value)
    {
        switch (header.ToLowerInvariant())
        {
            case "firstname":
                user.FirstName = value;
                break;
            case "lastname":
                user.LastName = value;
                break;
            case "dateofbirth":
                user.DateOfBirth = DateTime.Parse(value);
                break;
            case "fulladdress":
                user.FullAddress = value;
                break;
            case "postcode":
                user.PostCode = value;
                break;
            case "telephonenumber":
                user.TelephoneNumber = value;
                break;
            case "emailaddress":
                user.EmailAddress = value;
                break;
            default:
                break;
        }
        return user;
    }
}


texts: Delete order's details' line without changing page using AJAX

texts:
Following a teacher's JavaScript code I intend to delete order's lines with AJAX.

I have tried the code below and it allows the user to delete line by line but for example for the last line it won't delete it.

Function to display order's details:

    public static function showOrderDetails($id){
    $res=DB::execute_sql('select id,idbebida, unidades, pvp from lineaspedido where idpedido=?', array($id));

    if($res){
        $res -> setFetchMode(PDO::FETCH_NAMED);
        $first=true;
        echo '

';
        foreach ($res as $table_row) {
            if($first){ //HEADERS

                foreach ($table_row as $row_index => $row_data) { // titulos campos
                    if($first){ //TO NOT DISPLAY ID
                        $first=false;
                        continue;
                    }
                    echo "$row_index	";
                }

            }
            echo '
';

            $first=true;
            foreach ($table_row as $row_data) { // DATA
                if ($first){
                    $idLinea=$row_data;
                    $first=false;
                    echo "
";
                } else{
                    echo "$row_data	";
                }
            }

            echo "<button onclick=\"deleteLineaPedido($idLinea )\">Borrar</button>	";
           echo "
";
        }
        echo '
';
    }
}

PHP OBJECT to manage JSON:

    <?php
$res = new stdClass();
$res->deleted=false; //Attribute DELETED default false
$res->message=''; //Error message
try{
    $datoscrudos = file_get_contents("php://input"); //READ
    $datos = json_decode($datoscrudos);
    $db = new PDO("sqlite:./datos.db");
    $db->exec('PRAGMA foreign_keys = ON;'); //KEYS
    $sql=$db->prepare('delete FROM lineaspedido WHERE idpedido=?;');
    if($sql){
        $sql->execute(array($datos->id));
        if($sql->rowCount()>0){ //NUMBER OF ROWS AFFECTED
           $res->deleted=true; //WHATEVER have been deleted is refreshed
        }
    }
}catch(Exception $e){
   $res->message=$e->getMessage();

header('Content-type: application/json');
echo json_encode($res);

JS function to delete:

function deleteLineaPedido(idLinea){
if(!confirm("Desea borrar la linea de pedido: '"+idLinea+"'")){
    return;
}
var ajax= new XMLHttpRequest();
ajax.onreadystatechange=function(){
    if(this.readyState == 4 && this.status == 200) {
        var res= JSON.parse(this.responseText); //RESULT in JSON
        if(res.deleted === true){
            var fila=document.querySelector('#fila'+idLinea); //We choose the first and unique row which has whatever ID needed.
            fila.parentNode.removeChild(fila); //We delete the previous row firstly going to its parent node and then deattaching it.
        }
    }
};
ajax.open("post","borrar_linea_Pedido.php",true);
ajax.setRequestHeader("Content-Type","application/json;charset=UTF-8");
ajax.send(JSON.stringify({"id":idLinea})); //Formato {id:identificador de registro a borrar}

Is there a simpler way to achieve this?

PD: The table used 'lieanspedidos' has the following structure:

id          Numeric identifier of every row of order's details
idpedido    Numeric order identifier
idbebida    Numeric drink identifier
unidades    How many drinks have been inserted into that order's row.
PVP         Each drink's price per unit.


texts: Is this a good structure for my website?

texts:
I have been building a site using php and would like advice to improve the structure of my site and the best way to lay out my code for SEO. I'm also a little concerned about echoing large chunks of HTML and how SEO will work with my structure.

Ok here's my structure...

My site contains many pages with only the body content changing for each page. So I have created template functions in PHP for echoing HTML. I use $_GET['page_id'] in a switch statement to determine what page content to load. .

my pages look something like this....

Header();                            //echo header HTML

 switch ($_GET['page_id'])            //Echo body content
 {
   default: homePage(); break;
   case 1:  servicesPage(); break;
   case 2:  galleryPage(); break;
   case 3:  contactPage(); break;
 }

 Footer();                           //Echo footer HTML

And my php functions look like this

 function header() {
      echo "

Header

";
 }

 function footer() {
      echo "

Header

";
}

 function homePage()
 {
    echo "

 Home

 Home1

 Home1

This is home page

";

 }

I'm really looking for any pointers to improve my code but my main concerns are...

Is it ok to echo large chucks of HTML like that from php? especially with my site growing?

Does Google crawler bot still crawl my site ok using $_GET['page_id'] for all my pages?

P.S I'm new here, so sorry if any code formatting is a little off!


texts:
I am trying to solve this LeetCode question:

  Given a non-empty string s and a dictionary wordDict containing a list
  of non-empty words, add spaces in s to construct a sentence where each
  word is a valid dictionary word. Return all such possible sentences.

  Note:

  The same word in the dictionary may be reused multiple times in the
  segmentation. You may assume the dictionary does not contain duplicate
  words.

I have a solution that works correctly but exceeds python's memory limit on large inputs.

Note that the Solution class is required by LeetCode's interface.

from collections import defaultdict
class Solution:
    def wordBreak(self, s, wordDict):
        cache = defaultdict(list)
        word_dict = set(wordDict)
        def partition(s):
            if s in cache:
                return cache[s]
            res = []
            if s in word_dict:
                res.append(s)
            for i in range(1, len(s)):
                words = partition(s[i:])
                k = s[:i]
                if k in word_dict:
                    for word in words:
                        res.append(k +" "+word)

            cache[s] = res
            return res
        return partition(s)

How do I optimize it in terms of space complexity?

Please refrain from commenting that the function doesn't have to be a method bound to the class instance. It cannot be changed as it is the template used to run the solution.


texts: Encapsulating common Try-Catch code. Is this a known pattern? Is it good or bad?

texts:
In an effort to reduce code duplication, I often use and have used this style to capture handling of exceptions on a boundary of an application:
Given the following extension methods:

public static class FuncExtenstion
{
    [DebuggerStepThrough]
    public static Action<A> AsAction<A, T>(this Func<A, T> f)
    {
        return (a) => f(a);
    }

    [DebuggerStepThrough]
    public static Func<bool> AsFunc(this Action a)
    {
        return () => { a(); return true; };
    }
}

public static class IlogExtensions
{
    public static TResult TryCatchLogThrow<TResult>(this ILog logger, Func<TResult> f)
    {
        try
        {
            return f();
        }
        catch (Exception ex)
        {
            logger.Error(ex.Message, ex);
            throw;
        }
    }

    public static void TryCatchLogThrow(this ILog logger, Action f)
    {
        logger.TryCatchLogThrow(f.AsFunc());
    }

    public static TResult TryCatchLog<TResult>(this ILog logger, Func<TResult> f)
    {
        try
        {
            return f();
        }
        catch (Exception ex)
        {
            logger.Error(ex.Message, ex);
            return default(TResult);
        }
    }

    public static void TryCatchLog(this ILog logger, Action f)
    {
        logger.TryCatchLog(f.AsFunc());
    }
}

In the code I will use these (e.g. in a Windows/WCF/Web Service) to either silently catch the error and let the code continue to run (used in a polling service) or to at least log the error locally on the server and then rethrow the full exception again.
I have used several other variations where the exception gets wrapped in more 'user friendly' exceptions or in WCF FaultExceptions

So typically this code is used as follows:

    Response ISomeService.SomeOperation(Request request)
    {
        return _logger.TryCatchLogThrow(() => _domainImplementation.SomeOperation(request));
    }

    OtherResponse ISomeService.OtherOperation(OtherRequest request)
    {
        return _logger.TryCatchLogThrow(() => _domainImplementation.OtherOperation(request));
    }

I have not seen this style of code anywhere else. So I was wondering if there is an other pattern I should be using, or if this is ok to use.


texts: vectorize 2D gradient with spatially varying bins

texts:
The following code takes in some values ssh and solves the equations for the geostrophic motion (slide 8 here).

The main part of the code is the computation of the partial derivatives of ssh. In particular the discrete differentials have to be multiplied by a factor that depends on y. This can be easily done with a linear code:

close all
clearvars
clc

%define grid
x=linspace(120,145,20);
y=linspace(30,45,20);
[x, y]=meshgrid(x,y);
x = x';
y = y';

%define constants
R = 6371000; % Earth radius

g=9.806-.5*(9.832-9.780)*cos(2*y*pi/180); % gravity

omega = 2*pi/(24*60*60); % Earth rotation angle velocity [s]
f = 2*omega*sind(y); %Coriolis force coefficients

%data
ssh = (exp(-((x-130).^2/20)).*(exp(-(y-35).^2/7)))*1e6; % Sea surface height in each point

%Calculate geostrophic current
u=zeros(size(ssh));
v=zeros(size(ssh));
for i=2:size(x,1)-1
    for j=2:size(y,2)-1
        dx(i,j) = (x(i+1,j)-x(i-1,j)) *(R*cosd(y(i,j))*pi/180);
        dy(i,j) = (y(i,j+1)-y(i,j-1)) *(R*pi/180);

        u(i,j) = -g(i,j)/f(i,j) *(ssh(i,j+1)-ssh(i,j-1)) /dy(i,j);
        v(i,j) =  g(i,j)/f(i,j) *(ssh(i+1,j)-ssh(i-1,j)) /dx(i,j);
    end
end

figure
pcolor(x,y,ssh)
shading flat
hold on
quiver(x,y,u,v,2,'k')
title('Geostrophic current [m/s]','fontweight','bold')
xlabel('longitude','fontweight','bold')
ylabel('latitude','fontweight','bold')
set(gcf,'color','w')

Output:

However, I am having problems to vectorize the code.

I tried to use the gradient function in the following way:

%%%%===== vectorized code =====%%%%

dx2 = x  .*(R*cosd(y)*pi/180); %x-position matrix
dy2 = y  *(R*pi/180); %y-position matrix

[dsshdy,dsshdx] = gradient(ssh, dy2,dx2);

u2 = -g./f .*dsshdy;
v2 =  g./f .*dsshdx;

figure;hold on
pcolor(x,y, ssh)
shading flat
hold on
quiver(x,y, u2,v2, 2,'k')
title('Geostrophic current 2','fontweight','bold')
xlabel('longitude','fontweight','bold')
ylabel('latitude','fontweight','bold')
set(gcf,'color','w')

Output:

However, this fail (I think) because the gradient function does not take as inputs matrices of spacing values. As a consequence, the code somehow computes differentials that are way too big and the arrows are not visibile.

How can I vectorize such a problem without re-introducing a for loop to take into account the variation of dx with y?


texts:
I'm trying to work HTML5 canvas video into a React application while making the code as clean as possible. What kind of improvements should be made to improve the performance utilizing the React to its fullest potential?

import React, { Component } from 'react';
import './App.css';
import video from './video.mp4';
import watermark from './watermark.png';

class App extends Component {
constructor() {
    super();
    this.state = {};
}

componentDidMount() {

const canvas = document.createElement('canvas');
canvas.width = 1280;
canvas.height = 720;
const context = canvas.getContext('2d');
context.drawImage(document.querySelector('video'), 0, 0, 720, 1280);
                    context.drawImage(
                        document.querySelector('.watermark'),
                        parseInt(document.querySelector('select').value),
                        parseInt(document.querySelector('select').value)
                    );
                    if (document.querySelector('input[name=live]').checked) {
                        this.setState({ image: canvas.toDataURL() });
                    }

}

render() {
    const range = [];
    for (let i = 0; i < 1280; i++) {
        range.push(i);
    }

    return (

            <video  src={video} controls />

                Watermark X
                <select className="positionX">
                    {range.map(i => (
                        <option key={i}>{i}</option>
                    ))} </select>

                Watermark Y
                <select className="positionY">
                    {range.map(i => (
                        <option key={i}>{i}</option>
                    ))} </select>

                Live
                <input type="checkbox" name="live" />

                <button className = "watermarkButton watermarkSubmit"
                    onClick={() => {
                        const canvas = document.createElement('canvas');
                        canvas.width = 1280;
                        canvas.height = 720;
                        const context = canvas.getContext('2d');
                        context.drawImage(document.querySelector('video'), 0, 0, 1280, 720);
                        context.drawImage(
                            document.querySelector('.watermark'),
                            parseInt(document.querySelector('.positionX').value),
                            parseInt(document.querySelector('.positionY').value)
                        );
                        this.setState({ image: canvas.toDataURL() });
                    }}> Watermark! </button>

    );
                }

            }

export default App;


texts:
I'm attempting to write an animation system on top of SFML, and I've come up with a design where I can wrap sf::Drawable objects into a RenderComponent class, and the RenderComponent class can be given an Animation object at any time, which will overwrite a previous animation if one exists. Here is what I'm looking for.

Am I using the std::unique_ptr correctly/optimally?
Should I be using a pointer to store the Animation?
Is my method of settings the animation (with a variadic template) too complicated, and is there a better way?
I would normally separate the code into header and implementation, but for the brevity, I am uploading it in pure headers. Ignore that please.
Any general advice.

Here is the code:

Animation base class

class Animation {
    typedef std::chrono::high_resolution_clock hrc;

private:

    std::chrono::time_point<hrc> m_now;

protected:

    unsigned int m_us;      // us for microseconds
    unsigned int m_endUs;

    void UpdateTime() {
        auto end = hrc::now();
        auto diff = end - m_now;
        m_now = end;
        auto msDuration = std::chrono::duration_cast<std::chrono::microseconds>(diff);
        m_us += (unsigned int)msDuration.count();
    }

public:

    Animation() {
        m_us = 0;
        m_now = hrc::now();
    }

    bool finished() {
        return m_endUs <= m_us;
    }

    virtual bool Update(sf::Sprite& spr) = 0;

};

Animation child class

class FadeIn : public Animation {

public:

    FadeIn(int ms) {
        m_endUs = ms * 1000;
    }

    // Updates the sprite based on the timeline, and returns if the animation is over
    virtual bool Update(sf::Sprite& spr) {
        UpdateTime();
        if (finished()) return true;

        sf::Color color = spr.getColor();
        color.a = (int)((float)m_us / m_endUs * 255);
        spr.setColor(color);
        return false;
    }

};

Render Component

class RenderComponent {

private:

    sf::Texture m_texDefault;
    std::unique_ptr<Animation> m_animationPtr;

public:

    RenderComponent() { }
    RenderComponent(sf::Drawable* element, sf::Vector2u size) {
        sf::RenderTexture rt;
        rt.create((unsigned int)size.x, (unsigned int)size.y);
        rt.draw(*element);
        m_texDefault = rt.getTexture();
    }

    template <typename T, typename... Args>
    void SetAnimation(Args... args) {
        m_animationPtr = std::make_unique<T>(args...);
    }

    void draw(sf::RenderTarget* target) {
        sf::Sprite sprite;
        sprite.setTexture(m_texDefault);

        // Handle animation and set pointer to null if done
        if (m_animationPtr) {
            if (m_animationPtr.get()->Update(sprite)) {
                m_animationPtr = nullptr;
            }
            sf::Color c = sprite.getColor();
        }
        target->draw(sprite);
    }

};

A helper function

sf::Vector2u floatRectToVec2u(sf::FloatRect r) {
    sf::Vector2u vec;
    vec.x = (unsigned int)ceil(r.width);
    vec.y = (unsigned int)ceil(r.height);
    return vec;
    auto start = std::chrono::high_resolution_clock::now();
}

Main function

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);
    RenderComponent circle(&shape, floatRectToVec2u(shape.getGlobalBounds()));
    circle.SetAnimation<FadeIn>(1000);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        circle.draw(&window);
        window.display();
    }

    return 0;
}


texts: Is it still necessary to check for a front camera?

texts:
I'm trying to clean up redundant old code, so I'm asking this general question. Since all iOS 7 devices have a front camera, would it be safe to remove the code to check if the device has a front camera? In the past this was necessary as not all devices with iOS 6 had a front camera.

It is true that Apple could theoretically release a new device without a front camera, but I doubt this would ever happen.

What is your answer though on what I should do?

BOOL deviceHasFrontCamera = NO;

NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

for (AVCaptureDevice *device in videoDevices)
{
    if (device.position == AVCaptureDevicePositionFront)
    {
        deviceHasFrontCamera = YES;
    }
}


texts: Store variables function-wide and access them in an anonymous function

texts:
At the moment, I have this code:

(function() {
  var lastSelectedIndex = -1;
  function onSelTypeSelected() {
    // #selType is a <select> tag
    // var selType = document.getElementById("selType");
    var selType = this;
    // finished(onSuccess, onError)
   loader.finished(function(data) {
      lastSelectedIndex = selType.selectedIndex;
    }, function(err) {
      selType.selectedIndex = lastSelectedIndex;
    });
  }
})();

So lastSelectedIndex is not in the global context, however I want to put it into eventListener()'s context. inside eventListener(), so you can't access it in the outer anonymous function.
That's cleaner in my opinion and also faster (okay, a few nanoseconds) because of the scope chains hierarchy (Google Tech Talk: Speed Up Your JavaScript is a good introduction).

I thought of adding a property to the function (as I learnt here) but I don't have access to eventListener() in the anonymous functions.

The next idea I had was to use HTML 5 data-* attributes:

function onSelTypeSelected() {
  // #selType is a <select> tag
  // var selType = document.getElementById("selType");
  var selType = this;
  // finished accepts two arguments: onSuccess and onError
  loader.finished(function(data) {
    selType.setAttribute("data-lastIndex", selType.selectedIndex);
  }, function(err) {
    selType.selectedIndex = selType.getAttribute("data-lastIndex");
  });
}

(The default value for data-lastIndex will be set in the HTML Markup)


texts:
The following extension method is the limiting factor in the performance of an application I am developing, according to Visual Studio 2012 Performance Analysis profiler.

Is there a faster way to compare two collections for set equality?

public static bool SetEqual<T>(this IEnumerable<T> source, IEnumerable<T> other, IEqualityComparer<T> comparer = null)
{
    if (source == null) {
        throw new ArgumentNullException("source");
    }

    if (other == null) {
        throw new ArgumentNullException("other");
    }

    ICollection<T> sourceCollection = source as ICollection<T> ?? source.ToArray();
    ICollection<T> otherCollection = other as ICollection<T> ?? other.ToArray();

    if (sourceCollection.Count != otherCollection.Count) {
        return false;
    }

    if (sourceCollection.Except(otherCollection, comparer).Any()) {
        return false;
    }

    if (otherCollection.Except(sourceCollection, comparer).Any()) {
        return false;
    }

    return true;
}


texts:
I'm trying to refactor some code I wrote months ago when I used to use lots of anonymous functions. The way I'm trying to do it now is by taking all those functions and rewrite them within Object Literal Pattern.

I'm new to this kind of pattern and I would like to know if I'm doing it right, what should I improve or if there's a better way to write the code for easier maintainability.

The first piece of code I refactored is in the following rows and is about an accordion view.

I've also created a JsFiddle for this where you can see the whole code including the former way of writing the js.

var mainAccordion = {
  init: function() {
    this.cacheDom();
    this.bindEvents();
  },

  cacheDom: function() {
    this.$elTrigger = $('.js-accordion-trigger');
  },

  bindEvents: function() {
    this.$elTrigger.on('click', this.elExpand);
  },

  elExpand: function(event) {
    var $el = $(this),
        $elContent = $el.next('.accordion__content'),
        $elParent = $el.closest('li'),
        $elSiblings = $el.parent().siblings(),
        $groupSiblings = $el.parents('.list-with-header').siblings();

    if (!$elParent.hasClass('is-expanded')) {
      event.preventDefault();

      $elContent.show();
      $elParent.addClass('is-expanded');

      $elSiblings.removeClass('is-expanded');
      $elSiblings.find('.accordion__content').hide();

      if ($groupSiblings.find('li').hasClass('is-expanded')) {
        $groupSiblings.find('li').removeClass('is-expanded');
        $groupSiblings.find('.accordion__content').hide();
      }

      // animate accordion element to top of page
      $('html, body').stop().animate({
        'scrollTop': $elParent.offset().top
      });
    } else {
      event.preventDefault();

      $elContent.slideUp('fast');
      $elParent.removeClass('is-expanded');
    }
  }
};

mainAccordion.init();


texts:
My understanding is that Stack possesses LIFO property. And, based upon that I have written the following program:

// This is a sample program to demonstrate push and pop
// functionality in Stack in Java.

package collections;

public class Stack_Array {

    private static final int capacity = 3;
    int[] arr = new int[capacity];
    int top = -1;

    public void push(int pushedElement) {
        if(top >= capacity) {
            System.out.println("StackOverflow !!");
        } else {
            top++;
            arr[top] = pushedElement;
        }
    }

    public void pop() {
        if(top>=0) {
            top--;
        } else {
            System.out.println("Stack underflow !!");
        }
    }

    public void printStack() {
        System.out.println("Elements in Stack are: ");
        for(int i = top; i >=0; i--) {
            System.out.println(arr[i]);
        }
    }

    public static void main(String[] args) {

        Stack_Array s1 = new Stack_Array();
        s1.push(23);
        s1.push(21);
        s1.push(14);

        s1.pop();
        s1.printStack();
    }

}

Please let me know if it is the correct approach.
Or, is there a better way to implement the same


texts:
I have searched around but I was not able to find a complete implementation of the memoize pattern in a multithreaded context. It's the first time playing with thread synchronization. The code seems to works, but I am not able to test it extensively, in particular to find if there are race conditions. Do you think there is a better implementation, maybe using more advanced synchronization mechanism?

from threading import Thread, Lock, current_thread
import thread

def memoize(obj):
    import functools
    cache = obj.cache = {}
    lock_cache = obj.lock_cache = Lock()

    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        key = str(args) + str(kwargs)
        cached_result = None
        item_lock = None
        with lock_cache:
            # do the minimal needed things here: just look inside the cache,
            # return if present, otherwise create and acquire lock  specific to a
            # particular computation. Postpone the actual computation, do  not
            # block other computation.
             cached_result = cache.get(key, None)
            if cached_result is not None:
                 if type(cached_result) is not thread.LockType:
                     return cached_result
            else:
                item_lock = Lock()
                item_lock.acquire()
                cache[key] = item_lock

        if item_lock is not None:
            # if we are here it means we have created the lock: do the
            # computation, return and release.
            result = obj(*args, **kwargs)
            with lock_cache:
                cache[key] = result
            item_lock.release()
            return result

        if type(cached_result) is thread.LockType:
            # if we are here it means that other thread have created the
            # locks and are doing the computation, just wait
            with cached_result:
                return cache[key]
    return memoizer

Here a little test:

import time

@memoize
def f(x):
    time.sleep(2)
    return x * 10

lock_write = Lock()
def worker(x):
    result = f(x)
    with lock_write:
        print current_thread(), x, result

threads = []

start = time.time()
for i in (0, 1, 1, 2, 0, 0, 0, 1, 3):
    t = Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

time.sleep(1)

for i in (0, 1, 1, 2, 0, 0, 0, 1, 3):
    t = Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print time.time() - start

I get the correct results and it runs in 2 seconds, as expected.


texts:
My goal with this bit of code is to check if my processor supports rdrand and, if not, execute some other random number generating function. To check if rdrand is supported, the 30th bit in the ecx register should be set.

I guess my one of my dilemmas is whether or not I should explicitly check inside level 1 but I think eax implicitly sets the level there. Additionally, I wonder if I should set initialize the values of the registers to 0. I'd also like to know of any 'gotchas' and possible improvements.

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

#define bit_RDRND   (1 << 30)

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

    unsigned int eax;
    unsigned int ebx;
    unsigned int ecx;
    unsigned int edx;

    eax = 0x01;

    __asm__ __volatile__(
                         "cpuid;"
                         : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
                         : "a"(eax)
                         );

    printf("The value of the ecx register is %08x.\n", ecx);

    if(ecx & bit_RDRND){
        //use rdrand
        printf("use rdrand\n");
    }
    else{
        //use mt19937
        printf("use mt19937");
    }

    return 0;
}


texts: Implementing a method that escapes single quotes in a string

texts:
Background: In tcsh we can use single quotes inside single quote like this (like it said here):
echo 'It'\''s Shell Programming'

I want to create a method which escapes single quotes and prints it into a tcsh script I build on fly with Java. It should do:

If there is a \' (two chars) in the string, it will escape it so: \'\''.
If there is a ' (one char with no \ before it)  in the string, it will escape it so '\''.

I wrote the following method to do so:
private static String escapeStr(final String str) {
    String result = "";
    for (int index = 0; index < str.length(); ++index) {
        if (str.charAt(index) == '\\') {
            if (index + 1 < str.length() && str.charAt(index + 1) == '\'') {
                result += "\\'\\\''";
                index++;
            } else {
                result += str.charAt(index);
            }
        } else if (str.charAt(index) == '\'') {
            result += "'\\\''";
        } else {
            result += str.charAt(index);
        }
    }
    return result;
}

It looks like it does the job but I really don't like how I implemented it. It's hard to read as it has quite a lot of \ chars. Also I do index++ inside the  loop which feels like bad design. Is there a better approach here?
I will add that I want to call the method like so:
fileWriter.write("echo '" + escapeStr(cmd) + "'\n");

The whole point of this part is so the escape will print the cmd as-is. I wrap the command with ' so it won't evaluate stuff like environment variables. So if the cmd already contains single quote it will fail. I will need to escape single quotes and that what I tried to do.


texts:
Please review my code for bearer token (JWT) authentication of Web API 2 (Self Hosted using OWIN)

Are there any security issues in the implementation?

Quick overview:

Token creation and validation using JWT Handler
Symmetric key encryption
CORS support not yet checked for the authorization header
Web traffic will be on SSL.
The key cannot be auto-generated as it will break during a load balanced scenario. Can I save the key in config? Or switch to X509 certificates?

This is the main class to create and validate tokens:

public class TokenManager
{
    public static string CreateJwtToken(string userName, string role)
    {
        var claimList = new List<Claim>()
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.Role, role)     //Not sure what this is for
            };

        var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true };
        var sSKey = new InMemorySymmetricSecurityKey(SecurityConstants.KeyForHmacSha256);

        var jwtToken = tokenHandler.CreateToken(
            makeSecurityTokenDescriptor(sSKey, claimList));
        return tokenHandler.WriteToken(jwtToken);
    }

    public static ClaimsPrincipal ValidateJwtToken(string jwtToken)
    {
        var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true };

        // Parse JWT from the Base64UrlEncoded wire form
        //(<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>)
        JwtSecurityToken parsedJwt = tokenHandler.ReadToken(jwtToken) as JwtSecurityToken;

        TokenValidationParameters validationParams =
            new TokenValidationParameters()
            {
                AllowedAudience = SecurityConstants.TokenAudience,
                ValidIssuer = SecurityConstants.TokenIssuer,
                ValidateIssuer = true,
                SigningToken = new BinarySecretSecurityToken(SecurityConstants.KeyForHmacSha256),
            };

        return tokenHandler.ValidateToken(parsedJwt, validationParams);
    }

    private static SecurityTokenDescriptor makeSecurityTokenDescriptor(
        InMemorySymmetricSecurityKey sSKey, List<Claim> claimList)
    {
        var now = DateTime.UtcNow;
        Claim[] claims = claimList.ToArray();
        return new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            TokenIssuerName = SecurityConstants.TokenIssuer,
            AppliesToAddress = SecurityConstants.TokenAudience,
            Lifetime = new Lifetime(now, now.AddMinutes(SecurityConstants.TokenLifetimeMinutes)),
            SigningCredentials = new SigningCredentials(sSKey,
                "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                "http://www.w3.org/2001/04/xmlenc#sha256"),
        };
    }
}

I have a message handler to intercept the requests and I verify the validity of token except for the route for log in, using TokenManager.ValidateJwtToken() above.

To create the token, in the LoginController, I have the following code:

[Route("login")]
[HttpPost]
public HttpResponseMessage Login(LoginBindingModel login)
{
    if (login.Username == "admin" && login.Password == "password")  //Do real auth
    {
        string role = "Librarian";
        var jwtToken = TokenManager.CreateJwtToken(login.Username, role);

        return new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ObjectContent<object>(new
            {
                UserName = login.Username,
                Roles = role,
                AccessToken = jwtToken
            }, Configuration.Formatters.JsonFormatter)
        };
    }
    return new HttpResponseMessage(HttpStatusCode.BadRequest);
}

The full working code is available here and the instructions to run the sample are in the Wiki.


texts:
This is a Leetcode problem:

  Given an array of non-negative integers, you are initially positioned at the first index of the array.

  Each element in the array represents your maximum jump length at that
  position.

  Your goal is to reach the last index in the minimum number of jumps.

  Note:

  You can assume that you can always reach the last index.

Here is my first solution to this problem:

def jump(nums):
    n = len(nums)
    curr_far = min(nums[0], n - 1)
    next_far = 0
    step = 0
    for i in range(n):
        if i <= curr_far:
            if next_far < i + nums[i]:
                next_far = min(i + nums[i], n - 1)
            if i == curr_far and curr_far != 0:
                curr_far = next_far
                step += 1

    return step

nums = #Enter a list.
print(jump(nums))

Here is an example of an input/output:

nums = [2,3,1,1,4]
>>> 2

The minimum number of jumps to reach the last index is 2.

Jump 1 step from index 0 to 1, then 3 steps to the last index.

Here is my second solution to this problem:

class Solution:

    def __init__(self, nums):
        self.nums = nums

    def jump(self, nums):
        if not nums or len(nums) == 1:
            return 0

        curr = 0
        count = 0
        while(curr < len(nums)):
            maxReach = -1
            index = 0
            for i in range(1, nums[curr] + 1):
                if curr + i >= len(nums) - 1:
                    return count + 1
                else:
                    if nums[curr + i] + i > maxReach:
                        maxReach = nums[curr + i] + i
                        index = curr + i
            curr = index
            count += 1

nums = #Enter a list.
game = Solution(nums)
print(game.jump(nums))

Input/output - Same as above.

So, I would like to have a code review for the efficiency of both the programs.

Any help would be highly appreciated.


texts: Extracting the five most frequent queries from a log file

texts:
I'm trying to print the top 5 most queried strings from a text file. I can't use other third-party libraries to make it easier w.r.t hashmap implementations.

I need to improve on these if possible:

cyclomatic complexity
Memory usage
Execution time
Page faults

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

class Topfive {

    private HashMap<String, Integer> hashmap = new HashMap<String, Integer>();

    public HashMap<String, Integer> getHashmap() {
        return hashmap;
    }

    public void putWord(String main) {
        Integer frequency = getHashmap().get(main);
        if (frequency == null) {
            frequency = 0;
        }
        hashmap.put(main, frequency + 1);
    }

    public TreeMap<String, Integer> process(File fFile)
    throws FileNotFoundException {
        Scanner scanner = new Scanner(new FileReader(fFile));
        while (scanner.hasNextLine()) {
            String wordp = scanner.nextLine();
            int j = wordp.indexOf("query=") + 6;
            int k = wordp.length() - 1;
            String fut = wordp.substring(j, k).trim();
            this.putWord(fut);
        }
        scanner.close();
        ValueComparator bvc = new ValueComparator(getHashmap());
        TreeMap<String, Integer> sorted_map = new TreeMap<String, Integer>(bvc);
        sorted_map.putAll(getHashmap());
        return sorted_map;
    }
    public static void main(String[] args) {
        if (args.length > 0) {
            File fFile = new File(args[0]);
            Topfive topfive = new Topfive();
            try {
                TreeMap<String, Integer> sorted_map = topfive.process(fFile);
                int count = 0;
                for (String key : sorted_map.keySet()) {
                    System.out.println(key);
                    count++;
                    if (count >= 5) {
                        break;
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}

class ValueComparator implements Comparator<Object> {

    private Map<String, Integer> base;

    public ValueComparator(Map<String, Integer> base) {
        this.base = base;
    }

    @Override
    public int compare(Object first_obj, Object second_obj) {
        int ret = -1;
        if (base.get(first_obj) < base.get(second_obj)) {
            ret = 1;
        }
        return ret;
    }
}

Sample text in text file which is given as command line argument:

 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=60.112.154.0, query=this year]
 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=116.161.234.129, query=fashion]
 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=38.214.87.66, query=big lies]
 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=60.112.154.0, query=this year]
 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=116.161.234.129, query=fashion]
 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=38.214.87.66, query=big lies]
 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=68.175.141.150, query=seven levels]
 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=114.235.27.231, query=head]
 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=67.238.116.254, query=special]
 [Fri Jan 07 18:37:54 CET 2011] new query: [ip=220.153.109.208, query=present]


texts: Carousel using a function passed a target element

texts:
I've made a carousel, which uses a function that is passed a target element, and from this element it adds next, prev, next next, and prev prev classes to its siblings (causing the rotation) - what do they call this, pyramid code?

Looking at this code - it works, but can't stand know that there is probably a better way to write this:

   var render = function (cont) {
      cont.parent().find('.active').removeClass();
      cont.attr('class', 'active');
      cont.parent().children().removeClass('next prev next_next prev_prev');
      cont.next().attr('class', 'next');
      cont.prev().attr('class', 'prev');
      cont.next().next().attr('class', 'next_next');
      cont.prev().prev().attr('class', 'prev_prev');
   };


texts:
I'm fairly new to programming and I'm learning python.
I've defined a function for a dice roll and set it up to roll multiple.
def d20(num):
    rolls = 0
    for i in range(num):
        rolls += randint(1,20)
    return rolls

Thonny and my assistant tab gives me a warning:
Line 3: Unused variable 'i'

The code works fine but I like a clean workspace. I was wondering if there is an alternate way to write the range loop or is this just something I need to learn to deal with?


texts: Counting subsets with sum not exceeding some limit

texts:
I am facing a variation of a subset sum problem. I have to count the number of subsets with sum less than or equal to some integer(limit). I think the optimal solution for this problem would be the following DP relations

#number of ways to get sum using subsets of {1, 2, ..., i}
dp[i][sum] += dp[i - 1][sum]            #not using element i
dp[i][sum + array[i]] += dp[i - 1][sum] #using element i

Constraints:

1 <= n <= 30
1 <= array[i] <= 1e9
0 <= limit <= 1e9
Time: 1s
Memory: 64 Mb

At first I considered using plain array( or std::array, whatever) but an array dp[30][1e9 + 1] can't be allocated on stack and heap allocation would be too expensive given time limit of 1 second. I came up with the following implementation using std::unordered_map:

std::unordered_map<int, int> dp;

for (int element_idx = 0; element_idx < i_size; ++element_idx) {

  if (arr[element_idx] > limit) {
    continue;
  }
  std::unordered_map<int, int> new_sums;
  new_sums[arr[element_idx]] = 1;
  if (!element_idx) {
    dp = std::move(new_sums);
    continue;
  }
  for (std::pair<int, int> &sum_count : dp) {
    new_sums[sum_count.first] += sum_count.second;
  }

  for (std::pair<int, int> &sum_count : dp) {
    if (sum_count.first + arr[element_idx] <= limit) {
      new_sums[sum_count.first + arr[element_idx]] += sum_count.second;
    }
  }
  dp = std::move(new_sums);
}

The problem it that this implementation runs into a memory limit error. Moreover, my computer just freezes if the input is 30 distinct 6-, 7-digit integers. I am pretty sure there is nothing wrong with my algorithm and the only problem my poor algorithm implementation experience and C++ knowledge.


texts: Enum vs lookup table for temporary and permanent teeth

texts:
I'm implementing a solution in Java using Ebean and I'm having some issues choosing between using enums or simply look up tables.

I have a table "Tooth". A tooth can be "Temporary" or "Permanent".

I could create a simple enum:

@EnumMapping(nameValuePairs = "TEMPORARY=T, PERMANENT=P")
public enum DentitionType { TEMPORARY, PERMANENT; }

However, if I want to do a direct SQL query, I have to convert "T" and "P", so a solution would be to use a lookup table as below:

@Entity
public class DentitionType {

   @Column(length = 15)
   public String name;

    private static DentitionType permanent;

    public boolean isTemporary() {
        return !this.equals(getPermanent());
    }

    public boolean isPermanent() {
        return this.equals(getPermanent());
    }

    public static DentitionType getPermanent() {
        if (permanent == null) {
            permanent = DentitionType.FIND.byId(2L);
        }

        return permanent;
    }
}

This feels kind of hardcoded and for larger tables a lot of isSomething functions are required.

Is there a better solution?


texts:
Every time I write a new PHP page, I usually need to include this at the top:

<?php

    require_once(__DIR__ . '/../libraries/global.lib.php');

    function load_classes($class) { // appears to get all the names of the classes that are needed in this script...
        $file_name = './classes/' . $class . '.class.php';
        if (file_exists($file_name)) {
            require_once($file_name);
        }
    }

    function load_interfaces($interface) {
        $file_name = './classes/' . $interface . '.interface.php';
        if (file_exists($file_name)) {
            require_once($file_name);
        }
    }

    spl_autoload_register('load_interfaces');
    spl_autoload_register('load_classes');

?>

Is there any way to condense this? Would putting this in a separate PHP file work?


texts: Multithread to print odd and even numbers

texts:
I recently started on C++ multithreading. Here is my code to print odd and even numbers in two different thread. Can somebody please review this code?

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;

int x = 1;
mutex m;
bool evenready = false;
bool oddready = true;
condition_variable cond;
void printEven()
{
    for (; x < 10;) {
        unique_lock<mutex> mlock(m);
        cond.wait(mlock, [] {
            return evenready;
        });
        oddready = true;
        evenready = false;
        cout << "Even Print" << x << endl;
        x++;
        cond.notify_all();
    }
}

void printOdd()
{
    for (; x < 10;){
        unique_lock<mutex> mlock(m);
    cond.wait(mlock, [] {
        return oddready;
    });
    oddready = false;
    evenready = true;
    cout << "Odd Print" << x << endl;
    x++;
    cond.notify_all();
}
}

int main()
{
    thread t1(printOdd);
    thread t2(printEven);
    t1.join();
    t2.join();
    return 0;
}


texts:
How do I simplify this method?  Is handling an exception in this method a good idea?

[WebMethod]
public string GetMDSToken(string xuid)
{
    var tokenTask = _mapTokenService.GetMappedSSOTokenAsync(xuid);
    var tokenTimestampTask = _SSOFrontendService.GetSSOTokenTimestampAsync();

    Task.WhenAll(tokenTask, tokenTimestampTask);

    if (tokenTimestampTask.Result.Status != ResultStatus.OK)
        return _serializer.Serizalize(tokenTimestampTask.Result);

    if (tokenTask.Result == null)
    {
        var response = _handledResponseFactory.CreateErrorResponce(ResultStatus.Business, NotLogginErrorMessage);
        return _serializer.Serizalize(response);
    }

    try
    {
        var mappedToken = tokenTask.Result;
        if (mappedToken.SSOTokenTimestamp != tokenTimestampTask.Result.Content)
            UpdateSSOToken(mappedToken);

        var MDSTokenTask = _MDSFrontendService.GetToken(mappedToken.SSOToken);

        Task.WhenAll(MDSTokenTask);
        return _serializer.Serizalize(MDSTokenTask.Result);
    }
    catch (Exception ex)
    {
        var response = _handledResponseFactory.CreateExceptionResponce(ex);
        return _serializer.Serizalize(response);
    }
}


texts:
Context: I've been learning Python for a few months and I'm able to write codes which do work, but they normally look very ugly and contain a lot of unnecessary code. But I normally struggle to find better ways to do things because of my limited knowledge.

I would like some advice on what I can improve on the code below. FYI - it works perfectly well, but I'm guessing there must be ways to improve it. I know I'm repeating myself in the loops, for example.

def getTableGroupTopMember_Test1(coordinates):
    '''
    Depending on the number of coordinates given, this function/code returns a unique     coordinate.
    '''

    mylist = coordinates

    for adc in activeDataConnections:
        if mylist.Count == 1:
            for table in adc:
                if table.Name == mylist[0]:
                    print "/"
        elif mylist.Count == 2:
            for table in adc:
                if table.Name == mylist[0]:
                    for topgroup in table.TopAxis.Groups:
                        if topgroup.Name == mylist[1]:
                            print topgroup.Address
        elif mylist.Count == 3:
            for table in adc:
                if table.Name == mylist[0]:
                    for topgroup in table.TopAxis.Groups:
                        if topgroup.Name == mylist[1]:
                            for topmember in topgroup:
                                if topmember.Name == mylist[2]:
                                    print topmember.Address
        else:
            print "your code is shit!"

getTableGroupTopMember_Test1(["Table10"])
getTableGroupTopMember_Test1(["Table10", "profile_julesage",])
getTableGroupTopMember_Test1(["Table10", "profile_julesage", "_25_to_34"])

Output:

/
/2
/2[3]


texts: All outcomes for subtraction on each value in list individually

texts:
As you can see from my predicate iterate, I am repeating Z is X-3 and Z is X-2, the scenarios are different if the value is 0 or greater than 0. thus why the duplicates,

Was wondering if there was a way round this

iterate([], []).           %Nothing to change
    iterate([1|T], T).
    iterate([X|T], [Z|T]) :-   % Change only the headT
        (   Z is X - 3
        ;
            Z is X - 2
        ),
        Z>0 .
    iterate([X|T], T) :-   % Change only the head
        (   Z is X - 3
        ;
            Z is X - 2
        ),
        Z is 0 .

    iterate([X|Xs], [X|Ys]) :-  %Keep the head and change something later
        iterate(Xs, Ys).


texts: Find items in collection one that are the greatest value less than an item in collection two

texts:
This is hard to explain.  I wanted to get all of the items in collection one (ints in the example below) that are the highest values that are lower than any of the items in collection two (otherInts).  In the example below, only 2 and 8 should be returned from ints.  1 doesn't qualify because it is lower than 3 (in otherInts), but 2 is higher than 1, but still lower than 3.  2 does qualify because there is nothing higher than it that is lower than 3.  5 does not qualify for the same reason as 1, namely, 8 is higher than it, but also lower than 9 (in otherInts).

I've written the following linq to accomplish this.  I'd like to stay constrained to linq as opposed to a standard forEach since this is a sub-linq statement.  Is there a better linq way to accomplish this?

var ints = new List<int>{1,2,5,8};
var otherInts = new List<int>{3,4,9};

var intsImmediatelyLessThanOrEqualToOtherInts = from i in ints
    let firstGreaterOtherInt = otherInts.First(o => o > i)
    let intBetweenThisAndOther = from i2 in ints
        where i2 > i && i2 < firstGreaterOtherInt
        select i2
    select intBetweenThisAndOther.Count() > 0 ? null as object : i;

intsImmediatelyLessThanOrEqualToOtherInts.Where(i => i != null).ToList().ForEach(Console.WriteLine);

Here's a working fiddle if you want to test other cases.


texts:
I wonder whether I included too many libraries; also can you point out obvious beginner mistakes?

Is the while loop the best for what I intend, or is there a better way?

Also, is it possible to put more into functions such that the main() looks like this:

int main()

{

call function1

call function2

etc.

return 0;

}

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <vector>
#include <cstring>
using namespace std;

string random_line()
{
    string line;
    vector<string> lines;
    srand(time(0));
    //input file stream
    ifstream file("wordlist.txt");
    //count number of total lines in the file and store the lines in the string vector
    int total_lines=0;
    while(getline(file,line))
    {
        total_lines++;
        lines.push_back(line);
    }
    //generate a random number between 0 and count of total lines
    int random_number=rand()%total_lines;
    //fetch the line where line index (starting from 0) matches with the random number
    return lines[random_number];
}

int main()
{
    string secret_word=random_line();
    cout << secret_word; //this has to be cut at the end
    int word_length=secret_word.length();
    string guess_word="";
    string guessed_letters="";
    for (int i=0; i<word_length; ++i)
    {
        guess_word.append("_");
    }
    int remaining_fails=10;
    string guess="";

    while(remaining_fails!=0)
    {
        if(guess_word==secret_word)
        {
            cout << "Congratulations, the word is: "<<secret_word<<endl;
            return 0;
        }
        else
        {
            cout << string(50, '\n');
            cout << guess_word << endl;
            cout << "Remaining fails: " << remaining_fails << endl;
            cout << "Guessed letters: " << guessed_letters << endl;
            cout << "Guess your letter!" << endl;
            cin  >> guess;
            if(guess.length() !=1)
            {
                cout << "Please only enter one character!";
            }
            else if(strstr(secret_word.c_str(),guess.c_str()))
            {
                for(int i=0; i<word_length; ++i)
                {
                    if (guess.at(0)==secret_word.at(i))
                    {
                        guess_word.at(i)=guess.at(0);
                    }
                    else
                    {

                    }
                }
            }
            else
            {
                guessed_letters.append(guess);
                remaining_fails--;
            }
        }

    }
    cout << "You loose!"<<endl;
    return 0;
}

The wordlist.txt contains?

word
trio
list


texts: Handling Enum flags for a copy operation

texts:
I've just set up a bit of code to try and make things neater, but all I've really done, is add a whole bunch of nested if statements:

public void Copy(Copy copyType)
{
    FrmProjectChooser frm = null;
    if (copyType.HasFlag(Copy.Single))
    {
        if (copyType.HasFlag(Copy.Estimations) && copyType.HasFlag(Copy.SubItems))
        {
            // Single item, with sub items and estimations
            List<WB> items = new List<WB> { (WB)treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) };
            items.AddRange(_WBSManager.GetAllChildren(items[0].idWBS));
            List<CTREstimation> estimations = new List<CTREstimation>();
            foreach (WB wbs in items)
                estimations.AddRange(CTREstimationsManager.Instance.GetEstimationsForWBS(wbs.idWBS));
            frm = new FrmProjectChooser(items, estimations);
        }
        else if (copyType.HasFlag(Copy.Estimations))
        {
            // Single item, with estimations.
            WB wbsItem = treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) as WB;
            if (wbsItem != null)
                frm = new FrmProjectChooser(new List<WB> { wbsItem },
                    CTREstimationsManager.Instance.GetEstimationsForWBS(wbsItem.idWBS));
        }
        else if (copyType.HasFlag(Copy.SubItems))
        {
            // Single item, with sub items
            List<WB> items = new List<WB> { (WB)treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) };
            items.AddRange(_WBSManager.GetAllChildren(items[0].idWBS));
            frm = new FrmProjectChooser(items);
        }
        else
        {
            // Single item
            WB wbsItem = treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) as WB;
            if (wbsItem != null)
                frm = new FrmProjectChooser(new List<WB> {wbsItem});
        }
    }
    else if (copyType.HasFlag(Copy.All))
    {
        if (copyType.HasFlag(Copy.Estimations))
        {
            // All items, with estimations.
            List<WB> wbsItems = _WBSManager.GetWBSForProject(CurrentProject.idProjects);
            List<CTREstimation> estimations = new List<CTREstimation>();
            foreach (WB wbs in wbsItems)
                estimations.AddRange(CTREstimationsManager.Instance.GetEstimationsForWBS(wbs.idWBS));
            frm = new FrmProjectChooser(wbsItems, estimations);
        }
        else
        {
            // All items
            frm = new FrmProjectChooser(_WBSManager.GetWBSForProject(CurrentProject.idProjects));
        }
    }

    if (frm != null)
        frm.ShowDialog();
}

[Flags]
private enum Copy
{
    None = 0,
    Single = 1, // Straight copy of single item
    SubItems = 1 << 1, // Include any children in the copy
    Estimations = 1 << 2, // Include estimations in the copy
    All = 1 << 3 // Copy all items
}

The code will pull "Items" from a TreeList. "Sub Items" are of the same type as "Items", but Estimations are a different type. I don't think it's very neat. I've tried googling similar titles to this question but I can't really find anything that helps.

Is there anything I can do to make this neater?


texts: JavaScript component to display ephemeral notifications

texts:
I would like to improve my code and organization of JS files so I'm wondering if you guys could tell me what I could do better. I've included a small but typical example of how I often use components.

With this component I'm able to show different kind of notifications to the user, which then disappear after a set amount of time.

I use these components by adding this in the appropriate location: new notification('warning', $('.sourcecode-warning').text(), 20000);. Rip away!

function notification(notificationType, message, delay) {
var _this = this;
this.notificationType = notificationType;
this.className = 'notification';
this.message = message;
this.delay = delay || 3000;
this.removeTimeOut;
this.disappearTimeOut;

this.init = function () {
    $('body').append('

' + _this.message + '

');
    _this.setEvents();

    _this.removeTimeOut = setTimeout(function () {
        _this.startDisappearing();
    }, _this.delay);
};

this.setEvents = function () {
    $('.close-notification').bind('click', function () {
        _this.removeSelf();
    });
};

this.startDisappearing = function () {
    $('.' + _this.className).addClass('disappearing');

    _this.disappearTimeOut = setTimeout(function () {
        _this.removeSelf();
    }, 1200);
};

this.removeSelf = function () {
    clearTimeout(_this.removeTimeOut);
    clearTimeout(_this.disappearTimeOut);

    $('.' + _this.className).remove();
};

if ($('.' + _this.className).length === 0) _this.init();
};


texts:
I need to learn bash at some point in the near future, so I decided to start playing around with it. This is really the first actual script that I've written and would like feedback.

This finds and prints all the prime numbers up to the argument provided to the script:

./primes.sh 100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

Honestly, this is proving to be a challenging language with very finicky syntax and a lot of ways to do things half-incorrectly. This code works, but I'm sure it's far from optimal. I'd like any and all recommendations.

I intentionally included the mostly-unnecessary hasFactor function just to force use of functions. I wanted to see what complications it caused. The main issue with it is needing to return a number representing a boolean that indicates if the number has a factor or not, and cleanly handling that returned exit code at the "call-site". Needing to check against 1 seems poor. Any suggestions regarding use of functions would be appreciated.

And I know better algorithms exist, but I wanted to keep it simple.

#!/usr/bin/env bash

maxNumber=$1

# Returns if a number has factors other than 1 and itself
# Params: n - number to check
function hasFactor {
    n=$1
    for ((factor=2; factor<n; factor++)); do
        if [ $((n % factor)) -eq 0 ]; then
            true
            return
        fi
    done

    false
    return
}

for ((n=2; n<maxNumber; n++)); do
    hasFactor $n
    if [ $? = 1 ]; then
        echo $n
    fi
done


texts: Scroll with multiple, and going different directions

texts: I have a large image of an L-shaped painting on one page. I created divs over parts of the painting I want to explain. When the page loads, I want it to scroll down the length of the image, and then move to the left of the image, stopping at each div for a few seconds. I understand how to get the page to scroll down on load, but I do not understand how to continue scrolling once it has reached the first div. Should I target the data-box and not the class, so it will continue to move through each div box?


texts:
I have been trying to learn the various aspects of the languages I know so far to do the Daily Challenges in reddit (/r/DailyProgrammer). The one which I am working on just now asks for an alphabetised count of the occurrences of letters in a string e.g: "Hello World" -> "d:1 e:1 h:1 l:3 o:2 r:1 w:1".

I have tried to write this seemingly simple challenge in Swift (I had already done it in C#, JavaScript and F#), but after longer than should have been the case, I have arrived at the following solution which seems a bit messy to me:

func countLetters(input: String) -> String  {

    // Convert to Lowercase
    var lower = input.lowercaseString

    // Filter out invalid characters ([a-z] only)
    var validCharacters = filter(lower) { $0 >= Character("a") && $0 <= Character("z") }

    // Create a dictionary to build the letter counts
    var letterCounts = Dictionary<Character, Int32>()
    // Go through the characters and add to the dictionary
    for i in validCharacters {
        if letterCounts[i] != nil { // If already exists, add one to the count
            letterCounts[i] = letterCounts[i]! + 1
        } else {
            letterCounts[i] = 1 // If doesn't exist, add to the dictionary with a count of 1
        }
    }

    // Unfortunately the Dictionary does not seem to be sorted / sortable, so we need to
    // create an Array of the stringified version to allow sorting
    var stringifiedCounts = Array<String>()

    // Convert each dictionary item to a 'a:1' type string
    for (k,v) in letterCounts {
        stringifiedCounts.append("\(k):\(v) ")
    }

    // Sort the list
    sort(&stringifiedCounts)

    // Concatenate the results
    var output = ""
    for i in stringifiedCounts {
        output += i
    }

    // Remove the last space
    return output.substringToIndex(advance(output.startIndex, countElements(output) - 1))
}

I was going to ask the question in my reply on Reddit, but I am quite late with it, so I doubt anyone will be looking.

For those who have been more regularly using Swift, is there a cleaner way to deal with Dictionaries so that I don't have to covert it to an array before sorting? What are some of the cleverer ways to get the same results?


texts: Calculating the last digit of a^b where a and b are very large numbers

texts:
I have to make code that calculates the last digit of \$a^b\$. Here, \$a\$ can have up to 1000 digits whereas \$b\$ can be from 0 to 915*1015. Now I calculated the last digit of a and raised that single digit number to the power b and that number's last digit will be the answer.

#include <iostream>
#include <math.h>
#include <string>
using namespace std;
unsigned long long int foo (unsigned long long int a,unsigned long long int b );
int main (void)
{
    int test;
    cin>>test;
    while ( test != 0 )
    {
        string a;
        cin>>a;
        unsigned long long int b;
        cin>>b;
        char c;
        int e;
        string::iterator it = a.end()-1;
        c = *it;
        e = c -48;
        if ( e == 0 && b == 0 )
            cout<<"0"<<"\n";
        else
        {
            unsigned long long modu  = foo(e,b);
            cout<<modu<<"\n";
            test--;
        }
    }
    return 0;
}

unsigned long long int foo (unsigned long long int a,unsigned long long int b )
{
    unsigned long long int ret;
    if ( b == 0 )
        return 1;
    if ( b % 2 == 0 )
    {
        ret = foo(a,b/2);
        ret = ret*ret;
    }
    else if ( b % 2 != 0 )
    {
        ret = foo(a,b/2);
        ret = ret*ret;
        ret = ret*a;
    }
    return ret%10;
}

However, I don't know why this shows WA on submitting it? Any corner cases that I might be missing?


texts:
I have the following code for reading a json file into pandas dataframe and parsing the fields, but it is too slow for large files. Is there a way to make the code more efficient?

def extract_text(json_train_path):

    with open(json_train_path, 'r') as json_file:

        train = {'example_id':[],
                    'question':[],
                    'text':[],
                    'long_answer':[],
                    'long_answer_text':[],
                    'short_answer':[],
                    'short_answer_text':[],
                    'yes_no_answer':[]}

        # extract files
        for line in tqdm(json_file):
                data = json.loads(line)

                example_id = str(data['example_id'])
                question = data['question_text']

                # clean text
                text = data['document_text']
                text = BeautifulSoup(text, "lxml").text
                #text = text.lower()

                long_start = data['annotations'][0]['long_answer']['start_token']
                long_end = data['annotations'][0]['long_answer']['end_token']
                long_answer_text = text.split(' ')[long_start:long_end]
                long_answer_text = ' '.join(long_answer_text)

                yes_no_answer = data['annotations'][0]['yes_no_answer']

                if yes_no_answer == 'NONE':
                    yes_no_answer = ''

                if data['annotations'][0]['short_answers']:
                    short_start = data['annotations'][0]['short_answers'][0]['start_token']
                    short_end = data['annotations'][0]['short_answers'][0]['end_token']
                    short_answer = (f'{short_start}:{short_end}')
                    short_answer_text = text.split(' ')[short_start:short_end]
                    short_answer_text = ' '.join(short_answer_text)

                else:
                    short_start = ''
                    short_end = ''
                    short_answer_text = ''
                    short_answer = ''

                # construct the DataFrame
                train['example_id'].append(example_id)
                train['question'].append(question)
                train['text'].append(text)
                train['long_answer'].append(f'{long_start}:{long_end}')
                train['long_answer_text'].append(long_answer_text)
                train['short_answer'].append(short_answer)
                train['short_answer_text'].append(short_answer_text)
                train['yes_no_answer'].append(yes_no_answer)

    return train

This is an example of a line of json being parsed

document_text   long_answer_candidates  question_text   annotations document_url    example_id
0   Email marketing - Wikipedia <H1> Email marketi...   [{'start_token': 14, 'top_level': True, 'end_t...   which is the most common use of opt-in e-mail ...   [{'yes_no_answer': 'NONE', 'long_answer': {'st...   https://en.wikipedia.org//w/index.php?title=Em...   5655493461695504401


texts: Using pytest fixtures for the expected answers to a test?

texts:
I want to test a number of different functions I have written to solve the Fizzbuzz challenge and would like to know what is the best way to check the result?
Each function returns a list of the answers and I want to check the list is correct. One of the functions is shown below
def fizz_buzz_using_boolean():
    fizz_buzz_list = []

    for x in range(1, 101):

        fizz = x % 3 == 0
        buzz = x % 5 == 0

        if fizz and buzz:
            fizz_buzz_list.append('fizzbuzz')
            continue
        elif fizz:
            fizz_buzz_list.append('fizz')
            continue
        elif buzz:
            fizz_buzz_list.append('buzz')
            continue
        else:
            fizz_buzz_list.append(x)

    return fizz_buzz_list

My tests look like this:
import pytest
from fizz_buzz import fizz_buzz_if_calc, fizz_buzz_using_boolean

@pytest.fixture
def fizzbuzz_expected_answer():
    """A list of the fizzbuzz answers for 1 - 100"""
    fizz_buzz = [1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16, 17, 'fizz', 19, 'buzz', 'fizz', 22, 23, 'fizz', 'buzz', 26, 'fizz', 28, 29, 'fizzbuzz', 31, 32, 'fizz', 34, 'buzz', 'fizz', 37, 38, 'fizz', 'buzz', 41, 'fizz', 43, 44, 'fizzbuzz', 46, 47, 'fizz', 49, 'buzz', 'fizz', 52, 53, 'fizz', 'buzz', 56, 'fizz', 58, 59, 'fizzbuzz', 61, 62, 'fizz', 64, 'buzz', 'fizz', 67, 68, 'fizz', 'buzz', 71, 'fizz', 73, 74, 'fizzbuzz', 76, 77, 'fizz', 79, 'buzz', 'fizz', 82, 83, 'fizz', 'buzz', 86, 'fizz', 88, 89, 'fizzbuzz', 91, 92, 'fizz', 94, 'buzz', 'fizz', 97, 98, 'fizz', 'buzz']

    return fizz_buzz

def test_fizz_buzz_using_boolean_has_correct_items(fizzbuzz_expected_answer):

    actual = fizz_buzz_using_boolean()

    assert actual == fizzbuzz_expected_answer

I have used a fixture to return the correct answer. Whilst the tests pass I can't find other examples of fixtures being used this way.
The other solutions come to mind is to use a global
import pytest
from fizz_buzz import fizz_buzz_if_calc, fizz_buzz_using_boolean

FIZZBUZZ_EXPECTED_ANSWER = [1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16, 17, 'fizz', 19, 'buzz', 'fizz', 22, 23, 'fizz', 'buzz', 26, 'fizz', 28, 29, 'fizzbuzz', 31, 32, 'fizz', 34, 'buzz', 'fizz', 37, 38, 'fizz', 'buzz', 41, 'fizz', 43, 44, 'fizzbuzz', 46, 47, 'fizz', 49, 'buzz', 'fizz', 52, 53, 'fizz', 'buzz', 56, 'fizz', 58, 59, 'fizzbuzz', 61, 62, 'fizz', 64, 'buzz', 'fizz', 67, 68, 'fizz', 'buzz', 71, 'fizz', 73, 74, 'fizzbuzz', 76, 77, 'fizz', 79, 'buzz', 'fizz', 82, 83, 'fizz', 'buzz', 86, 'fizz', 88, 89, 'fizzbuzz', 91, 92, 'fizz', 94, 'buzz', 'fizz', 97, 98, 'fizz', 'buzz']

def test_fizz_buzz_using_boolean_has_correct_items():

    actual = fizz_buzz_using_boolean()

    assert actual == FIZZBUZZ_EXPECTED_ANSWER

Or my least favourite to use a literal in each test (which will lead to lots of duplicatation)
def test_fizz_buzz_using_boolean_has_correct_items():

    actual = fizz_buzz_using_boolean()

    assert actual == [1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16, 17, 'fizz', 19, 'buzz', 'fizz', 22, 23, 'fizz', 'buzz', 26, 'fizz', 28, 29, 'fizzbuzz', 31, 32, 'fizz', 34, 'buzz', 'fizz', 37, 38, 'fizz', 'buzz', 41, 'fizz', 43, 44, 'fizzbuzz', 46, 47, 'fizz', 49, 'buzz', 'fizz', 52, 53, 'fizz', 'buzz', 56, 'fizz', 58, 59, 'fizzbuzz', 61, 62, 'fizz', 64, 'buzz', 'fizz', 67, 68, 'fizz', 'buzz', 71, 'fizz', 73, 74, 'fizzbuzz', 76, 77, 'fizz', 79, 'buzz', 'fizz', 82, 83, 'fizz', 'buzz', 86, 'fizz', 88, 89, 'fizzbuzz', 91, 92, 'fizz', 94, 'buzz', 'fizz', 97, 98, 'fizz', 'buzz']

Which method should I use?