texts:
Honestly, it should be an incredibly simplistic function, yet it has become the following atrocity:

function rotate(arr, n){

  // step 1: pick n different elements in the array
  var allIndexes = [];
  for(var i = 0; i<arr.length; i++){
    allIndexes.push(i);
  }

  var pickedIndexesToRotate = [];
  var valuesOfPickedIndexes = [];
  for(var i = 0; i<n; i++){
    var randomIndex = Math.floor(Math.random()*allIndexes.length);
    valuesOfPickedIndexes.push(arr[allIndexes[randomIndex]]);
    pickedIndexesToRotate.push(allIndexes.splice(randomIndex,1)[0]);
  }

  // step 2: actually rotate those elements...
  //         so if n = 3 and pickedIndexesToRotate = [5, 1, 2]
  //         we get [10, 60, 20, 40, 50, 30]
  for(var i = 1; i<=n; i++){
    arr[pickedIndexesToRotate[i == n ? 0 : i]] = valuesOfPickedIndexes.shift();
  }

  return arr;

}
rotate([10,20,30,40,50,60], 3);

And as it's just for a weekend project and it works I should be happy... but honestly, I can not say I am. It feels like the function is both far too complex for the simplicity of the task and far too inefficient. Looking forward to any and all criticism and advice.

(And just for the record: I wouldn't normally have those comments in my code as I believe code should be self explanatory, but it seemed useful in this case (as in, on codereview.SE) to make the intent of the function clear.)


texts: Identifying a development and production server by http_host

texts:
I am using below code to recognize which set up I need to use in Codeigniter:

$dev_urls = array('dev.com');
$prod_urls = array('prod.com');

if(in_array($_SERVER['HTTP_HOST'], $dev_urls)){
    define('ENVIRONMENT', 'development');
}
else if(in_array($_SERVER['HTTP_HOST'], $prod_urls)){
    define('ENVIRONMENT', 'production');
}
else{
    define('ENVIRONMENT', '');
}

if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
    case 'development':
        error_reporting(E_ALL);
        require('/application/config/development/dev_config.php');
    break;

    case 'testing':
    case 'production':
        error_reporting(0);
        require('/application/config/production/prod_config.php');
    break;

    default:
        exit('The application environment is not set correctly.');
}
}

I went through this answer, but, I am still skeptical about my code.


texts: Is the "current connected user" an information that should be shared with the domain?

texts:
I'm working right now in a readers social network. The main points are this:

When an user connects with his account I save his user id in the
session variable.
My MVC is working with DTO's all the way, filling the necessary
variables for the presentation in the model.

So, everything was ok, until today that I had to do a function that returns a DTO that has all the information of an user profile page. User profile pages can be accessed by anyone who has an account (Like Facebook user pages).

This profile page, shows a button "Follow" if the profile is not the profile of the current user (to avoid you following yourself).
If we are following that user, it will display an unfollow button.

So I was thinking that the UserProfileDTO must have two boolean:

isTheCurrentUser and isFollowedByTheCurrentUser.

public class UserProfileDTO {
    private Long id;
    private String username;

    private Boolean isCurrentUser;
    private Boolean isfollowedByCurrentUser;
...

And the Domain Controller

public User getUserProfile(String username, Long currentUserId) throws UserNameDoesntExist {
         UserProfileDTO user = dataController.getUserByUsername(username);
         if(user != null) {
               user.setIsCurrentUser(currentUserId == user.getId());
           user.setIsFollowedByCurrentUser(dataController.isFollowed(user.getId(), currentUserId));
          ...

But I thought, "This DTO will be filled with information at the domain model. So the domain must have information that the presentation had first. That information is the current connected user, thus that will create a dependency between the two layers.

Am I correct? Should the domain model be ignorant about who the current connected user is? Or is what I am doing okay?


texts: Transforming lists of products to boolean vectors

texts:
Task

Inputs

Lists of products stored in a CSV file, where each line represents the shopping list of a single client:

Outputs

A CSV file:

Header: products names sorted by number of appearances in the input file.
For each line k we output boolean vectors where each of its elements indicates whether the i-th product was present on the line k in the input file or not.

Approach 1

from collections import defaultdict

with open('bigtest.csv', 'r') as inp:
    index = defaultdict(lambda: set())
    for line_number, line_str in enumerate(inp):
        products = line_str[:-1].split(',')
        for product in products:
            index[product].add(line_number)

product_names = index.iterkeys()
sorting_key = lambda name: len(index[name])

header = sorted(product_names, key=sorting_key, reverse=True)

def generate_table():
    for line in range(line_number + 1):
        yield (1 if line in index[product] else 0 for product in header)

with open('formal0.csv', 'w') as out:
    print >> out, ','.join(header)
    for vector in generate_table():
        print >> out, ','.join(str(val) for val in vector)

Approach 2

More declarative

from collections import defaultdict

with open('bigtest.csv', 'r') as inp:
    data = (line[:-1].split(',') for line in inp)

    index = defaultdict(lambda: set())
    for line_number, products in enumerate(data):
        for product in products:
            index[product].add(line_number)

header = sorted(
    index.iterkeys(),
    key=lambda p: len(index[p]),
    reverse=True
)

table = ((1 if line in index[product] else 0 for product in header)
         for line in range(line_number + 1))

with open('formal0.csv', 'w') as out:
    print >> out, ','.join(header) + '\n' + '\n'.join(','.join(map(str, vector))
                                                      for vector in table)

Concerns

Readability
Clean way to make nested generators?
Am I abusing .join()?
How much declarative style is too much?


texts:
Is there any room for improvements in this code. I am new to programming (python3), learning and practicing functions related to arguments recently.
def make_pizza(*toppings, **pizza_info):

    """Creating a dictionary for pizza information"""
    pizza = {}

    pizza_toppings = [topping for topping in toppings]
    pizza['toppings'] = pizza_toppings

    for key, value in pizza_info.items():
        pizza[key] = value

    return pizza

def show_pizza(pizza):

    """Showing the order with the information provided by make_pizza() function."""

    print("You've ordered " + str(pizza['size']) + " inches size " + pizza[
        'crust'].title() + " crust pizza with the toppings of:")

    for topping in pizza['toppings']:
        print("-" + topping.title())

# Taking order in a form of dictionary structure
order = make_pizza('cheese', 'mushroom', size=12, crust='thin')

# Show the order message
show_pizza(order)


texts:
I have the following code below I was wondering if there is a way to clean it up/improve it especially near the if statements. I am new to programming and this is what I came up with and its working fine I just think there might be a better way to accomplish it.

    <?php

require 'DB.php';

try {

    $stmt = $conn->prepare('SELECT * FROM equipment');
    $stmt->execute();
    } catch(PDOException $e){
        echo'ERROR: ' . $e->getMessage();
    }

echo "

Equipment Type
Unit Number
Last Updated
Current Hours
Scheduled PM

";

while($row = $stmt->fetch())
  {
  echo "
";
  echo "" . $row['equipType'] . "	";
  echo "" . $row['unitNumber'] . "	";
  echo "" . $row['lastUpdate'] . "	";

  if ($row['nextPM'] - $row['currentHours'] > 100) {

  echo "" . $row['currentHours'] . "	";
  echo "" . $row['nextPM'] . "	";

  } else if ($row['nextPM'] - $row['currentHours'] < 100 && $row['nextPM'] - $row['currentHours'] > 50){

  echo "" . $row['currentHours'] . "	";
  echo "" . $row['nextPM'] . "	";

  }

  else {
  echo "" . $row['currentHours'] . "	";
  echo "" . $row['nextPM'] . "	";
  }
  echo "
";
  }
echo "
";
?>


texts:
I commonly run into the need to implement IDisposable in my code. To correctly dispose of both managed and unmanaged resources requires a reasonable amount of boilerplate code. Based on the documentation found here I have created the following base class.

My intent is that any object I create that needs to dispose of resources doesn't need to rewrite the boilerplate code. Rather it can inherit from this object and implement two abstract methods.

Does this appear correct? And has anyone else written something similar? I would appreciate comments on the style, correctness and how well this conforms to best practices.

public abstract class DisposableObject : IDisposable
{
    private bool _disposed = false;

    public bool Disposed
    {
        get { return _disposed; }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~DisposableObject()
    {
        Dispose(false);
    }

    private void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                DisposeManagedResources();
            }

            DisposeUnmanagedResources();

            _disposed = true;
        }
    }

    protected abstract void DisposeManagedResources();
    protected abstract void DisposeUnmanagedResources();
}

EDIT: Final Implementation

public abstract class DisposableObject : IDisposable
{
    public bool Disposed { get; private set;}

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~DisposableObject()
    {
        Debug.Assert(Disposed, "WARNING: Object finalized without being disposed!");
        Dispose(false);
    }

    private void Dispose(bool disposing)
    {
        if (!Disposed)
        {
            if (disposing)
            {
                DisposeManagedResources();
            }

            DisposeUnmanagedResources();
            Disposed = true;
        }
    }

    protected virtual void DisposeManagedResources() { }
    protected virtual void DisposeUnmanagedResources() { }
}


texts: Inorder, Preorder, and Postorder traversal of a binary tree in C++

texts:
I am a newbie in this world of data structures and algorithms (returning to these topics after 5 long years).  Can someone please check if the code I have written for Binary Tree is OK?

Test-case
10, 3,11,11,5,0

PrintInorder
3,0,5,10,11,11

PrintPreOrder
10,3,0,5,11,11

PrintPostOrder
3,0,5,11,11,10

using namespace std;

template<typename T>
struct Node
{
    T data;
    Node<T>* left;
    Node<T>* right;

    Node()
    {
        left = nullptr;
        right = nullptr;
    }
};

template<typename T>
class BTree
{
public:
    BTree();
    ~BTree();
    void Add(T val);
    void Print(int o);
    T Find(T key);
private:
    Node<T>* root;
    Node<T>* temp;
    int height;
    Node<T>* Add(T val, Node<T>* node);
    void PrintInorder(Node<T>* ptr);
    void PrintPreOrder(Node<T>* ptr);
    void PrintPostOrder(Node<T>* ptr);
};

template<typename T>
T BTree<T>::Find(T key)
{
    Node<T>* current = this->root;

    while (current!= nullptr)
    {
        if (current->data == key)
        {
            return current->data;
        }
        else if(current->data > key)
        {
            current = current->left;
            continue;
        }
        else if (current->data < key)
        {
            current = current->right;
            continue;
        }
    }
}

template<typename T>
void BTree<T>::PrintInorder(Node<T>* ptr)
{
    PrintPreOrder(ptr->left);
    cout<<ptr->data<<endl;
    PrintPreOrder(ptr->right);
}

template<typename T>
void BTree<T>::PrintPostOrder(Node<T>* ptr)
{
    PrintPreOrder(ptr->left);
    PrintPreOrder(ptr->right);
    cout<<ptr->data<<endl;
}

template<typename T>
BTree<T>::BTree()
{
    root = nullptr;
    height = 0;
}

template<typename T>
void BTree<T>::PrintPreOrder(Node<T>* ptr)
{
    if (ptr!=nullptr)
    {
        cout<<ptr->data<<endl;
    }

    if(ptr->left!=nullptr)
        PrintPreOrder(ptr->left);
    if(ptr->right!=nullptr)
        PrintPreOrder(ptr->right);
}

template<typename T>
void BTree<T>::Print(int o)
{
    if (o==1)
    {
        PrintInorder(root);
    }
    else if (o==2)
    {
        PrintPreOrder(root);
    }
    else if(o==3)
    {
        PrintPostOrder(root);
    }
}

template<typename T>
BTree<T>::~BTree()
{
}

template<typename T>
void BTree<T>:: Add(T val)
{
    if (root==nullptr)
    {
        root = Add(val, nullptr);
    }
    else
    {
        root = Add(val,root);
    }
}

template<typename T>
Node<T>* BTree<T>::Add(T val, Node<T>* node)
{
    if (node == nullptr)
    {
        node = new Node<T>();
        node->data = val;
        return node;
    }
    else
    {
        if (val <= node->data)
        {
            node->left = Add(val,node->left);
        }
        else
        {
            node->right =  Add(val,node->right);
        }
    }

    return node;
}


texts:
I have a PHP cronjob script. I need to send requests and get responses from some external API.

So, there is code for the API class. In this class, I connect to the API and  call public methods of this class from another class.

class Api {
private $authApi;
private $logger;

function __construct()
{
    global $_AUTH_API;
    $this->authApi = $_AUTH_API;
    $this->logger = new CustomLogs();
}

public function getBrands()
{
    $options = [
        'request' => 'get_brands',
    ];

    $brands = $this->requestApi($options);

    return $brands->rows;
}

public function get****() {}

/**
 * @param $data
 *
 * @return array|mixed|object
 * @throws Exception
 */
private function requestApi($data)
{
    $data = $this->authApi + $data;

    $data = [
        'data' => json_encode($data)
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.com/api/");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $answer = json_decode(curl_exec($ch));
    curl_close($ch);

    if (empty($answer)) {
        $this->logger->log->error('Empty answer from API');
        throw new Exception('Empty answer from API');
    } else {
        if ($answer->success != true) {
            $this->logger->log->error('API error: ', (array) $answer );
            throw new Exception('API error: ' . $answer->message  );
        } else {
            return $answer;
        }
    }
}
}

How can different API responses be handled correctly? What should be written in Logs? Do I need to throw Exceptions? What should be returned to external code? (i.e. in getBrands())

What would you change in this code?


texts:
Given a collection of intervals, merge all overlapping intervals.

  input: [1,3],[2,6],[8,10],[15,18],

  output: [1,6],[8,10],[15,18].

The logic is very simple: just merge all the intervals iteratively from first to last.

# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
        def merge(self, intervals_struct):
            """
            :type intervals: List[Interval]
            :rtype: List[Interval]
            """
            def is_intersect((i1_l, i1_r), (i2_l, i2_r)):
                if i1_r >= i2_l and i1_r <= i2_r:
                    return True
                elif i2_r >= i1_l and i2_r <= i1_r:
                    return True
                return False

            def merge_interval((i1_l, i1_r), (i2_l, i2_r)):
                return [min(i1_l, i2_l), max(i1_r, i2_r)]

            intervals = []
            for i in intervals_struct:
                intervals.append([i.start, i.end])

            intervals = sorted(intervals, key=lambda x:x[0])

            i, result = 0, []
            while i < len(intervals):
                max_l, max_r = intervals[i]
                while i < len(intervals) and is_intersect([max_l, max_r], intervals[i]):
                    max_l, max_r = merge_interval([max_l, max_r], intervals[i])
                    i += 1
                result.append([max_l, max_r])
                if i < len(intervals) and intervals[i] == [max_l, max_r]:
                    i += 1
            return result


texts: Finding the common prefix in a list of strings

texts:
Given a list of strings, my task is to find the common prefix.

Sample input: ["madam", "mad", "mast"]
Sample output: "ma"

Sample input: ["question", "method"]
Sample output: ""

Below is my solution, I'd be happy for help improving the algorithm (I'm open to totally different approaches) or general code improvement tips.
Thanks :)

public class PreFixer {

    public static void main(String[] args) {
        if(args.length < 1) {
            System.out.println("invalid arguments");
            return;
        }
        String commongPrefix = getCommonPrefix(args);
        System.out.println("Common Prefix for list is : " + commongPrefix);
    }

    private static String getCommonPrefix (String[] list){
        int matchIndex = recursiveChecker(0, list);
        return list[0].substring(0, matchIndex);
    }

    private static int recursiveChecker(int strIndex, String[] list){

        for(int x=0; x<list.length; x++) {
            if(strIndex >= list[x].length()){
                return strIndex;
            }

            if(list[0].charAt(strIndex) != list[x].charAt(strIndex)) {
                return strIndex;
            }
        }

        return recursiveChecker(strIndex + 1, list);
    }
}


texts:
I've been developing a forum as my first OOP project, I've successfully built a login/registration and other functionality typical in forums.

I'm looking for some guidance in terms of where to take the build and other common functions that will need integrating.

users.php

<?php
class USER
{
  private $db;

  function __construct($DB_con)
  {
    $this->db = $DB_con;
  }

  public function register($fname,$lname,$uname,$umail,$upass)
  {
   try
   {
     $new_password = password_hash($upass, PASSWORD_DEFAULT);

     $stmt = $this->db->prepare("INSERT INTO users(user_name,user_email,user_pass)
       VALUES(:uname, :umail, :upass)");

     $stmt->bindparam(":uname", $uname);
     $stmt->bindparam(":umail", $umail);
     $stmt->bindparam(":upass", $new_password);
     $stmt->execute();

     return $stmt;
   }
   catch(PDOException $e)
   {
     echo $e->getMessage();
   }
 }

 public function login($uname,$umail,$upass)
 {
   try
   {
    $stmt = $this->db->prepare("SELECT * FROM users WHERE user_name=:uname OR user_email=:umail LIMIT 1");
    $stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
    $userRow=$stmt->fetch(PDO::FETCH_ASSOC);
    if($stmt->rowCount() > 0)
    {
     if(password_verify($upass, $userRow['user_pass']))
     {
      $_SESSION['user_session'] = $userRow['user_id'];
      return true;
    }
    else
    {
      return false;
    }
  }
}
catch(PDOException $e)
{
 echo $e->getMessage();
}
}

public function is_loggedin()
{
  if(isset($_SESSION['user_session']))
  {
   return true;
 }
}

public function redirect($url)
{
 header("Location: $url");
}

public function logout()
{
  session_destroy();
  unset($_SESSION['user_session']);
  return true;
}

public function back() {
  $previous = $_SERVER['HTTP_REFERER'];
  if (isset($previous)) {
    echo $previous;
  } else {
    return FALSE;
  }

}

}
?>

forum.php

<?php

include_once 'database.php';

class FORUM {

    function __construct($DB_con)
    {
        $this->db = $DB_con;
    }

    public function getColumn() {
        try {
            $query = $this->db->prepare("DESCRIBE posts");
            $query->execute();
        //retrieve the columns inside the table posts
            $forumrows = $query->fetchAll(PDO::FETCH_COLUMN);
        //Output each column  Value
            foreach($forumrows as $forumrow) {
                echo $forumrow . "</br>";
            }
        } catch(PDOException $e) {
            echo $e->getMessage();
        }
    }

public function getColumnUrl() {

}

} //End forum class

$forum = new FORUM($DB_con);
$forum->getColumn();

?>

database.php

<?php

session_start();

$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "dblogin";

try
{
    $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
    $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

include_once 'users.php';
$user = new USER($DB_con);

?>

The rest of the pages just optimise the the functions and a general bootstrap layout for the posts and login pages.


texts: Determine if an image is opaque or transparent

texts:
I wrote an extension method defined for the Image Class (System.Drawing) —
 which returns a Boolean value telling you if the image is opaque or transparent.

The color of each pixel in the image is represented as a 32-bit number: 8 bits each for alpha, red, green, and blue (ARGB). Each of the four components is a number from 0 through 255, with 0 representing no intensity and 255 representing full intensity.

The alpha component specifies the transparency of the color.

If any pixel in the image has a value not equal to 255 in its alpha channel, then the image is not opaque, and therefore transparent.

    public static bool IsOpaque(this Image image)
    {
        var bitmap = new Bitmap(image);
        var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly,
            PixelFormat.Format32bppArgb);
        unsafe
        {
            var p = (byte*)bitmapData.Scan0;
            for (var x = 0; x < bitmap.Width; x++)
            {
                for (var y = 0; y < bitmap.Height; y++)
                {
                    if (p[x * 4 + y * bitmapData.Stride + 3] == 255) continue;
                    bitmap.UnlockBits(bitmapData);
                    return false;
                }
            }
        }
        bitmap.UnlockBits(bitmapData);
        return true;
    }

Concerns:

Can performance be improved at all?
Is it possible to improve readability and reusability without affecting performance?


texts:
After growing tired of all the ways in which a file loop can be broken (find -print | while read) or unreadable (find -exec with complex commands), I think I've managed to build a find template which can handle any and all files which could possibly exist on a Linux system (not so famous last words). Can you find a way to break it, by changing either the test_ variables or the environment? For example, is it possible to mess with file descriptor 9 outside the script so that it won't work?

The only requirement is "sanity." In other words, test_file_name and test_dir_path cannot contain \0 or /, test_file_path cannot contain \0 (or be more than 1 level deep, since mkdir for the sake of the test is run without -p), and /bin/bash must be  a stable version of Bash 4.

#!/bin/bash
# Filenames can contain *any* character except only null (\0) and slash (/);
# here's some general rules to handle them:
#
# $'...' can be used to create human readable strings with escape sequences.
#
# ' -- ' in commands is necessary to separate arguments from filenames, since
# filenames can start with '--', and would therefore be handled as parameters.
# To handle parameters properly (like GNU tools) use `getopt`.
#
# `find` doesn't support this syntax, so we use `readlink` to get an absolute
# path which by definition starts with slash.
#
# The "$()" construct strips trailing newlines, so we have to add a different
# character and then strip it outside the "$()" construct.
#
# `IFS=` is necessary to avoid that any characters in IFS are stripped from
# the start and end of $path.
#
# '-r' avoids interpreting backslash in filenames specially.
#
# '-d '' splits filenames by the null character.
#
# '-print0' separates find output by null characters.
#
# Variables inside '$()' have to be quoted just like outside this construct.
#
# Use process substitution with "<(" instead of pipes to avoid broken pipes.
#
# Use file descriptor 9 for data storage instead of standard input to avoid
# greedy commands like `cat` eating all of it.

set -o errexit
set -o nounset
set -o noclobber

test_file_name=$'--$`\! *@ \a\b\e\E\f\r\t\v\\\"\' \n'
test_dir_path="$test_file_name"
test_file_path="${test_dir_path}/${test_file_name}"

mkdir -- "$test_dir_path"
touch -- "$test_file_path"

absolute_dir_path_x="$(readlink -fn -- "$test_dir_path"; echo x)"
absolute_dir_path="${absolute_dir_path_x%x}"

exec 9< <( find "$absolute_dir_path" -type f -print0 )
while IFS= read -r -d '' -u 9
do
    file_path="$(readlink -fn -- "$REPLY"; echo x)"
    file_path="${file_path%x}"
    echo "START${file_path}END"
done

rm -- "$test_file_path"
rmdir -- "$test_dir_path"


texts:
I want to calculate all sum of all possible paths from root to leaf. Each node has value of an integer number (decimal).

In the following example:

    1
   / \
  2   4
 /    /\
3    5  6

Possible paths are *123, 145, and 146, which adds to 414). In this example, 12 is not a valid path since 2 is not a leaf node.

I did basic tests and it works, and I'm wondering if the code is logically correct, and how I can improve its performance.

class Node:

    def __init__(self, value, left, right):
        self.value = value
        self.left = left
        self.right = right

def sum(node, prefix):
    r1 = 0
    r2 = 0
    if not node:
        return
    if node and not node.left and not node.right:
        return prefix*10+node.value
    if node.left:
        r1 = sum(node.left, prefix*10 + node.value)
    if node.right:
        r2 = sum(node.right, prefix*10 + node.value)

    return r1+r2

if __name__ == "__main__":

    node3 = Node(3, None, None)
    node5 = Node(5, None, None)
    node6 = Node(6, None, None)
    node4 = Node(4, node5, node6)
    node2 = Node(2, node3, None)
    node1 = Node(1, node2, node4)

    print sum(node1, 0)


texts:
Most implementations of FizzBuzz that I've seen rely on 3 modulus operations. Mine does two and a Boolean. (Not implying one is better, just different)

I understand that FizzBuzz is supposedly not to identify great coders, but rather to weed out those that would fail, but I'd like to know if this solution would likely be viewed in positive terms by a potential employer.

<?php
function fizzbuzz($fizz,$buzz,$max=100){
    $output=array();

    for ($i=1; $i <= $max; $i++){
        $output[$i]=''; //If I ignore warnings, this isn't needed.
        if(!($i % $fizz)){
        $output[$i]="Fizz";
        }
        if(!($i % $buzz)){
        $output[$i].="Buzz";
        }
        if(!$output[$i]){
            $output[$i]=$i;
        }
    }
    return $output;
}

foreach(fizzbuzz(3,5) as $out){
    echo $out . "\n"; //or echo $out.'<br>';
}

See it work: Fizzbuzz


texts: Optimize a simple and quick python script for transposing a .csv file


texts:
This was a homework assignment that I'm now done with - I submitted it as is. However the fact that I needed to use the same code twice bugged me... The double code is:

printf("Enter a distance in inches (0 to quit): ");
scanf("%f",&input);

Is there a better way to do the same thing in my loop instead of the double scanf/printf? It does need to quit the program immediately if a 0 is entered.

#include <stdio.h>
int main()
{
    float distance, floatFeet, input;
    int feet;

    printf("Enter a distance in inches (0 to quit): ");
    scanf("%f", &input);
    while (input != 0)
    {
        feet = input/12;
        distance = (input-feet*12);
        floatFeet = input/12;
        printf("%d feet and %f inches or %f feet \n\n", feet, distance, floatFeet);
        printf("Enter a distance in inches (0 to quit): ");
        scanf("%f", &input);
    }
}


texts:
I usually find the .js files to be quite messy and the truth is that mine are even worse than the average as, being soft, I'm not the sharpest tool neither at jQuery nor JavaScript.

I would really appreciate if someone could give me a heads up about improving the readability (and point me bad practices) of this code. I would try to have them into account for other .js files.

$(function () {
    $('form').on("click", "div.toggler", function () {
        $(this).next().slideToggle(300);
    });

$('a.edit').click(function (e) {
    var clickedElement = $(this).parent();
    var url = $('#editForm').data('amp-url');

    $.get(url, { id: parseInt($(this).attr('id')) }, function (result) {
        $("#editForm").html(result);

        // Display edit form just below the "item" clicked
        if ($("#editForm").is(":visible")) {
            $('#editForm').slideToggle(300, function() {
                $("#editForm").appendTo(clickedElement);
                $('#editForm').slideToggle(300);
            });
        } else {
            $("#editForm").appendTo(clickedElement);
            $('#editForm').slideToggle(300);
        }
    }, "html");
    e.preventDefault();
});

// Hide edit form when click outside it
$(document).mouseup(function (e) {
    if ($('#editForm').is(":visible")) {
        var container = $("#editForm");

        if (container.has(e.target).length === 0) {
            container.slideUp(300);
        }
    }
});

(function (a) {

    jQuery.fn.screencenter = function () {
        this.css("position", "absolute");
        this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
        this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
        return this;
    };
})(jQuery);
});

By the way, I have seen here that deferred objects seems cleaner (apart of other considerations). I couldn't make it work, though.


texts: Is my N-drome (variation of palindrome) checking program efficient?

texts:
An N-Drome is a string that is the same forwards and backwards when split into n-character units.
For example, a string would be a 1-drome if and only if it were a standard palindrome.
An example of a 2-drome would be abcdab since its 2-character units are ab, cd, and ab, and its first and last 2-character units are identical.

package ndrome;

import java.util.Scanner;

public class NDrome {
    public static void main(String[] args) {
        System.out.print("enter a string: ");
        Scanner in = new Scanner(System.in);
        String original = in.nextLine();
        System.out.print("enter the n value: ");
        int n = in.nextInt();
        if(n-1>=original.length()){
            System.out.println("Error:N value is greater than string length! exiting...");
            System.exit(0);
        }
        int y = 2;
        here: for (int i = 0, j = original.length() - 1;;) {
            int x = n - 1;
            String a = "", b = "";
            while (x >= 0) {
                if (i >= original.length()) {
                    break here;
                } else {
                    a = a + original.charAt(i);
                    i++;
                    b = b + original.charAt(j - x);
                    x--;
                }
            }
            j=j-n;
            if (a.equals(b)) {
                y = 1;
            } else {
                y = 0;
                break;
            }
        }
        if (y == 1) {
            System.out.print("this is a " + n + "-drome");
        } else if (y == 0) {
            System.out.print("this is not a " + n + "-drome");
        }
    }
}


texts:
I'm creating a class which has a raw pointer member which comes from a C function. In order to make it RAII approved, I just created a method free() that is called on the destructor of this class.
Reading some guidelines I came across that Rule of 5 (and Rule of 3) which, from my understanding, I should also create a bunch of constructors and operator overloadings.
This is what I've done:
/* header */
class SDL2_Font {
 public:
  SDL2_Font() {}
  SDL2_Font(const SDL2_Font& other);  // copy constructor
  SDL2_Font(SDL2_Font&& other);       // move constructor
  ~SDL2_Font() { free(); }

  SDL2_Font& operator=(const SDL2_Font& other); // copy assignment
  SDL2_Font& operator=(SDL2_Font&& other);      // move assignment

  bool loadFont(const std::string& path, int size);
  // more stuff
 private:
  void free();

  TTF_Font* font_ = nullptr;
  FontInfo font_info_ {};
  std::string path_ {};
  int size_ = 0;
}

/* cpp file */
SDL2_Font::SDL2_Font(const SDL2_Font& other) {
  if (other.font_ != nullptr) {
    SDL2_Font::loadFont(other.path_, other.size_);
  }
}

SDL2_Font::SDL2_Font(SDL2_Font&& other): font_{other.font_} {
  other.font_ = nullptr;
}

SDL2_Font& SDL2_Font::operator=(const SDL2_Font& other) {
  if (&other != this && other.font_ != nullptr) {
    SDL2_Font::loadFont(other.path_, other.size_);
  }
  return *this;
}

SDL2_Font& SDL2_Font::operator=(SDL2_Font&& other) {
  if (&other != this) {
    SDL2_Font::free();
    font_ = other.font_;
    other.font_ = nullptr;
  }
  return *this;
}

void SDL2_Font::free() {
  if (font_ != nullptr && TTF_WasInit()) {
    TTF_CloseFont(font_);
    font_ = nullptr;
    path_.clear();
    size_ = 0;
    font_info_ = {};
  }
}

bool SDL2_Font::loadFont(const std::string& path, int size) {
  SDL2_Font::free();
  font_ = TTF_OpenFont(path.c_str(), size);
  if (font_ == nullptr) {
    ktp::logSDLError("TTF_OpenFont");
    return false;
  }
  path_ = path;
  size_ = size;
  SDL2_Font::queryFontInfo();
  return true;
}

This works, or at least I looks to me. But because it's my first time doing this stuff I just want to somebody take a look at it. What do you think? Is the way I implemented the methods/overloads correct?
Or maybe it's a bit overkill? Because I don't intend to copy/move/assign SDL2_Fonts and just for that destructor I had to do all those methods.


texts:
I'm new to JavaScript, and in Java I probably would do this as a singleton. I need something that I can call from anywhere and instantiate only once.

This is what I have done, but I need some advice to write it in the right way in this new prototype based and functional JavaScript.

var winston = require('winston');

var genericLogger = null,
    dbLogger = null,
    viewLogger = null,
    networkLogger = null;

function initLogger() {
    console.log('logger.js > initLogger');

    genericLogger = new (winston.Logger)({
        transports: [
          new (winston.transports.Console)(),
          new (winston.transports.File)({ filename: './log/error.log' })
        ]
    });

    dbLogger = new (winston.Logger)({
        transports: [
          new (winston.transports.Console)(),
          new (winston.transports.File)({ filename: './log/db.log' })
        ]
    });

    viewLogger = new (winston.Logger)({
        transports: [
          new (winston.transports.Console)(),
          new (winston.transports.File)({ filename: './log/view.log' })
        ]
    });

    networkLogger = new (winston.Logger)({
        transports: [
          new (winston.transports.Console)(),
          new (winston.transports.File)({ filename: './log/network.log' })
        ]
    });
}

initLogger();
var Logger = {};

Logger.error = function(n) {
  genericLogger.log('error', n);
};

Logger.info = function(n) {
  genericLogger.log('info', n);
};

Logger.db = function(t, n) {
    if(n) {
        dbLogger.log(t, n);
    } else {
        dbLogger.info(t);
    }
};

Logger.view = function(t, n) {
    if(n) {
        viewLogger.log(t, n);
    } else {
        viewLogger.info(t);
    }
};

Logger.network = function(t, n) {
    if(n) {
        networkLogger.log(t, n);
    } else {
        networkLogger.info(t);
    }
};

module.exports = Logger;

I can call it from anywhere with require, and I expose only few public methods with module.exports and due to the require mechanism there is only one instance.

Is there a cleaner way to do it? More OOP? More functional?


texts: Scala implementation of @rolfl's integer-partitioning algorithm

texts:
While reviewing @Martijn's Distinct sums of integers (finding all combinations of positive integers that sum to a given number), I proposed the following solution:

/** List of non-increasing positive integers */
type Sum = List[Int]

def sums(n: Int): Iterator[Sum] = {
  /** Prepends the head of the stack repeatedly until a total amount has
    * been added.  The leading element of the result is then increased
    * so that the total added is exactly the specified amount.
    */
  @tailrec
  def topUp(amount: Int, stack: List[Int]): List[Int] = {
    if (amount < stack.head)
      (stack.head + amount) :: stack.tail
    else
      topUp(amount - stack.head, stack.head :: stack)
  }

  /** Returns the next partition by popping the first element, increasing the
    * next element, and topping it up to the same total.  Returns None if
    * the input has only one element.
    */
  def advance(partition: Option[Sum]): Option[Sum] = {
    partition.get match {
      case List(n) => None
      case p       => Some(topUp(p.head - 1, p.tail.head + 1 :: p.tail.tail))
    }
  }

  Iterator.iterate(Some(List.fill(n)(1)): Option[Sum])(advance)
          .takeWhile(! _.isEmpty)
          .map(_.get)
}

Example run:

scala> sums(5).foreach(println)
List(1, 1, 1, 1, 1)
List(2, 1, 1, 1)
List(3, 1, 1)
List(2, 2, 1)
List(4, 1)
List(3, 2)
List(5)

I'm pretty satisfied with the algorithm, as it is based on a Java solution that was devised by @rolfl.

However, I'm not happy about the way I've expressed it in Scala, particularly with regards to the termination of the iterator.

Is there a way to write topUp without explicit recursion, yet still avoiding ::: concatenation?
Is the : Option[Sum] type annotation on Some(List.fill(n)(1)) avoidable?
There seems to be a lot of Option / None / Some noise in advance.  Is there a better way to handle the termination condition?  (Perhaps by using lift?)
Similarly, Iterator.iterate(…)(…).takeWhile(! _.isEmpty).map(_.get) seems cumbersome.  Is there a less verbose way to say "repeatedly apply this function until exhausted" using the standard Scala library?

For the record, instead of advance and Iterator.iterate(…).takeWhile(…).map(…), I had previously written it this way, using explicit recursion:

def makeSums(partition: Sum): Stream[Sum] = {
  partition #:: (partition match {
    case List(n) => Stream.Empty
    case p       => makeSums(topUp(p.head - 1, p.tail.head + 1 :: p.tail.tail))
  })
}

makeSums(List.fill(n)(1))

… which returned a Stream[Sum] instead of an Iterator[Sum].  Note that it's not tail-recursive.  (I also tried to write it as a self-referential stream, but couldn't figure out how to terminate it.)

I think that, despite being longer, the Iterator.iterate(…) solution is better because it decouples the "repeated application" aspect from the "produce the next result" aspect.  Your opinion on this matter would be appreciated.


texts: Systems management using SSH for my school

texts:
I wrote this script in order to generate a hosts.txt file with the IP addresses of the laptops in my school.

Each laptop is assigned a number, and their IP addresses are assigned to them with the template "192.168.0.x". X being the computer's number + 10. All these computers are running Arch Linux with XFCE4, custom tailored to aid in education. Each laptop is setup with SSH and the Teacher, (me), has the ability to ssh into any machine and execute any command I deem necessary.

Up until recently, I would SSH into the machines individually and install programs one-by-one. Now I use a program called PSSH (Parallel SSH) to connect to certain machines simultaneously and perform my commands. I only find one issue with this arrangement, all the IP addresses are stored in a file called, you guessed it, hosts.txt.

Now, as you can imagine, this gets quite cumbersome when dealing with 70 different addresses, and I would rather not have to type all the addresses by hand. So I made this script to generate a hosts file based off the computer numbers I choose. Selecting all the machines is now as easy as typing 'all'.

addresses = []
nums = []
run = True

def rem_dupl(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

while run:
    x = str(input("Computer numbers: "))

    if x == 'done':
        run = False
    elif x == 'all':
        nums = [x for x in range(1, 70)]
        run = False
    elif int(x) > 0 and int(x) < 70:
        nums.append(x)
    else:
        print "Out of range"
else:
    nums_finished = rem_dupl(nums)

    for i in nums_finished:
        addresses.append("192.168.0." + str((int(i) + 10)))

    temp = open('hosts', 'w').close()

    file = open('hosts.txt', 'w')
    for item in addresses:
        print>>file, item

   file.close

Any thoughts, constructive criticism, apparent issues, or redundancies?


texts:
Is this return style acceptable? Would the code be more readable if I assigned the MonthDay.parse() return value to a variable and returned that variable on the last line?

Also, is it a bad idea to both log and rethrow inside a catch block?

/**
 * Parses showing date from the header text.
 *
 * @throws PageStructureException if the date string does not conform to the expected format
 */
public MonthDay parseShowingDate( String date ) throws PageStructureException {
    Preconditions.checkNotNull( date );

    DateTimeFormatter matDTF = DateTimeFormat.forPattern( DATE_FORMAT );
    String dayAndMonth = removeDayOfWeek( date );
    try {
        return MonthDay.parse( dayAndMonth, matDTF );
    } catch ( IllegalArgumentException iae ) {
        logger.error( "Could not parse MAT date {}, expected format [{}].", date, DATE_FORMAT );
        throw new PageStructureException( iae );
    }
}


texts:
At a JavaScript test for a job, I was asked the question below. I believe there has to be a better way to accomplish the same result, but I couldn't find any. If some JavaScript geek would take a look and suggest a better approach I would really appreciate it:

  Given a positive integer greater or equal to 1, write a function f(n) to calculate as efficiently as possible the sum of the first 1 to n powers of 2. Do no use any buit-in function to calculate the power of a number.
  Example: if n = 3:

  $$ f(3)=2^1+2^2+2^3=2+4+8=14 $$

jsFiddle

function solution (n) {
    var t='';
    var q='';
    for (var i=1;i<=n;i++) {
        q='';
        for (var j=1;j<=i;j++) {
            q=q+'2*';
        }
        q=q+1;
        t=t+'('+q+')+';
    }
    t=t.substr(0,t.length-1);
    return eval(t);
}


texts: Checking whether one string is a rotation of another

texts:
Given a method isSubstring, two strings s1 and s2, check whether s1 is a rotation of s2 using only one call to isSubstring.

Any comments on the code below?

I would like to check the complexities as well:

For isSubstring:

runtime: \$O(n^2)\$
memory: in place

For isRotation:

runtime: \$O(n^2)\$
memory: \$O(n)\$

import static org.junit.Assert.*;

import org.junit.Test;

public class Solution {
  // Find whether string s1 is a rotation of string s2
  // using only one call to isSubstring

  static boolean isSubstring(String s1, String s2) {
    // return true if s1 is a substring of s2
    // false otherwise
    int n1 = s1.length();
    int n2 = s2.length();
    for (int i = 0; i < n2; i++) {
      if (i+n1>n2){
        return false;
      }
      else if (s1.equals(s2.substring(i,i+n1))) {
        return true;
      }
    }
    return false;
  }

  static boolean isRotation(String s1, String s2) {
    // return true if s2 is a rotation of s1
    // false otherwise

    // concatenate all the rotated strings of s1
    StringBuffer allRotated = new StringBuffer();
    int n1 = s1.length();
    int n2 = s2.length();
    if (n1 != n2) {
      return false;
    }
    allRotated.append(s1);
    for (int i = n1 - 1; i > 0; i--) {
      allRotated.append(s1.substring(i) + s1.substring(0, i));
    }

    // Return true if s2 is a substring of allRotated
    String rotated = allRotated.toString();

    return isSubstring(s2, rotated);
  }

  @Test
  public static void abcTest() {
    String abc = "abc";
    String cab = "cab";
    String bca = "bca";

    assertTrue(isRotation(abc, cab));
    assertTrue(isRotation(abc, bca));
  }

  @Test
  public static void falseTest(){
    String abc = "abc";
    String cba = "cba";
    assertFalse(isRotation(abc,cba));
  }

  @Test
  public static void evenTest(){
    String abcd = "abcd";
    String dcba = "dcba";
    assertFalse(isRotation(abcd,dcba));
  }

  @Test
  public static void identityTest(){
    String aaaa = "aaaa";
    assertTrue(isRotation(aaaa,aaaa));
  }
  public static void main(String[] args) {
    abcTest();
    falseTest();
    evenTest();
    identityTest();
  }

}


texts:
The code is an implementation of the Gauss–Seidel method. I would like a general review of the code.

PS: I use code::blocks IDE

//generalized code for gauss seidal iteration method
#include<stdio.h>
#include<malloc.h>

#define chk_end 0.01

int row_lim=0,col_lim=0;

float** partial_pivot(float** mat,int row,int col);//finds the pivot of matrix
int condition(float* result,float* temp,int row);//checks the terminating condition
float* final_result(float** mat,float* result,int row,int col);//calculates final result
float** create_mat(float** mat,int row,int col);//creates a matrix of row X col
float** feed_mat(float** mat,int row,int col);//inputs value in matrix
void disp_mat(float** mat,int row,int col);//displays matrix

float** partial_pivot(float** mat,int row,int col)
{
 float pivot;
 int i=0,j=0,k=0,l=0;

 if(row_lim<row)
 {
  for(i=0,j=col_lim;i<row-1;i++)
  {
   for(l=row_lim;l<row-i-1;l++)
   {
   if(mat[l][j]<mat[l+1][j])
   {
    for(k=0;k<col;k++)
    {
     pivot=mat[l+1][k];
     mat[l+1][k]=mat[l][k];
     mat[l][k]=pivot;
    }
   }
   }
  }
 row_lim++;
 col_lim++;
 partial_pivot(mat,row,col);
 }

 return mat;
}

int condition(float* result,float* temp,int row)
{
 int i=0,flag = 0;

 for(i=0;i<row;i++)
 {
 if(result[i] > temp[i])
 {
  if((result[i]-temp[i]) < chk_end)
  {
   flag = 1;
  }
  else
  {
   flag = 0;
   break;
  }
 }

 else
 {
  if((temp[i]-result[i]) < chk_end)
  {
   flag = 1;
  }
  else
  {
   flag = 0;
   break;
  }
 }
 }

 return flag;
}

float* final_result(float** mat,float* result,int row,int col)
{
 int k=0,i=0,j=0;
 float T = 0;
 float *temp;

 temp=(float*)malloc((row)*sizeof(float));//Edit: row-1 changed to row
 for(i=0;i<row;i++)
 {
  temp[i] = 0;
 }

 printf("Processing result ... \n");

 do
 {
   for(k=0;k<row;k++)
   temp[i] = result[i];    //was a logical error, sorry
   {
   for(i=0;i<row;i++)
   {
    for(j=0;j<(col-1);j++)
    {
     if(i==j)
     {

     }
     else
     {
      T += (mat[i][j])*(temp[j]);
     }
    }
    result[i] = ((mat[i][col-1] - T)/(mat[i][i]));
    //temp[i] = result[i];
    T=0;
   }
  }
 }
 while(condition(result,temp,row) == 0);

 free(temp);

 return result;
}

float** create_mat(float** mat,int row,int col)
{
    int i=0;

     mat=(float**)malloc((row)*sizeof(float*));//Edit: row-1 changed to row
     if(mat)
     {
        for(i=0;i<row;i++)
        {
            mat[i]=(float*)malloc((col)*sizeof(float));//Edit: col-1 changed to col
        }
     }

    return mat;
}

float** feed_mat(float** mat,int row,int col)
{
    int i=0,j=0;

    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("Enter mat[%d][%d] element:\n",i,j);
            scanf("%f",&mat[i][j]);
        }
    }

    return mat;
}

void disp_mat(float** mat,int row,int col)
{
    int i=0,j=0;

     for(i=0;i<row;i++)
     {
        for(j=0;j<col;j++)
        {
            printf("\t%f",mat[i][j]);
        }
        printf("\n");
     }

}

int main()
{
 float **mat,*result;
 int i=0,row=0,col=0;

 mat=NULL;

 printf("Enter the number of Equations :\n");
 scanf("%d",&row);
 col=row+1;

 result = (float*)malloc((row)*sizeof(float));//Edit: row-1 changed to row
 for(i=0;i<row;i++)
 {
  result[i] = 0;
 }

 mat=create_mat(mat,row,col);

 printf("Enter the values in the %d x %d matrix:\n",row,col);
 mat=feed_mat(mat,row,col);

 printf("matrix entered by you:\n");
 disp_mat(mat,row,col);

 mat=partial_pivot(mat,row,col);

 printf("pivoted matrix entered:\n");
 disp_mat(mat,row,col);

 result = final_result(mat,result,row,col);

 printf("\nResult is : \n");
 for(i=0;i<row;i++)
 {
  printf("  x[%d]   %f",i,result[i]);
 }

 for(i=0;i<row;i++)
 {
     free(mat[i]);
 }
 free(mat);

 free(result);

 return 0;
}


texts: A more efficient way of extracting a name from a string?

texts:
Here is some code that reads Active Directory to get a person's manager and parses the result for the managers name. It omits the remaining information. I was just wondering if there might be some more efficient way of doing this instead of the code I am currently using.

var Manager = (string)UserDirectoryData.Properties["manager"].Value;
var StartIndex = Manager.IndexOf("=");
var EndIndex = Manager.IndexOf(",");
StartIndex++;
EndIndex--;
var Length = EndIndex - StartIndex;
Manager = Manager.Substring(StartIndex, Length);

The string returned in the first line of code is in this format:

  CN=Joseph Rod,OU=LaptopUser,OU=Users,DC=Company,DC=local

The goal is to just get the name and drop the rest. As the Name length will vary and my RegEX is rusty I could not come up with a working RegEX for this or any other way in C# to pull the name.

Edit:

Buy more efficient I mean faster run times and less resource utilization. This same code will be used in multiple spots in loops of up to 500 iterations (and it will continue to grow as the company does).


texts: Class to verify if a rectification is upgradable

texts:
Today I encountered something that I have been wondering about in the past a few times before. How can I refactor a method that has this format:

private boolean isRectificationUpgradable(Rectification rectification) {

    final boolean validType = rectification.getType() == RectificationType.VH
            || rectification.getType() == RectificationType.COL;

    if (!validType) {
        return false;
    }

    if (rectification.getStatus() != RectificationStatus.IN_PROGRESS && rectification.getStatus() != RectificationStatus.OPEN) {
        return false;
    }

    if (rectification.getVehicle() == null) {
        return false;
    }

    final List<CarPassCertificate> certificates = rectification.getVehicle().getCertificates();

    if (CollectionUtils.isEmpty(certificates)) {
        return false;
    }

    CarPassCertificate validCertificate = getValidCertificate(rectification);

    if (validCertificate == null) {
        return false;
    }

    return true;
}

When a rectification is created it has the status "open". An employee indicates that he started to handle it by putting it in the status "in progress".

The upgradable in this context means that sometimes the creator chose a certain type for the rectification, when in fact he could have picked a more accurate other type. In this case someone in the application can "upgrade" this rectification to the more specific type.

In code, this "upgraded" type is not modeled as another class as it is not really an upgrade, it always stays the same Rectification class and some shared additional fields are set to make it a bit more specific.

I think it is pretty readable but as more validations are added it can become very long. Any ideas?


texts: Groupby Count on user defined time periods pandas


texts: Determine if two strings with no repeating characters are permutations of each other

texts:
I've made a short program to determine if a string is permutation of another string.
Example input/output :

a) 123, 112 <- False
b) 123, 321 <- True
c) 112, 121 <- these don't count as permutations since they have duplicate characters

    private static void Main()
    {
        string a = Console.ReadLine();
        string b = Console.ReadLine();
        Console.WriteLine(IsPermutation(a, b));
        Console.ReadKey();
    }

    private static bool IsPermutation(string first, string second)
    {
        if (first.Length != second.Length)
        {
            return false;
        }
        for (int i = 0; i < first.Length; i++)
        {
            if (first.Count(t => t == second[i]) != second.Count(t => t == first[i]))
            {
                return false;
            }
        }
        return true;
    }

I wonder if it can be optimized.


texts: Generating random numbers from thread timing in C++

texts:
I have the following code blocks that generate apparently random numbers by using thread timing variations.

I am looking for a general code review, and a specific focus on whether the results are "true random numbers".

For computers with more than two CPUs

#include<chrono>
#include<iostream>
#include<thread>
using namespace std;

#define Mili 7
#define Base 7
#define Thrs 2

typedef unsigned char      Num;
typedef unsigned long long Out;

volatile Out out,tmp;

void inline thr(Num const num){
 while(true)
  out=out*Base+tmp,tmp=tmp*Base+num;
}

int main(){
 thread ths[Thrs];
 for(Num i=0;i<Thrs;++i)
  ths[i]=thread(thr,i);
 this_thread::sleep_for(chrono::milliseconds(Mili));
 while(true)
  cout.write((char*)&out,sizeof(out));
}

For computers with two CPUs

#include<iostream>
using namespace std;

#define Base 7
#define Iter 53

typedef unsigned char      Num;
typedef unsigned long long Out;

volatile Out out,tmp;

int main(){
 for(Num i=0;i<Iter;++i)
  #pragma omp parallel for schedule(runtime)
  for(Num num=0;num<Iter;++num)
   out=out*Base+tmp,tmp=tmp*Base+num;
 while(true){
  #pragma omp parallel for schedule(runtime)
  for(Num num=0;num<Iter;++num)
   out=out*Base+tmp,tmp=tmp*Base+num;
  cout.write((char*)&out,sizeof(out));
 }
}

For computers with one CPU:

#include<chrono>
#include<iostream>
#include<thread>
using namespace std;

#define Nano 1
#define Mili 7
#define Base 7
#define Thrs 2

typedef unsigned char      Num;
typedef unsigned long long Out;

volatile Out out,tmp;

void inline thr(Num const num){
 while(true)
  out=out*Base+tmp,tmp=tmp*Base+num;
}

int main(){
 thread ths[Thrs];
  for(Num i=0;i<Thrs;++i)
   ths[i]=thread(thr,i);
 this_thread::sleep_for(chrono::milliseconds(Mili));
 while(true)
  cout.write((char*)&out,sizeof(out)),
  this_thread::sleep_for(chrono::nanoseconds(Nano));
}


texts:
I've been trying to optimize this while making it readable. Thoughts?

  The sequence of triangle numbers is generated by adding the natural
  numbers.  So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 +
  7 = 28.  The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have over five
  divisors.

  What is the value of the first triangle number to have over five
  hundred divisors?

@triangle_number = 441
@factors = []
@right_of_tree = []
@left_of_tree = []

def find_triangle_number_with_500_factors
  natural_number = 1000
  while !over_500_factors?
    @factors = []
    @right_of_tree = []
    @left_of_tree = []
    triangle_number_generator(natural_number)
    find_factors_with_a_factor_tree
    natural_number += 1
  end
  p @triangle_number
end

def triangle_number_generator(natural_number)
  @triangle_number = natural_number*(natural_number+1) / 2
end

def find_factors_with_a_factor_tree
  create_prime_factor_tree(@triangle_number)
  find_combinations_in_left_of_tree
end

def find_combinations_in_left_of_tree
  last_prime_factor = @right_of_tree.last
  @left_of_tree.push(last_prime_factor)
  (1..@left_of_tree.length).each do |combination_size|
    cxget_combinations(@left_of_tree, combination_size)
    combinations.each do |arr|
      @factors << arr.inject(:*)
    end
  end
end

def get_combinations(arr, combination_size)
  arr.combination(combination_size).to_a.uniq
end

def create_prime_factor_tree(number)
  until number <= 1
    factor = get_initial_divisor(number)
    if factor
      @right_of_tree.push(number / factor)
      @left_of_tree.push(factor)
      number = number / factor
    else
      break
    end
  end
end

def get_initial_divisor(number)
  2.upto(number / 2) do |possible_factor|
    if number % possible_factor == 0
      return possible_factor
      break
    end
  end
  return nil
end

def over_500_factors?
  return true if @factors.size + @right_of_tree.size >= 498
end

Benchmark.bm do |bm|
  bm.report { find_triangle_number_with_500_factors}
end


texts: SQL update scripts taking too much memory and doesn't free it up

texts:
I have this piece of code that executes update scripts on the database. I have 20 .sql files that contains about 400 update scripts. The overall size of the files is around 60MB. When I execute all the update scripts, it eats up about 400 MB of RAM and doesn't free it. I'm looking for ways to optimize this code.

private void ExeCuteCommand(SqlConnection conn, string script, bool flag)
    {
        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        command.CommandType = CommandType.Text;
        command.CommandText = script;

        if (flag)
            command.ExecuteNonQuery();
    }

EDIT:

This is the calling method, basicall what it does is loop through the files, get the contents and pass the contents to the ExecuteCommand method.

private void ExecuteUpdateScripts(SqlConnection conn)
    {
        int step = 1;
        foreach (string update in Directory.GetFiles(scriptDirectory, @"SCRIPT UPDATE ??.sql"))
        {
            string updateScript = File.ReadAllText(updateSQL);
            ExeCuteCommand(conn, updateScript, true);

            step++;
        }
    }

I have looked at the Visual Studio profiler and this is the line the consumes a lot of memory command.ExecuteNonQuery();


texts: Function to check empty cells found or not in Datagrid

texts:
I want to check if any empty cells found or not in a Datagridview when save data to database, so I've written this function:

Public Function IsDataGridViewEmpty(ByRef dataGridView As DataGridView) As Boolean
Dim isEmpty As Boolean
isEmpty = False
For Each row As DataGridViewRow In dataGridView.Rows
    For Each cell As DataGridViewCell In row.Cells
        If Not String.IsNullOrEmpty(cell.Value) Then

            If Not String.IsNullOrEmpty(Trim(cell.Value.ToString())) = True Then
                Dim d = Trim(cell.Value.ToString())
                isEmpty = False

            End If
        Else
            isEmpty = True
            Exit For
        End If
    Next
Next
Return isEmpty
End Function

The code is working now, but are any improvements needed? Is there any way to do this without a foreach loop?

Function calling:

 Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If IsDataGridViewEmpty(Me.DataGridView1) = True Then
            MsgBox("Empty Cells Found PLease Check!")
        End If
    End Sub

Source

I changed the code from the source website, so see the difference with my code and the source link.

Can anyone explain why we use By ref in a function parameter?

 Public Function IsDataGridViewEmpty(ByRef dataGridView As DataGridView) As Boolean


texts: Getting multiple table schema and returning them, using one helper method

texts:
I want to get two distinct sets of schema from a database without having to create multiple Connection/PreparedStatement/ResultSet objects.

Currently, I have a helper method that queries the database, gets each individual schema, and then returns them together in one ArrayList - please refer to the code below.

private ArrayList<ArrayList<?>> getAttributesAndGroups() {
    ArrayList<ArrayList<?>> retList = new ArrayList<ArrayList<?>>();

    Connection conn = null;
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection(jdbcUrl, userId, password);

        ArrayList<Attribute> listAttrs = new ArrayList<Attribute>();
        String query = "select aid, aname from tbl_attributes order by aid";
        PreparedStatement ps = conn.prepareStatement(query);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            int aid = rs.getInt(1);
            String aname = rs.getString(2);
            Attribute attr = new Attribute(aid, aname);
            listAttrs.add(attr);
        }
        retList.add(listAttrs);

        ArrayList<Group> listGroups = new ArrayList<Group>();
        query = "select gid, gname from tbl_groups order by gid";
        ps = conn.prepareStatement(query);
        rs = ps.executeQuery();
        while (rs.next()) {
            int gid = rs.getInt(1);
            String gname = rs.getString(2);
            Group grp = new Group(gid, gname);
            listGroups.add(grp);
        }
        retList.add(listGroups);

        rs.close();
        ps.close();

    } catch (Exception e) {
        log.error("Exception", e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                //
            }
        }
    }

    return retList;
}

Where I call my helper method, I do the following:

    ArrayList<ArrayList<?>> lists = getAttributesAndGroups();

    ArrayList<Attribute> listAttrs = (ArrayList<Attribute>) lists.get(ATTRIBUTES);
    request.setAttribute("listAttrs", listAttrs);

    ArrayList<Group> listGroups = (ArrayList<Group>) lists.get(GROUPS);
    request.setAttribute("listGroups", listGroups);

    request.getRequestDispatcher("addUser.jsp").forward(request, response);

(ATTRIBUTES and GROUPS are simple integer constants representing 0 and 1 respectively.)

However, my code is giving me warnings of Type safety: Unchecked cast from ArrayList<capture#1-of ?> to ArrayList<Attribute> (ditto for the other line).

Is there a better approach for what I want to do?


texts:
I'm a beginner in js and jQuery. I wrote animation tab-slider. But my code is bad. What should I improve? What should I do to make the code less cumbersome?

var slideTabImg = $('.js-slide-tabImg');
var firstTab = $('#js-first-tabImg');
var secondTab = $('#js-second-tabImg');

$('#js-first-tab').click(function(){
    $(this).next().removeClass('m-slideTa href');
    $(this).addClass('m-slideTab-href');

    slideTabImg.removeClass('m-slide-tabImg_active');
    slideTabImg.removeClass('m-secondTab-active m-firstTab-active');

    secondTab.addClass('m-secondTab-active');
    firstTab.addClass('m-slide-tabImg_active m-firstTab-active');
});

$('#js-second-tab').click(function(){
  $(this).prev().removeClass('m-slideTab-href');
  $(this).addClass('m-slideTab-href');

   slideTabImg.removeClass('m-secondTab-active m-firstTab-active');
  slideTabImg.removeClass('m-slide-tabImg_active');

  secondTab.addClass('m-slide-tabImg_active m-firstTab-active');
  firstTab.addClass('m-secondTab-active');
});
.slide-tabImages {
 position: relative;
 width: 100%;
 max-width: 860px;
 margin: 0 auto;
}
.slide-tabImg {
 position: absolute;
}
.m-slide-tabImg_active {
 top: 40px;
 left: -40px;
 z-index: 5
}
.slide-tab {
 padding: 30px 0;
}
.slideTab-href {
 font-size: 20px;
 color: #000;
 text-transform: uppercase;
 font-weight: normal;
 cursor: pointer;
 margin: 0 8px;
}
.slideTab-href:hover {
 text-decoration: none;
}
.slideTabLink {
 padding-top: 80px;
}
.m-slideTab-href {
 border-bottom: 1px dashed;
 }

.m-secondTab-active {
  animation: secondTab-animation 2.5s forwards;
}

.m-firstTab-active {
  animation: firstTab-animation 2.5s forwards;
}

@keyframes secondTab-animation {
  49% {
    transform: translateX(-120px);
  }

  to {
    transform: translateX(0);
    z-index: 1;
  }
}

@keyframes firstTab-animation {
  49% {
    transform: translateX(120px);
  }

  to {
    transform: translateX(0);
  }
}

 New
 Old


texts:
I'm creating an online calculator to get the average grade of different tests my students take and also the final grade. I wonder if you see any problems in this update or any way to improve it:

var inputs = document.getElementsByTagName('input');
var i;

function calculateAverage(tests) {
  var total = 0;
  var count = 0;
  for (i = 0; i < tests.length; i++) {
    if (tests[i].value) {
      total += Number(tests[i].value);
      count++;
    }
  }
  if (!count) {
    return 'Please enter a grade.';
  }
  return 'Average: ' + (total / count).toFixed(1);
}
document.getElementById('calculator').addEventListener('click', function() {
  var physicsTests = document.getElementById('physics').getElementsByTagName('input');
  var physicsAverage = document.getElementById('physicsAverage');
  physicsAverage.value = calculateAverage(physicsTests);

  var historyTests = document.getElementById('history').getElementsByTagName('input');
  var historyAverage = document.getElementById('historyAverage');
  historyAverage.value = calculateAverage(historyTests);

  var finalGrade = document.getElementById('finalGrade');
  var averagesTotal = physicsAverage.value.slice(9) * 3 + historyAverage.value.slice(9) * 2;
  if (averagesTotal || averagesTotal == 0) {
    finalGrade.value = 'Final grade:' + (averagesTotal / 5).toFixed(1);
  } else {
    finalGrade.value = '';
  }
});
document.getElementById('resetter').addEventListener('click', function() {
  var form = document.getElementById('form');
  var edited = calculateAverage(inputs);
  if (edited != 'Please enter a grade.' && confirm('Your changes will be lost.\nAre you sure you want to reset?')) {
    form.reset();
  }
});
window.addEventListener('beforeunload', function(event) {
  var edited = calculateAverage(inputs);
  if (edited != 'Please enter a grade.') {
    event.returnValue = 'Your changes may be lost.';
  }
});
<form id="form">

    Physics:
    <input type="number">
    <input type="number">
    <input type="number">
    <output id="physicsAverage"></output>

    History:
    <input type="number">
    <input type="number">
    <input type="number">
    <output id="historyAverage"></output>

  <button type="button" id="calculator">Calculate</button>
  <button type="button" id="resetter">Reset</button>
  <output id="finalGrade"></output>
</form>

P.S. I've made changes to the previous code to shorten the script and added some new features such as a reset button.

Note

Please review the final product made thanks to the hints I've received in this thread.


texts:
I'm just wondering Is there any ways I could simplify the following code without making it too difficult:

Actually I want to extract specific year data from content node based on lastNumberOfYears variable.

Example: Content array has 2019,2018,2017,2016 years data and lastNumberOfYears value is 2 then output should have only 2019, 2018 data. other scenario is if content array is like 2020, 2014, 2013 then output should have 2020, 2014 data (if lastNumberOfYears value is 2)

My solution

Step 1 : Define predefined data

const content = [{
    "document": "/content/path/document1.pdf",
    "date": "2020-02-20"
  }, {
    "document": "/content/path/file.docx",
    "date": "2019-02-20"
  }, {
    "document": "/content/abc/document2.docx",
    "date": "2018-06-20"
  }, {
    "document": "/document/order/order.pdf",
    "date": "2020-06-20"
  }, {
    "document": "/content/order/update.pdf",
    "date": "2018-03-21"
  }, {
    "document": "/content/author/author.pdf",
    "date": "2017-03-21"
  }, {
    "document": "/content/path/dummy.pdf",
    "date": "2016-02-15"
  }, {
    "document": "/content/dummy/dummy.docx",
    "date": "2015-12-15"
}];

let lastNumberOfYears = 2;
let selectedYearArray = [];

Step 2: Convert content data into year base data

const result = content.reduce((current, value) => {
  const dateYear = new Date(value.date).getFullYear();
  current[dateYear] = current[dateYear] || [];
  current[dateYear].push(value);
  return current;
}, {});

/*
output is like
{
   "2015":[{...}],"2016":[{}],..."2020":[{}, {}]
}
*/

Step 3: Put specific year data in same order for result array

Object.values(result).forEach(value => value.reverse());

Step 4: Create Year array from object key

const yearsArray = Object.keys(result).sort((first, second) => (first > second ? -1 : 1));

Step 5: Create last number of year array using lastNumberOfYears variable
Step 6: Extract Step 5 data from result array define in step 3
Step 7: Remove year key and join all array value of Step 6 outcome

if (yearsArray.length !== 0 && lastNumberOfYears <= yearsArray.length) {
  for (let i = 0; i < lastNumberOfYears; i++) {
    selectedYearArray.push(yearsArray[i]);
  }

  /*
    Step 5: console.log(selectedYearArray);
  */

  const filteredResult = Object.keys(result)
    .filter(key => selectedYearArray.includes(key))
    .reduce((obj, key) => {
      obj[key] = result[key];
      return obj;
    }, {});

  /*
    Step 6: console.log(filteredResult);
  */

  contentObj = [].concat.apply([],Object.values(filteredResult));

  /*
    Step 7:
  */
  console.log(contentObj.reverse());
}

Output:

[{
    "document": "/content/path/document1.pdf",
    "date": "2020-02-20"
}, {
    "document": "/document/order/order.pdf",
    "date": "2020-06-20"
}, {
    "document": "/content/path/file.docx",
    "date": "2019-02-20"
}]


texts: Flip coin Game in an Object oriented way

texts:
I started out creating a simple game in an Object Oriented way to practice.

The rules are pretty simple

There are two players
You let one player choose if they want Heads or Tails.
You assign the leftover option to the other player.
You simulate a coin flip and say who won that game.

More than the logic, naming conventions etc. I was looking at the most object-oriented way of structuring code to implement this from this exercise.

I created three classes for this, the Player, Coin and CoinGame and an enum as well.

The Player Class

enum CoinOptions
{
    Heads, Tails
}

internal class Player
{
    public string playerName { get; set; }
    public CoinOptions coinOption { get; set; }
    public Player(string name)
    {
        playerName = name;
    }
    public CoinOptions chooseCoinOption()
    {

        //Simulate the user picking one option

        //Console.WriteLine("Chose a coin option");
        //Console.ReadKey();

        //Lets Assume they pick Heads
        coinOption = CoinOptions.Heads;

        return coinOption;
    }
    public void setCoinOption(CoinOptions opponent)
    {
        coinOption = opponent == CoinOptions.Heads ? CoinOptions.Tails : CoinOptions.Heads;
    }
    public bool didPlayerWin(CoinOptions winningFlip)
    {
        return winningFlip == coinOption;
    }
}

Coin class

class Coin
{
    private Random random;
    public Coin(Random rand)
    {
        random = rand;
    }
    public CoinOptions flipCoin()
    {

        double probability = random.NextDouble();
        return probability > 0.5 ? CoinOptions.Heads : CoinOptions.Tails;
    }
}

CoinGame Class

internal class CoinGame
{
    private List<Player> players = new List<Player>(Enumerable.Repeat(default(Player), 2));
    private Coin coin;
    private CoinOptions winningFlip;

    public CoinGame(Coin coinUsed, List<string> playerNames = null)
    {
        for (int i = 0; i < players.Count; i++)
        {
            var playerName = playerNames != null ? playerNames[i] : $"player{i}";
            players[i] = new Player(playerName);
        }
        coin = coinUsed;
    }

    public void playCoinFlip()
    {
        int chooseIndex = new Random().Next(2);
        int applyIndex = chooseIndex == 0 ? 1 : 0;
        var selectedOption = players[chooseIndex].chooseCoinOption();
        players[applyIndex].setCoinOption(selectedOption);
        winningFlip = coin.flipCoin();
    }
    public void gameResult()
    {
        foreach (var player in players)
        {
            if(player.didPlayerWin(winningFlip))
            {
                Console.WriteLine($"The player {player.playerName} won choosing {player.coinOption}");
            }
            else
            {
                Console.WriteLine($"The player {player.playerName} lost choosing {player.coinOption}");
            }
        }
    }

}

And the calling code

class Program
{
    static void Main(string[] args)
    {
        var coin = new Coin(new Random(12312));
        var coinGame = new CoinGame(coin);
        coinGame.playCoinFlip();
        coinGame.gameResult();
        Console.ReadKey();
    }
}

My main concern is if there is a better strategy to

Initialize the players in the game
Allowing a random user to choose their coin option while simultaneously setting the other user with the leftover option


texts:
I'm attempting to learn more about Java and have created a method that takes a text file with stdout (space separated file) and converts it to a CSV file.
I was attempting to use standard Java SE version 8.

Is there a better, more efficient, way of doing this?

The logic is:

Open file
Read file by line into string so it can be split
Split string removing spaces, back into array
Join with StringJoiner using ,
Convert back to string to remove leading ,
Update final array to be returned

Method to open file:

public void OpenFile(String fileName)
{
    try
    {
        subFile = new Scanner (new File(fileName));
    }
    catch (Exception e)
    {
        System.out.println("File dosn't exist.");
    }
}

Method to convert:

    public String[] TextToCsvArray(String[] fileArray)
{
    int i=0;
    while(subFile.hasNext())
    {
        String line = subFile.nextLine();
        String[] split = line.split("\\s+");
        StringJoiner joiner = new StringJoiner(",");

        for (String strVal: split)
            joiner.add(strVal);

        line = joiner.toString();
        line = line.startsWith(",") ? line.substring(1) : line;
        fileArray[i++] = line;
    }
    return fileArray;
}


texts: HttpRequest class using AsyncTask for Android application

texts:
I am using the following class to retrieve a http response, which contains data for my Android App. Everything works fine, but there is a performance issue. I get the following warning when requesting this class:

  Skipped 36 frames!  The application may be doing too much work on its main thread.

I used an AsyncTask to run the network connection on a different thread, but it is still saying I'm doing too much work on the main thread. Is there something you can point out to me that is slowing down my program?

package com.lakshan.gamematch.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

public class HttpRequest {

String url_to_task = "";
String string_result = "hasn't returned a value";

        public String getFromURL (String url) {
            url_to_task = url;
            new MyTask().execute();
            while (string_result.equals("hasn't returned a value")) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return string_result;
        }

        private class MyTask extends AsyncTask <Void, Void, Void> {
            @Override
            protected Void doInBackground(Void... params) {
                InputStream is = null;

                //Download JSON data from url
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(url_to_task);
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    Log.e("entity", entity.getContent().toString());

                } catch (Exception e) {
                    Log.e("log_tag", "Error in http connection " + e.toString());
                }

                //Convert response to string
                try {
                    BufferedReader reader = new BufferedReader (new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");

                    }
                    is.close();
                    string_result = sb.toString();
                } catch (Exception e) {
                    Log.e("log_tag", "Error converting result" + e.toString());
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
            }
        }
}


texts:
I'm pulling the values from the following XML based on the attribute name.

<DataRow>
  <DataItem name="SYMBOL">MSFT-US</DataItem>
  <DataItem name="NAME">Microsoft Corporation</DataItem>
  <DataItem name="CUSIP">59491812311</DataItem>
  <DataItem name="SEDOL">2588CFA</DataItem>
  <DataItem name="CURRENCY">USD</DataItem>
  <DataItem name="DATE">2018-10-05</DataItem>
  <DataItem name="PRICE">100.25</DataItem>
</DataRow>

Here's my working code to select the values into a list:

IEnumerable<XElement> xDoc = XDocument.Parse(xmlString).Descendants("DataRow");
var query = from item in xDoc
        let symbol = (item.Elements("DataItem")
            .Where(i => (string)i.Attribute("name") == "SYMBOL").Select(i => i.Value)).FirstOrDefault()
        let compName = (item.Elements("DataItem")
            .Where(i => (string)i.Attribute("name") == "NAME").Select(i => i.Value)).FirstOrDefault()
        let cusip = (item.Elements("DataItem")
            .Where(i => (string)i.Attribute("name") == "CUSIP").Select(i => i.Value)).FirstOrDefault()
        let sedol = (item.Elements("DataItem")
            .Where(i => (string)i.Attribute("name") == "SEDOL").Select(i => i.Value)).FirstOrDefault()
        select new {
            Symbol = symbol,
            CompName = compName,
            Cusip = cusip,
            Sedol = sedol
        };

I feel that this can be made cleaner.  How can it be done?


texts:
Create a class template named ValueStore that has a member variable,
to store a value and a member variable, hasValue that holds a true
value if there is data in the value member variable and false
otherwise. Use the class to store three values of different types.

#include <iostream>
using namespace std;

template <typename T>
class ValueStore {
private:
  T value;

public:
  bool hasValue = false;

  ValueStore(T val) {
    value = val;
    hasValue = true;
  }

  ValueStore() {
    value = {};
  }

  T getValue() {
    return value;
  }

};

int main ()
{
  ValueStore<string> v1("hello, world");
  if (v1.hasValue) {
    cout << "The value stored is: " << v1.getValue() << endl;
  }
  else {
    cout << "v1 has no value." << endl;
  }
  ValueStore<int>v2(1000);
  if (v2.hasValue) {
    cout << "The value stored is: " << v2.getValue() << endl;
  }
  else {
    cout << "v2 has no value." << endl;
  }
  ValueStore<double> v3;
  if (v3.hasValue) {
    cout << "The value stored is: " << v2.getValue() << endl;
  }
  else {
    cout << "v3 has no value." << endl;
  }
  return 0;
}


texts: Shell command to output all plugins that exist across multiple wordpress installations

texts:
I'm working on a server and need a complete list of plugins that are installed for all wp installations. I only need to know whether a plugin exists or not, it doesn't matter where it exists.

For example, given:

/siteA/wp-content/plugins/someplugin
/siteA/wp-content/plugins/anotherplugin

/siteB/wp-content/plugins/someplugin

I need the following result:

someplugin
anotherplugin

Here is the working command:

for i in $(find . -type d -name 'plugins' | grep 'wp-content/plugins$'); do find ${i} -maxdepth 1 -type d -exec sh -c 'for f do basename -- "$f"; done' sh {} + ; done | sort -u

Can this command be shortened?


texts: Program to check if in line are doubled words

texts:
I made program to open a text file and count the number of lines without doubled words. This number is printed in the end.

This is an example text file:

sayndz zfxlkl attjtww cti sokkmty brx fhh suelqbp
xmuf znkhaes pggrlp zia znkhaes znkhaes
nti rxr bogebb zdwrin
sryookh unrudn zrkz jxhrdo zrkz
bssqn wbmdc rigc zketu ketichh enkixg bmdwc stnsdf jnz mqovwg ixgken

I've already made a program, and it looks like that program works. But I'm aware that in programming if something works it doesn't mean that program is made properly.

My code:

class SkyphrasesValidation(object):
    def get_text_file(self):
        file = open('C:/Users/PC/Documents/skychallenge_skyphrase_input.txt', 'r')
        return file

    def lines_list(self):
        text = self.get_text_file()
        line_list = text.readlines()
        return [line.split() for line in line_list]

    def phrases_validation(self):
        validated_phrases = 0
        for line in self.lines_list():
            new_line = []
            for word in line:
                exam = line.count(word)
                if exam > 1:
                    new_line.append(0)
                else:
                    new_line.append(1)
            if 0 in new_line:
                validated_phrases += 0
            else:
                validated_phrases += 1
        return validated_phrases

    def __str__(self):
        return str(self.phrases_validation())

text = SkyphrasesValidation()

print(text)

Is my logic good and is this program is well-made? Or maybe it looks like poop and I could write this more clearly?


texts: Recursive os.scandir() for copying/moving files preserving subdirectories

texts:
This is modified from the general recursive solution here: https://stackoverflow.com/a/54544211/42346 to, more specifically, copy/move files with a given extension from one directory to another whilst preserving subdirectories.

I'm reluctant to use .rename() for this purpose as it seems slightly less intuitive than copying or moving.

Any other ideas you have about how to clean this up are greatly appreciated.

import os, shutil
from pathlib import Path

def recur(path,destination,file_ext,is_subdir=False):
    if not is_subdir:
        os.chdir(path)
    for entry in os.scandir(path):
        if os.path.splitext(entry.name)[-1].lower() == file_ext:
            subdir_path = entry.path.replace(os.getcwd() + os.sep,'')
            new_path = Path(destination) / subdir_path
            os.makedirs(os.path.dirname(new_path), exist_ok=True)
            shutil.copy(entry.path,new_path)
        if entry.is_dir():
            recur(Path(path).joinpath(entry.name),destination,file_ext,is_subdir=True)


texts:
I'm a Scala beginner, so it'd be great if anyone would be so kind to give some feedback.

package heap

import scala.collection.mutable.ListBuffer

class Heap[T](compareFunction: (T, T) => Int) {

private val HIGHER = 1
private val LOWER = -1

private val heapRepresentation = new ListBuffer[T]()

private def lastIndex = heapRepresentation.size - 1

private def valueOf(index: Int): T = heapRepresentation(index)

def add(item: T): Heap[T] = {
    heapRepresentation.append(item)
    bubbleUp(lastIndex)
    this
}

def swap(index1: Int, index2: Int) {
    val temp = valueOf(index1)
    heapRepresentation.update(index1, valueOf(index2))
    heapRepresentation.update(index2, temp)
}

def bubbleUp(currentIndex: Int) {
    def getParent(i: Int) = (i - 1) / 2

    if (currentIndex > 0) {
        val parentIndex = getParent(currentIndex)

        compareFunction(valueOf(currentIndex), valueOf(parentIndex)) match {
            case LOWER =>
                swap(currentIndex, parentIndex)
                bubbleUp(parentIndex)
            case _ =>
        }
    }
}

def bubbleDown(currentIndex: Int) {
    getLowerChild(currentIndex) match {
        case Some((lowerChildIndex, lowerChildValue)) =>
            if (compareFunction(valueOf(currentIndex), lowerChildValue) == HIGHER) {
                swap(currentIndex, lowerChildIndex)
                bubbleDown(lowerChildIndex)
            }
        case None =>
    }
}

def getLowerChild(index: Int): Option[(Int, T)] = {
    def getChildrenIndices(parentIndex: Int): (Int, Int) = (2 * parentIndex + 1, 2 * parentIndex + 2)

    val (leftChildIndex, rightChildIndex) = getChildrenIndices(index)

    val areChildrenInBoundsOfHeap = (rightChildIndex <= lastIndex) && (leftChildIndex <= lastIndex)
    if (!areChildrenInBoundsOfHeap) return None

    val (leftChildValue, rightChildValue) = (heapRepresentation(leftChildIndex), heapRepresentation(rightChildIndex))

    compareFunction(leftChildValue, rightChildValue) match {
        case LOWER => Some((leftChildIndex, leftChildValue))
        case _ => Some((rightChildIndex, rightChildValue))
    }
}

def pop: Option[T] = heapRepresentation.size match {
    case 0 => None
    case _ =>

        val firstValue = heapRepresentation(0)
        if (heapRepresentation.size == 1) {
            heapRepresentation.remove(0)
            return Some(firstValue)
        }
        swap(0, lastIndex)
        heapRepresentation.remove(lastIndex)
        bubbleDown(0)
        Some(firstValue)
}

override def toString = {
    s"[$heapRepresentation](${heapRepresentation.size})"
}

}

Usage of heap class

def compareInts(first: Int, second: Int): Int =
    if (first > second) 1
    else if (first == second) 0
    else -1

val heap = new Heap[Int](compareInts)

for (i <- 0 to 3) {
    heap.add((Math.random() * 100).toInt)
}
heap
heap.pop
heap.pop
heap.pop
heap.pop

def compareStrings(first: String, second: String): Int =
    if (first > second) 1
    else if (first == second) 0
    else -1
var heap2 = new Heap[String](compareStrings)
heap2.add("a")
heap2.add("cc")
heap2.add("")

heap2.pop
heap2.pop
heap2.pop
heap2.pop

Right now, I would like to get a Scala mindset, and get to know the tricks and tips. I have a background in PHP and JavaScript, and Scala is quite harder to learn, but way more elegant, so I want to master it!


texts:
I am going through the 4clojure problems and I currently just solved the Tic Tac Toe analyzer:

(fn [board]
    (let [vr (for [x (range 3)]
              (get-in board[(+ x 0) (+ x 0)]))
          vl (for [x (range 3)]
               (get-in board [(+ x) (- 2 x)]))
          columns (apply map vector board)
          checks (concat board [vl] [vr] columns)]
      (letfn [(check-board [[row & res]]
                (if row
                  (let [dist (distinct row)]
                      (if (or (= dist [:o]) (= dist [:x]))
                        (first dist)
                        (check-board res)))
                  nil))]
        (check-board checks))))

I'm looking for any feedback about how I could make the code more terse.

Could I have created the diagonal vectors in one expression?

I don't like that I had to use recursion but I could not think of a way of using something like reduce because I don't think there is a way to short circuit reduce if you find the result midway through processing all the values.

Is there a way that I could avoid recursion with this problem?


texts: Assigning array keys based on the values of another array

texts:
An optimisation question:

Currently I have entities stored in text files in the following format:

Attribute1,Attribute2,Attribute3
Value1-1,Value1-2,Value1-3
Value2-1,Value2-2,Value2-3
Value3-1,Value3-2,Value3-3

And convert it into a 2D array in the following format:

$array = array(array('Attribute1' => 'Value1-1',
                     'Attribute2', => 'Value1-2',
                     'Attribute3', => 'Value1-3'),
               array('Attribute1' => 'Value2-1',
                     'Attribute2', => 'Value2-2',
                     'Attribute3', => 'Value2-3'),
               array('Attribute1' => 'Value3-1',
                     'Attribute2', => 'Value3-2',
                     'Attribute3', => 'Value3-3'));

Using the following PHP code:

$lines = array();
$dump = normaliseNewLine($dump);
$dump = explode("\n", $dump);
$attributes = explode(',', array_shift($dump));

for($i = 0; $i < count($dump); $i++) {
    $tmp = explode(',', $dump[$i]);
    for ($j = 0; $j < count($tmp); $j++) {
        $lines[$i][$attributes[$j]] = $tmp[$j];
    }
}

I was wondering if there was a more efficient method of completing this task?


texts:
Is there a better or easier way of doing this?

if array[1] and array[2] and array[3] and array[4] and array[5] == false then

    --somthing

end

I have a lot of arrays to check and was wondering if there is a way to work with arrays where you can do something like array[1-6] or [1,6] or something. Can't seem to find anything online.


texts:
https://leetcode.com/problems/house-robber/

  You are a professional robber planning to rob houses along a street.
  Each house has a certain amount of money stashed, the only constraint
  stopping you from robbing each of them is that adjacent houses have
  security system connected and it will automatically contact the police
  if two adjacent houses were broken into on the same night.

  Given a list of non-negative integers representing the amount of money
  of each house, determine the maximum amount of money you can rob
  tonight without alerting the police.

  Example 1:

 Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and
 then rob house 3 (money = 3).
 Total amount you can rob = 1 + 3 = 4. Example 2:

  Example 2:
      Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2),
      rob house 3 (money = 9) and rob house 5 (money = 1).
      Total amount you can rob = 2 + 9 + 1 = 12.

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    ///  https://leetcode.com/explore/interview/card/top-interview-questions-easy/97/dynamic-programming/576/
    /// </summary>
    [TestClass]
    public class HouseRobber
    {
        [TestMethod]
        public void HouseRobberTest()
        {
            int[] nums = {1, 2, 3, 1};
            HouseRobberClass robber = new HouseRobberClass();
            Assert.AreEqual(4, robber.Rob(nums));
        }

        [TestMethod]
        public void HouseRobber2Test()
        {
            int[] nums = { 1, 2, 3, 1 };
            HouseRobberClass robber = new HouseRobberClass();
            Assert.AreEqual(4, robber.Rob2(nums));
        }
    }

    public class HouseRobberClass
    {
        private int[] _mem;
        //option 1 for a solution - this is easier for me to think this way
        public int Rob(int[] nums)
        {
            _mem = Enumerable.Repeat(-1, nums.Length).ToArray();

            return Helper(nums,  0);
        }

        private int Helper(int[] nums, int index)
        {
            if (index >= nums.Length)
            {
                return 0;
            }

            if (_mem[index] >= 0)
            {
                return _mem[index];
            }

            _mem[index] = Math.Max(Helper(nums, index + 2) + nums[index], Helper(nums, index + 1));
            return _mem[index];
        }

       // option 2 for a solution
        public int Rob2(int[] nums)
        {
            if (nums.Length == 0)
            {
                return 0;
            }
            int[] memo = new int[nums.Length + 1];
            memo[0] = 0;
            memo[1] = nums[0];
            for (int i = 1; i < nums.Length; i++)
            {
                int val = nums[i];
                memo[i + 1] = Math.Max(memo[i], memo[i - 1] + val);
            }

            return memo[nums.Length];
        }
    }
}


texts: Calling a method in parallel which returns the future

texts:
I have an async method which calls my Task class while my Task class does all the work:

    private ExecutorService executor = Executors.newFixedThreadPool(10);

    @Override
    public Future<DataResponse> executeAsync(DataKey key) {
        Future<DataResponse> future = null;

        try {
            Task task = new Task(key, restTemplate);
            future = executor.submit(task);
        } catch (Exception ex) {
            // logging exception here
        }

        return future;
    }

Here is my Task class which does all the work:

public class Task implements Callable<DataResponse> {

    private DataKey key;
    private RestTemplate restTemplate;

    public Task(DataKey key, RestTemplate restTemplate) {
        this.key = key;
        this.restTemplate = restTemplate;
    }

    @Override
    public DataResponse call() throws Exception {
        // some code here
    }
}

Now I need to call executeAsync method in parallel and then make a List<DataResponse> object and return it:

@Override
public List<DataResponse> executeSync(DataKey key) {
    List<DataResponse> responseList = new ArrayList<DataResponse>();

    // make a List of DataKey using single key passed to this method.
    List<DataKey> keys = new ArrayList<DataKey>();

    // here keys max size will be three
    List<Future> futures = new ArrayList<>(keys.size());
    for(DataKey key : keys) {
        Future<DataResponse> future = executeAsync(key);
        futures.add(future);
    }

    for (Future<DataResponse> future : futures) {
        try {
            responseList.add(future.get(300, TimeUnit.MILLISECONDS));
        } catch (Exception e) {
            // do something
        }
    }
    return responseList;
}

My intention is to call executeAsync method in parallel and return back responseList object. I mean I want to execute call method of my Task class in parallel for each of the key object so if I have three key object in keys list, then I want to execute call method for each key in parallel and then make a List<DataResponse> object and return it.

Since I don't want to wait 300 Milliseconds for each key future and then call next key future and then next call third key future. In this way it will wait 300 + 300 + 300 for each of the key. I want to execute call method in parallel in same 300 milliseconds for all three keys.

Does my above code looks right, and are there any better ways of doing this problem? I am still on Java 7.


texts: Given a digit sequence, print the possible decodings of the given digit sequence

texts:
Examples:

12 gives:
'AB' and 'L'

and

123 gives
'ABC', 'LC' and 'AW'

Here is my attempt:
import java.util.*;

public class decoding {

static int calls = 0;
static Map<Integer, String> codes  = new HashMap<Integer, String>();

private static void construct(){
codes.put(1, "A");
codes.put(2, "B");
codes.put(3, "C");
codes.put(4, "D");
codes.put(5, "E");
codes.put(6, "F");
codes.put(7, "G");
codes.put(8, "H");
codes.put(9, "I");
codes.put(10, "J");
codes.put(11, "K");
codes.put(12, "L");
codes.put(13, "M");
codes.put(14, "N");
codes.put(15, "O");
codes.put(16, "P");
codes.put(17, "Q");
codes.put(18, "R");
codes.put(19, "S");
codes.put(20, "T");
codes.put(21, "U");
codes.put(22, "V");
codes.put(23, "W");
codes.put(24, "X");
codes.put(25, "Y");
codes.put(26, "Z");
}

private static void decode(String str, String built){

    construct();

    int n = str.length();

    if (n == 0) {
        System.out.println(built);
        return;
    }

        // If you have 0's, then they don't have a corresponding singular letter. Break off the recursion.
        if (str.substring(0, 1).equals("0"))
            return;

        String x = codes.get(Integer.parseInt(str.substring(0, 1)));
        if (x == null)
            return;
        decode(str.substring(1), built+x);

        if (n > 1) {

            // If it's more than 26, it doesn't have a corresponding letter. Break off the recursion.
            if (Integer.parseInt(str.substring(0, 2)) > 26)
                return;

            String y = codes.get(Integer.parseInt(str.substring(0, 2)));

            decode(str.substring(2), built+y);
        }
    }

public static void main(String[] args) {
    decode(args[0], "");
}
}

I haven't done any memoization or dynamic programming in this. It's a rather crude solution with exponential run time I believe. Let me know what you think.


texts: Lowest common ancestor in recursive tree traversal

texts:
LCA = Lowest Common Ancestor

The following code finds the lowest common ancestor in tree of nodes, where a node can have two parents, left and right.

The tree looks like this:

     J-K
    /   \
 E-F-G-H-I

And K and H input, the output is F

public TreeSet<Node> find(Node node, TreeSet<Node> nodeSet) {
    nodeSet.add(node);
    if (node.getLeft() != null) {
        find(node.getLeft(), nodeSet);
    }
    if (node.getRight() != null) {
        find(node.getRight(), nodeSet);
    }

    return nodeSet;
}

which is called here:

TreeSet<Node> nodeList1 = new TreeSet<Node>();
TreeSet<Node> nodeList2 = new TreeSet<Node>();
nodeList1 = find(node1, nodesList1); // node1 = K
nodeList2 = find(node2, nodesList2); // node2 = H
Iterator iterator = nodeList1.descendingIterator();
  while (iterator.hasNext()){
    Node node = (Node) iterator.next();
    if(nodeList2.contains(node)){
      return node.getValue();
    }
}

and a Node looks like you'd expect and implements comparable.

Is my implementation O(n), I think it is, but can it be improved?

The relvant snippet of Node:

class Node implements Comparable<Node> {

    private String value;
        private Node left;
        private Node right;
        @Override
        public int hashCode() {
            return this.getValue().hashCode();
        }

        @Override
        public int compareTo(Node o) {
            return this.getValue().compareTo(o.getValue());
        }