texts:
In a project, I have a lot of HTML forms without validation and I want to add a front end validation, in a quick way. I start looking for a library and I met Parsley.js. It's a good library, but if I decided to use it I would have to modify all the forms in my application.

So there is where this code is born. It's for automatically binding a set of rules you define to a form.

//Only basic types and validators.
$.fn.parsley.mapping = {
//Types
'alphanum': {'parsley-type':    'alphanum'},
'email':    {'parsley-type':    'email'},
'url':  {'parsley-type':    'url'},
'number':   {'parsley-type':    'number'},
'digits':   {'parsley-type':    'digits'},
'dateIso':  {'parsley-type':    'dateIso'},
'phone':    {'parsley-type':    'phone'},

//Validators
'required': {'parsley-required':    'true'},
'notblank': {'parsley-notblank':    'true'},
'minlength':    {'parsley-minlength': '?'},
'maxlength':    {'parsley-maxlength': '?'},
'min':  {'parsley-min': '?'},
'max':  {'parsley-max': '?'}
}

//Only inputs and textareas
$.fn.parsley.fields = 'input:visible, textarea:visible';

!function ($) {
$.fn.generalValidation = function( validationRules ) {

var name, validations, validationName, validationValue, att, key, value
, form = $( this )
, addValidations = function( validationRules ){
if(validationRules === undefined){
console.log('Error!!! You need to add the validation rules parameter');
validationRules = {};
}
$( form ).find( $.fn.parsley.fields ).each(function(){
name = $( this ).attr('name');
validations = validationRules[name];

if(validations == undefined) return true;

for(validation in validations){
validationName = validations[validation];
validationValue = '';
if(validationName.indexOf(':') !== -1){
validationValue = validationName.substr(validationName.indexOf(':')+1, validationName.length);
validationName = validationName.substr(0, validationName.indexOf(':'));
}

att = $.fn.parsley.mapping[validationName];
if(att !== undefined){
$.map(att, function (v, k) { key = k; value = v; });
value = (value === '?') ? validationValue : value;
$(this).attr(key, value);
}
}
});
return true;
}
, callParsley = function( form ) {
form.parsley();
};

if(addValidations( validationRules )){
callParsley( form );
}
}
} ( window.jQuery );

Here is a JSFiddle.

This is my first plugin in jQuery.  Would you improve something in the code? Do you find this useful?


texts: The longest subsequence with specified difference between min and max

texts:
As an input you have non-empty zero-indexed array of integers. The goal is to find the longest subsequence (any sequence obtained by removing some elements from A), where difference between min value and max value does not exceed 1.

For example, given array: 6,10,7,7,9,8 function should return 3, because 6,7,7 (or 7,7,8) is the longest qualifying subsequence.

Is this solution efficient?

    public int solution(int[] A) {
    Arrays.sort(A);
    int counter = 0;
    int res = 0;
    int val = -1;
    for (int i = 0; i < A.length - 1; i++) {
        if (val == -1 && A[i + 1] - A[i] < 2) {
            counter = 2;
            val = A[i + 1] - A[i];
        } else if (val == 0 && A[i + 1] - A[i] <= 1) {
            counter++;
            val = A[i + 1] - A[i];
        } else if (val == 1 && A[i + 1] - A[i] == 0) {
            counter++;
        } else {
            val = -1;
            res = Math.max(res, counter);
            counter = 0;
        }
    }
    return res;
}

Time complexity is linearithmic.


texts:
Implement a MapSum class with insert, and sum methods.

  For the method insert, you'll be given a pair of (string, integer).
  The string represents the key and the integer represents the value. If
  the key already existed, then the original key-value pair will be
  overridden to the new one.

  For the method sum, you'll be given a string representing the prefix,
  and you need to return the sum of all the pairs' value whose key
  starts with the prefix.

Example 1:
Input: insert("apple", 3), Output: Null
Input: sum("ap"), Output: 3
Input: insert("app", 2), Output: Null
Input: sum("ap"), Output: 5

Please comment on performance and style

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TrieQuestions
{
    [TestClass]
    public class TrieMapSum
    {
        [TestMethod]
        public void MapSumTest()
        {
            MapSum mapSum = new MapSum();
            mapSum.Insert("apple", 3);
            Assert.AreEqual(3, mapSum.Sum("ap"));
            mapSum.Insert("app", 2);
            Assert.AreEqual(5, mapSum.Sum("ap"));
        }
    }

    public class MapSum
    {
        private TrieMSNode Head;
        /** Initialize your data structure here. */
        public MapSum()
        {
            Head = new TrieMSNode();
        }

        public void Insert(string key, int val)
        {
            var current = Head;
            foreach (var letter in key)
            {
                if (!current.Edges.ContainsKey(letter))
                {
                    current.Edges.Add(letter, new TrieMSNode());
                }
                current = current.Edges[letter];
            }

            current.IsTerminal = true;
            current.Value = val;
        }

        public int Sum(string prefix)
        {
            int sum = 0;
            var current = Head;
            foreach (var letter in prefix)
            {
                if (!current.Edges.ContainsKey(letter))
                {
                    return sum;
                }

                current = current.Edges[letter];
            }
            // we use dfs for each edges of the trie;
            return DFS(current);
        }

        private int DFS(TrieMSNode current)
        {
            if (current == null)
            {
                return 0;
            }

            int sum = current.IsTerminal ? current.Value : 0;
            foreach (var edge in current.Edges.Values)
            {
                sum += DFS(edge);
            }
            return sum;
        }
    }

    internal class TrieMSNode
    {
        public Dictionary<char, TrieMSNode> Edges { get; set; }
        public bool IsTerminal;
        public int Value;

        public TrieMSNode()
        {
            Edges = new Dictionary<char, TrieMSNode>();
            IsTerminal = false;
            Value = 0;
        }
    }
}


texts: Get an object with null values from an array of nested objects

texts:
I have an array of nested objects. How do I get an object with null values using only a particular key in the array of objects?

let headers = [{
    title: 'Arun',
    id: 'arunId',
    onClick: 'onClickArun'
  },
  {
    title: "George",
    id: 'georgeId',
    onClick: '',
    children: [{
        title: 'David',
        id: 'davidId',
        onClick: 'onClickDavid'
      },
      {
        title: 'Patrick',
        id: 'patrickId',
        onClick: 'onClickPatrick'
      }
    ]
  },
  {
    title: 'Mark',
    id: 'markId',
    onClick: 'onClickMark'
  }
]

const headersMap = ({
  onClick,
  children
}) => (onClick ? {
  onClick
} : _.map(children, headersMap));

const headersFlatMap = _.flatMap(headers, headersMap);

const headerObj = _.reduce(_.map(headersFlatMap, 'onClick'), (ac, a) => ({ ...ac,
  [a]: null
}), {});

console.log(headerObj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

The code works good, but is there a way to optimize it?

Expected Output:

{
  "onClickArun": null,
  "onClickDavid": null,
  "onClickPatrick": null,
  "onClickMark": null
}

Any help is greatly appreciated. Thanks.


texts: Java String Reverse Algorithm which is the most effcient approch?

texts:
I have the following two approaches for writing a custom string reverse algorithm and I was hoping someone could tell me which is the most efficient / preferable option and explain why. I am fairly new to Java and this would be educational for me. FYI I know this can be done using Stringbuilder but I wanted to write my own solution.

Solution 1: uses two arrays, copying the contents of one into another but in reverse order

//include needed util
import java.util.Scanner;

 /**
 * This class will reverse a string
 * @author Richard
 *
 */

public class ReverseString {
/**
 * This method will take in a string, convert that to two
 * char arrays, then swap the contents of one for the contents
 * of the other except moving in opposite directions and so
 * will reverse the order of the output string
 * @param args
 */

public static void main(String[] args) {

    //declare variables
    Scanner input = new Scanner(System.in);
    String inputString = "";
    int length = 0, indexOfArrayToChange = 0, indexOfReferenceArray = 0;

    //get input string
    System.out.print("Enter the string you want to reverse: ");
    inputString = input.nextLine();

    //find length of string, it needs to be reduced by one to prevent an error
    //as index start at 0.
    length = inputString.length()-1;
    //set 'indexOfReferenceArray' equal to string.length-1 for use later in loop
    indexOfReferenceArray = length;

    //convert to arrays
    char[] arrayToChange = inputString.toCharArray();
    char[] referenceArray = inputString.toCharArray();

    //loop through and reverse order as long as we are still within bounds of original string length
    while (indexOfArrayToChange<=length) {
        //change the first letter of one array to be the same as the last letter of reference array
        arrayToChange[indexOfArrayToChange] = referenceArray[indexOfReferenceArray];
        //increment/decrement to move through arrays
        indexOfArrayToChange++;
        indexOfReferenceArray--;

    }
    //convert back to string
    String newString = new String(arrayToChange);

    //output result
    System.out.println(newString);

    //close resources
    input.close();
}
}

Solution 2: uses one array and swaps from back to front meeting in the middle. However the code within the loop has to be longer to do the swapping.

//include needed util
import java.util.Scanner;

/**
* This class will reverse an inputed string
* @author Richard
*
*/
public class ReverseString {

/**
 * This method will take in a string, convert that to a
 * char array, then swap the contents of the array from back to front
 * meeting in the middle.
 * @param args
 */
public static void main(String[] args) {
    //declare variables
    Scanner input = new Scanner(System.in);
    String inputString = "";
    int length = 0, indexStart = 0, indexEnd = 0;

    //get input string
    System.out.print("Enter the string you want to reverse: ");
    inputString = input.nextLine();

    //find length of string, it needs to be reduced by one to prevent an error
    //as index start at 0.
    length = inputString.length()-1;
    //set 'indexOfReferenceArray' equal to string.length-1 for use later in loop
    indexEnd = length;

    //convert to arrays
    char[] array = inputString.toCharArray();

    //loop through and reverse order until two vars meet in middle of array
    while (indexStart<=(length/2)) {
        //swap array elements
        char temp = array[indexStart];
        array[indexStart] = array[indexEnd];
        array[indexEnd] = temp;
        //increment/decrement to move through arrays
        indexStart++;
        indexEnd--;
    }

    //convert back to string
    String newString = new String(array);

    //output result
    System.out.println(newString);

    //close resources
    input.close();

}

}


texts: Mapping interface between POJOs and DTOs

texts:
Following up on this question DTO interfaces for implementing web service integration I came up with this implementation.

Data Transfer Object interface following a java.util.Map protocol. The implementation uses Guava's ForwardingMap.

public interface Dto<K, V> extends Map<K, V> {}

public class DtoImpl<K, V> extends ForwardingMap<K, V> implements Dto<K, V> {

    private final Map<K, V> delegate;

    @Override
    protected Map<K, V> delegate() {
        return this.delegate;
    }

    private DtoImpl(final Map<K, V> map) {
        this.delegate = map;
    }

    public static <K, V> Dto<K, V> of(final Map<K, V> map) {
        return new DtoImpl<K, V>(map);
    }
}

Mapper interface between a type T and a Dto.

public interface Mapper<T> {

    public <K, V> Dto<K, V> toDto(T obj);

    public <K, V> T fromDto(Dto<K, V> dto, Class<T> clazz);
}

public class MapperImpl<T> implements Mapper<T> {

    public <K, V> Dto<K, V> toDto(T obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<K, V> map = objectMapper.convertValue(obj, Map.class);
        return DtoImpl.of(map);
    }

    public <K, V> T fromDto(Dto<K, V> dto, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        T obj = objectMapper.convertValue(dto, clazz);
        return obj;
    }

}

Comments and improvements on this implementation are welcome!
Is it worth it to define the Mapper interface with something like interface Mapper<T, K, V>? Ideally I would like to say interface Mapper<T, S extends Dto<K, V>> but this is not possible or is it?


texts:
Problem:Implement a queue class in Python: It should support 3 APIs:

  queue.top(): prints current element at front of queue

  queue.pop(): takes out an element from front of queue

  queue.add(): adds a new element at end of queue

class Queue:

    def __init__(self):
        """initialise a Queue class"""
        self.items = []
        self.index = len(self.items) - 1

    def top(self):
        """returns the current element at front of queue"""
        if self.items:
            return self.items[0]
        else:
            raise Exception("Empty Queue")

    def pop(self):
        """takes out an element from front of queue"""
        if self.items:
            self.items.pop(0)
        else :
            raise Exception("Empty Queue")

    def add(self , item):
        """adds a new element at the end of queue"""
        self.items.append(item)

    def __str__(self):
        """returns the string representation"""
        return str(self.items)

    def __iter__(self):
        """iterates over the sequence"""
        return self

    def __next__(self):
        """returns the next value in sequence"""
        if self.index == 0 :
            raise StopIteration
        self.index -= 1
        return self.items[self.index]

queue_1 = Queue()
queue_1.add(12)
queue_1.add(11)
queue_1.add(55)
queue_1.add(66)
queue_1.add(56)
queue_1.add(43)
queue_1.add(33)
queue_1.add(88)
queue_1.add(56)
queue_1.add(34)
iter(queue_1)
for i in queue_1:
    print i
print queue_1
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()

The code works as intended and executes the 3 APIs specified in the problem . But it gives ""TypeError: instance has no next() method"" when i try to use next method to iterate over the values in queue. What am i missing in defining the next method?


texts:
@Effect()
createQuiz$: Observable<Action> = this.actions$.pipe(
    ofType<quizAction.CreateQuiz>(quizAction.CREATE_QUIZ),
    switchMap((action) => {
        return this.quizService.createQuiz(action.payload)
        .pipe(
        map(() => {
            return new quizAction.CreateQuizCompleted()
        }),
        catchError(error => {
            console.log(error);
            return of(new quizAction.CreateQuizCompleted());
        })
        );

    })
);

export class QuizComponent implements OnInit {

  constructor(
    private quizService: QuizService,
    private store:Store<{app: fromApp.State}>,
  ) { }

  ngOnInit(): void {
  }

  trackByIdx = (index: number): number => index;

  onCreate(): void {
    this.store.select(fromApp.selectUserId).pipe(
      take(1)
    ).subscribe(userId => this.handleCreate(userId));
  }

  handleCreate(userId: string): void {
    let value = this.quizService.createDefaultQuiz();
    if (this.quizService.hasPermission(userId) && this.quizService.validateQuiz(value)) {
      this.store.dispatch(new quizAction.CreateQuiz(value));
    }
  }
}

I am wondering if there's any memory leak that can occur or any non-idiomatic patterns that I am using without knowing. Does everything look fine?


texts:
This is the first PDF class I have made for the iOS using code from Apple's samples.  There could easily be stuff here wrong that I am missing.

I intend this to get images out of for a layer, for example:

image.contents = (id)[self.test imageForPage: 3 size: CGSizeMake(4*dpc, 2*dpc)].CGImage;

Here is this hopefully decent code.  Any suggestions are welcome.

@interface PDFDocument : NSObject {
CGPDFDocumentRef pdfFile;
}

- (id) initWithURL: (NSURL*) url;
- (UIImage*) imageForPage: (size_t) pageno size: (CGSize) size;
- (CGSize) sizeOfPage: (size_t) pageno;

@end

@implementation PDFDocument

- (id) initWithURL: (NSURL*) url {
    if ([super init])
    {
        // Open PDF
        CGPDFDocumentRef doc = CGPDFDocumentCreateWithURL((CFURLRef)url);

        if (doc == NULL)
            @throw @"PDF File does not exist.";

        pdfFile = doc;

    }
    return self;
}

- (UIImage*) imageForPage: (size_t) pageno size: (CGSize) size {
    if (pdfFile) {
        // Get First Page
        CGPDFPageRef page = CGPDFDocumentGetPage(pdfFile, pageno);

        if (page == NULL)
            @throw @"Page does not exist.";

        // Get Page Size
        CGRect cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);

        // Start Drawing Context to Render PDF
        UIGraphicsBeginImageContext(size);

        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);

        CGRect u = { {0, 0}, size};

        CGContextFillRect(context, u);
        CGContextSetAllowsAntialiasing(context, NO);

        CGContextSaveGState(context);

        // Scale PDF
        CGContextScaleCTM(context, size.width / cropBox.size.width, size.height / cropBox.size.height);

        // Flip Context to render PDF correctly
        CGContextTranslateCTM(context, 0.0, cropBox.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);

        CGContextDrawPDFPage(context, page);
        CGContextRestoreGState(context);

        UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); // must retain?

        UIGraphicsEndImageContext();

        return img;

    }
    return nil;
}

- (CGSize) sizeOfPage: (size_t) pageno {
    if (pdfFile) {
        CGPDFPageRef page = CGPDFDocumentGetPage(pdfFile, pageno);

        if (page == NULL)
            @throw @"Page does not exist";

        CGRect cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);

        return cropBox.size;
    }

    @throw @"No document loaded.";
}

@end


texts:
I have a defaultdict being written to file like this:

writer = csv.writer(open(locationToSaveFile, 'wb+'))
for k,v in dict.iteritems():
    writer.writerow([k ,v])

I then have this horribly convoluted text to read it back in:

myDict = defaultdict(list)
with open(fileLocation, 'rb') as test:
    reader = csv.DictReader(test, ['processedText', 'date'])

    for line in reader:
        myDict[line['processedText']].append(line['date'])

textDict = defaultdict(list)

for processedText, date in myDict.items():
    actual_list = ast.literal_eval(date[0])
    for a in actual_list:
        textDict[processedText].append(a)

for processedText, date in textDict.items():

Obviously this looks very wasteful (and looks horrible!) but I don't know how else to import the defaultdict.

When opening it with the reader = and for line in reader lines it creates a list within a list. The only way out of this is to use ast to convert it.

Could somebody advise me how to tidy this up?

Note: I'm very unfamiliar with Python


texts:
I was solving the following problem on HackerRank.
Here's my solution -
from itertools import combinations
a = input()
ls = list(map(str, a.split()))
for i in range(1, int(ls[1])+1):
    ls2 = []
    ls2 = list(map("".join, combinations(ls[0], i)))
    for elem in ls2:
        ls2[ls2.index(elem)] = "".join(sorted(elem))
    ls2.sort()
    for char in ls2:
        print(char)

But I feel it's not very efficient as it uses 2 Lists and 2 nested loops.
Any suggestions as to how can I improve the code?


texts: Return boolean for navigation (nav) links before and after clicking them

texts:
I want to write a function to check if some nav links exist or not. However, those nav links are under one of the listbox icons so I need to click the icon
before and after to check if the element exists. The following code works. Nonetheless, is there a better way for writing this?

def func(locator, name):
    if self.driver.find_element_by_xpath('{}{}/i'.format(locator, '[@aria-expand="false"]')):
        self.driver.find_element_by_xpath(locator).click()
    try:
        est = True
        self.driver.find_element_by_xpath('{}//a[text()="{}"]'.format(locator, name)).
    except NoSuchElementException:
        est = False
    if self.driver.find_element_by_xpath('{}{}/i'.format(locator, '[@aria-expand="true"]')):
        self.driver.find_element_by_xpath(locator).click()

    return est


texts:
I am looking to hide an email id name, by only showing first 4 letters of the email. The code works fine. Looking for opinion if I could make it better, more readable and maybe even more efficient if possible. I am using Commons lang library for this and wondering if that is an unnecessary overhead.

Please look for the comment <-- HERE -->. I am looking for opinion in this region. I am using Java 7, no way around that.

import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.Map;

public class App {
    public static void main(String[] args) {

        //all these prints out as expected.

        String newEmail1 = getEmail("sample1");
        System.out.println("Expected: some**@gmail.com | actual: " + newEmail1);

        String newEmail2 = getEmail("sample2");
        System.out.println("Expected: null | actual: " + newEmail2);

        String newEmail3 = getEmail("short");
        System.out.println("Expected: q**@gmail.com | actual: " + newEmail3);

        String newEmail4 = getEmail("noname");
        System.out.println("Expected: null | actual: " + newEmail4);
    }

    private static String getEmail(String param){
        //added these solely for testing to show
        Map<String, String> emails = new HashMap<>();
        emails.put("sample1", "someone@gmail.com");
        emails.put("short", "qw@gmail.com");
        emails.put("noname", "@gmail.com");
        //added these solely for testing to show

        //I am looking for opinions from here onwards. <-- HERE -->
        String emailAddress = emails.get(param);
        if(emailAddress != null){
            String emailAddressFront = StringUtils.substringBefore(emailAddress, "@");
            String emailAddressBack = StringUtils.substringAfter(emailAddress, "@");

            // i need to hide emails by only revealing first 4 characters.
            // but also need to check in case email name is shorter than 4.
            if(emailAddressFront.isEmpty()){
                return null;
            }
            int shortenedLength = 4;
            int emailNameLength = emailAddressFront.length();
            if(emailNameLength < 4){
                shortenedLength = emailNameLength - 1;
            }
            emailAddress = emailAddressFront.substring(0, shortenedLength) + "**@" + emailAddressBack;
        }
        return emailAddress;
        //I am looking for opinions till here. <-- HERE -->
    }
}


texts:
I'm looking for advice on coding practices in general.

 public class Knapsack {

        public static int getMaxBenefit(int[] weights, int[] benefits, int capacity) {

        int[][] maxbenefit = new int[weights.length + 1][capacity + 1];

        for (int i = 0; i <= weights.length; i++)
            maxbenefit[i][0] = 0;
        for (int i = 0; i <= capacity; i++)
            maxbenefit[0][i] = 0;

        for (int item = 1; item <= weights.length; item++) {

            for (int weight = 1; weight <= capacity; weight++) {

                if (weights[item - 1] <= weight) {

                    int option1 = benefits[item - 1] + maxbenefit[item - 1][weight - weights[item - 1]];
                    int option2 = maxbenefit[item - 1][weight];
                    maxbenefit[item][weight] = Math.max(option1, option2);

                } else {
                    maxbenefit[item][weight] = maxbenefit[item - 1][weight];
                }

            }

            // printMatrix(maxbenefit, weights.length, capacity);
        }

        printMatrix(maxbenefit, weights.length, capacity);

        return maxbenefit[weights.length][capacity];
    }

    public static void printMatrix(int[][] matrix, int R, int C) {
        for (int i = 0; i <= R; i++) {
            for (int j = 0; j <= C; j++) {

                System.out.print(matrix[i][j] + " | ");

            }

            System.out.println();
        }

    }

    public static void main(String[] args) {
        int[] weights = new int[] { 2, 3, 4, 5, 6 };
        int[] benefit = new int[] { 3, 4, 8, 9, 9 };
        getMaxBenefit(weights, benefit, 5);
    }

}


texts:
I'm trying to improve my code's performance, and I've found an area where the execution time is being significantly increased. I've had a look through the code but I can't see how I can improve it.

AddData gets called over 200,000 times.

public void AddData(String label, int fromid, int toid, double distance, boolean oneway, int speedlimit)
    {
        currentRoad = new Edge(label, fromid, toid, distance, speedlimit, oneway);

        tempVertex = allVertices.GetValue(fromid);
        tempVertex.addEdge(currentRoad);
        allEdges.AddItem(currentRoad);
        if (!oneway)
        {
            currentRoad = new Edge(label, toid, fromid, distance, speedlimit, oneway);
            tempVertex = allVertices.GetValue(toid);
            tempVertex.addEdge(currentRoad);
        }
    }

The method within the AddData function that takes a large proportion of the time is allEdges.AddItem().

allEdges is a Hash Map containing vectors of Edges. (Edges is a class).

Here is my implementation of the Hash Map AddItem function:

public void AddItem(Edge value)
  {
       if ((noofitems/data.length) > 0.7)
       {
           long time = System.nanoTime();
           EdgeHashPair[] newMap = new EdgeHashPair[data.length * multiplier];
           multiplier = 8;
            for (EdgeHashPair oldMap1 : data)
            {
                if (oldMap1 != null)
                {
                    int index = HashFunction(oldMap1.data.GetItem(0).label);
                    int increment = 1;
                    index = index % newMap.length;
                    boolean inserted = false;
                    while (!inserted)
                    {
                        if (newMap[index] == null)
                        {
                            newMap[index] = oldMap1;
                            inserted = true;
                        }
                        else
                        {
                            index = index + (increment<<1);
                            index = index % newMap.length;
                        }
                    }
                }
            }
           data = newMap;
           System.out.println("Hash map resizing took: " + ((System.nanoTime() - time)/1000000) + "ms");
       }

        int index=HashFunction(value.label);
        index = index % data.length;
        int increment = 1;
        boolean inserted = false;
        while (!inserted)
        {
            if (data[index] == null)
            {
                data[index] = new EdgeHashPair();
                data[index].addItem(value);
                noofitems++;
                inserted = true;
            }
            else
            {
                if (data[index].data.GetItem(0).label.compareTo(value.label) == 0)
                {
                    data[index].addItem(value);
                    inserted = true;
                    noitems++;
                }
                else
                {
                    index = index + (increment<<1);
                    index = index % data.length;
                }
            }
        }
  }

Hash function:

      private int HashFunction(String key)
      {
        // Task 1 code: Hash the key and return a long value
        int code = 29;
        for (int i=0; i < key.length(); i++)
        {
            code = code*53+(key.charAt(i));
        }
        return (code < 0 ? -code : code);
  }

From timings I've done, the loading of data currently takes around 50% of my execution time (around 1000ms), which I feel is extremely high and would love to be able to reduce this.

Edit:
The program is a navigation application, it stores edges and vertices and then calculates many routes.


texts: Making use of a decorator within a python script

texts:
I've written a script in python which is able to collect links of posts and then fetch the title of each post by going one layer deep from the target page.

I've applied @get_links decorator which scrapes the titles from its inner page.

However, I wish to get any suggestion to improve my existing approach keeping the decorator within as I'm very new to work with it.

import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

url = "https://stackoverflow.com/questions/tagged/web-scraping"

def get_links(func):

    def get_target_link(*args,**kwargs):
        titles = []
        for link in func(*args,**kwargs):
            res = requests.get(link)
            soup = BeautifulSoup(res.text,"lxml")
            title = soup.select_one("h1[itemprop='name'] a").text
            titles.append(title)
        return titles
    return get_target_link

@get_links
def get_info(link):
    ilink = []
    res = requests.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    for items in soup.select(".summary .question-hyperlink"):
        ilink.append(urljoin(url,items.get('href')))
    return ilink

if __name__ == '__main__':
    print(get_info(url))


texts: php most efficient way to check if a variable contains only certain chars

texts:
I have a small function which I regularly use to check if a variable contains only [a-z][0-9] and the special chars '-' and '_'. Currently I'm using the following:

function is_clean($string){
    $pattern = "/([a-z]|[A-Z]|[0-9]|-|_)*/";
    preg_match($pattern, $string, $return);
    $pass = (($string == $return[0]) ? TRUE : FALSE);
    return $pass;
}

1 - Can anyone tell me if this is the best/most efficient way to do this and if not try to explain why?

2 - When I view this function through my IDE I get a warning that $return is uninitialized... should I be initializing variables in advance with php, if so how and why?


texts: Creating json objects with undefined properties

texts:
I have the following snippet code which, within a loop, creates a JavaScript object where some of the properties maybe undefined:

reader.on('record', function(record) {

    let p = record.children;
    let player = {};

    // below we create a dynamic key using an object literal obj['name'], this allows use to use
    // the id as the firebase reference id.
    player[p[0].text] = {
        id: parseInt(p[0].text, 10) || "",
        name: p[1].text || "",
        country: p[2].text || ""
    };
};

My question therefore; is there a better way for creating this object via a 'Map' for example? If the properties are undefined then do not add them to the object.

Note: This data is being sent to a Firebase DB, so any undefined values throw an error -- my crude (but working) approach is to add them as an empty string.

Here is a sample of the JSON I would like to see (notice country is not missing from the second player):

{
 "players" : {
    "100001" : {
      "id" : 100001,
      "name" : "Matt Webb",
      "country" : "ENG"
    },
    "100002" : {
      "id" : 100002,
      "name" : "Joe Bloggs",
    }
}


texts: Long SQL query with much duplication between two halves of a UNION

texts:
This works, but it's huge.

We need to repeat each table column on each UNION SELECT, as well as the WHERE clause for DATE comparison.

(
SELECT GROUP_CONCAT(APA_T.district), t.name
FROM tbl_activity AS t
INNER JOIN tbl_activity_package AS ap ON t.id = ap.activity_id
INNER JOIN (
SELECT DISTINCT apa.district AS district, (
SELECT s1.activity_package_id
FROM tbl_activity_package_address s1
WHERE apa.district = s1.district
ORDER BY s1.id DESC
LIMIT 1
) AS idActivityPackage
FROM
tbl_activity_package_address apa
ORDER BY apa.district
) AS APA_T
ON ap.id = APA_T.idActivityPackage
WHERE (ap.publication_date <= CURDATE())
AND (DATE_ADD(ap.publication_date, INTERVAL ap.publication_duration_in_days DAY) >= CURDATE())
GROUP BY t.name
ORDER BY APA_T.district
)
UNION DISTINCT
(
SELECT GROUP_CONCAT(DISTINCT apa2.district ORDER BY apa2.district), t2.name
FROM tbl_activity AS t2
INNER JOIN tbl_activity_package AS ap2 ON t2.id = ap2.activity_id
INNER JOIN tbl_activity_package_address AS apa2 ON ap2.id = apa2.activity_package_id
WHERE (ap2.publication_date <= CURDATE())
AND (DATE_ADD(ap2.publication_date, INTERVAL ap2.publication_duration_in_days DAY) >= CURDATE())
GROUP BY t2.name
ORDER BY apa2.district
)
LIMIT 6, 6

I have removed the WHERE CLAUSE for DATE comparisons, because I can't have it on this fiddle structure, but, the repetition is still an issue. I've been told about INTERSECT but found nothing about that on MySQL.

http://sqlfiddle.com/#!2/37dd94/51


texts: Apply classes to selected XHTML elements based on content

texts:
I wish to take an XHTML source document (e.g. demo.in.xhtml below) and add class attributes to every td element whose content is one of the following six strings: A1, A2, B1, B2, C1, or C2. The corresponding classes will be mytable-a1, mytable-a2, mytable-b1, mytable-b2, mytable-c1, mytable-c2. Any other td elements in the source document should be kept as they are.

demo.xsl performs this as desired, but is not DRY: it uses a six-line xsl:template element per class attribute. How can I refactor this so as to remove the repetition, or generally make demo.xsl more concise and readable?

I am using the following command on Debian Jessie GNU/Linux to perform the transformation:

saxonb-xslt -s:demo.in.xhtml -xsl:demo.xsl -o:demo.out.xhtml

demo.in.xhtml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Title</title>

            A1
            A2
            B1
            B2
            C1
            C2

demo.xsl

<?xml version="1.0"?>
<xsl:stylesheet
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        version="2.0"
        xpath-default-namespace="http://www.w3.org/1999/xhtml">
    <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

    <xsl:template match="//td[.='A1']">
        <xsl:copy>
            <xsl:attribute name="class">mytable-a1</xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//td[.='A2']">
        <xsl:copy>
            <xsl:attribute name="class">mytable-a2</xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//td[.='B1']">
        <xsl:copy>
            <xsl:attribute name="class">mytable-b1</xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//td[.='B2']">
        <xsl:copy>
            <xsl:attribute name="class">mytable-b2</xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//td[.='C1']">
        <xsl:copy>
            <xsl:attribute name="class">mytable-c1</xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//td[.='C2']">
        <xsl:copy>
            <xsl:attribute name="class">mytable-c2</xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>


texts: Optimize Python script for memory which opens and reads multiple times the same files

texts:
I have code that works perfectly, but it uses too much memory.

Essentially this code takes an input file (lets call it an index, that is 2 column tab-separated) that searches in a second input file (lets call it data, that is 4-column tab separated) for a corresponding term in the 1st column which it then replaces with the information from the index file.

An example of the index is:

amphibian   anm|art|art|art|art
anaconda    anm
aardvark    anm

An example of the data is :

amphibian-n is  green   10
anaconda-n  is  green   2
anaconda-n  eats    mice    1
aardvark-n  eats    plants  1

Thus, when replacing the value in Col 1 of data with the corresponding information from Index, the results are as follows:

anm-n   is  green
art-n   is  green
anm-n   eats    mice
anm-n   eats    plants

I divided the code in steps because the idea is to calculate average of the values given a replaced item (Col 4 in data) of Cols 2 and 3 in the data file. This code takes the total number of slot-fillers in the data file and sums the values which is used in Step 3.

The desired results are the following:

anm second  hello   1.0
anm eats    plants  1.0
anm first   heador  0.333333333333
art first   heador  0.666666666667

I open the same input file many times (i.e. 3 times) in Steps 1, 2 and 3 because I need to create several dictionaries that need to be created in a certain order. However, the bottleneck is definitely between Steps 2 and 3. If I remove the function in Step 2, I can process the entire file (13GB of ram in approx. 30 minutes). However, the necessary addition of Step 2 consumes all memory before beginning Step 3.

Is there a way to optimize how many times I open the same input file?

#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import division
from collections import defaultdict

import datetime

print "starting:",
print datetime.datetime.now()

mapping = dict()

with open('input-map', "rb") as oSenseFile:
    for line in oSenseFile:
        uLine = unicode(line, "utf8")
        concept, conceptClass = uLine.split()
        if len(concept) > 2:
                mapping[concept + '-n'] = conceptClass

print "- step 1:",
print datetime.datetime.now()

lemmas = set()

with open('input-data', "rb") as oIndexFile:
    for line in oIndexFile:
        uLine = unicode(line, "latin1")
        lemma = uLine.split()[0]
        if mapping.has_key(lemma):
            lemmas.add(lemma)

print "- step 2:",
print datetime.datetime.now()

featFreqs = defaultdict(lambda: defaultdict(float))

with open('input-data', "rb") as oIndexFile:
    for line in oIndexFile:
        uLine = unicode(line, "latin1")
        lemmaTAR, slot, filler, freq = uLine.split()
        featFreqs[slot][filler] += int(freq)

print "- step 3:",
print datetime.datetime.now()

classFreqs = defaultdict(lambda: defaultdict(lambda: defaultdict(float)))

with open('input-data', "rb") as oIndexFile:
    for line in oIndexFile:
        uLine = unicode(line, "latin1")
        lemmaTAR, slot, filler, freq = uLine.split()
        if lemmaTAR in lemmas:
            senses = mapping[lemmaTAR].split(u'|')
            for sense in senses:
                classFreqs[sense][slot][filler] += (int(freq) / len(senses)) / featFreqs[slot][filler]
        else:
            pass

print "- step 4:",
print datetime.datetime.now()

with open('output', 'wb') as oOutFile:
    for sense in sorted(classFreqs):
                for slot in classFreqs[sense]:
                        for fill in classFreqs[sense][slot]:
                                outstring = '\t'.join([sense, slot, fill,\
                                                       str(classFreqs[sense][slot][fill])])
                                oOutFile.write(outstring.encode("utf8") + '\n')

Any suggestions on how to optimize this code to process large text files (e.g. >4GB)?


texts:
I am creating a NAME column in a DataFrame and set its value based on substrings contained in another column.
Is there a more efficient way to do this?
import pandas as pd
df = pd.DataFrame([['www.pandas.org','low'], ['www.python.org','high']],
     columns=['URL','speed'])
print(df.head())

df['Name'] = df['URL']
print(df.head())

#set Name based on substring in URL
df.loc[df['Name'].str.contains("pandas", na=False), 'Name'] = "PANDAS"
df.loc[df['Name'].str.contains("python|pitone", na=False), 'Name'] = "PYTHON"
print(df.head())


texts: Optimize KnockoutJs Pagination Computed Function

texts:
I have written a function that builds an array of paging options for rendering on the view.

I have modelled it after DataTables for jQuery, a live example with lots of data is available here: http://www.companieshousedata.co.uk/a/490

Is there a better way to write this?
The function also returns ellipsis (as strings) where necessary.

Model/object:

function PageDirection(data) {
    var self = this;
    self.display = data.display;
    self.value = data.value;
    self.disabled = function (currentPage, lastPage) {
        return self.value() > lastPage || self.value() < 1 || self.value() == null;
    };
}

Computed observable:

self.pageDirections = ko.computed(function () {
    var pageIndex = self.pageIndex();
    var lastPage = self.lastPage();

    //Previous
    var directions = [
        new PageDirection({
            display: "Previous",
            value: ko.computed(function() {
                return parseInt(pageIndex, 10) - 1;
            })
        })
    ];

    //6 or less pages
    if (self.lastPage() <= 6) {
        for (var i = 0; i < lastPage; i++) {
            directions.push(new PageDirection({
                display: i + 1,
                value: ko.observable(i + 1)
            }));
        }
    } else {
        if (pageIndex > 4) {
            //1
            directions.push(new PageDirection({
                display: 1,
                value: ko.observable(1)
            }));
            //...
            directions.push(new PageDirection({
                display: "...",
                value: ko.observable(null)
            }));

            if (lastPage - pageIndex <= 3) {
                //last 5
                for (var k = lastPage - 5; k < lastPage; k++) {
                    directions.push(new PageDirection({
                        display: k + 1,
                        value: ko.observable(k + 1)
                    }));
                }
            } else {
                //-1
                directions.push(new PageDirection({
                    display: pageIndex - 1,
                    value: ko.observable(pageIndex - 1)
                }));
                //current
                directions.push(new PageDirection({
                    display: pageIndex,
                    value: ko.observable(pageIndex)
                }));
            }

            if (lastPage - pageIndex > 3) {
                //+1
                directions.push(new PageDirection({
                    display: pageIndex + 1,
                    value: ko.observable(pageIndex + 1)
                }));
                //...
                directions.push(new PageDirection({
                    display: "...",
                    value: ko.observable(null)
                }));
            }
        } else {
            //first 5
            for (var l = 0; l < 5 ; l++) {
                directions.push(new PageDirection({
                    display: l + 1,
                    value: ko.observable(l + 1)
                }));
            }
            //...
            directions.push(new PageDirection({
                display: "...",
                value: ko.observable(null)
            }));

        }
        if (lastPage - pageIndex > 3) {
            //last
            directions.push(new PageDirection({
                display: lastPage,
                value: ko.observable(lastPage)
            }));
        }
    }

    //Next
    directions.push(new PageDirection({
        display: "Next",
        value: ko.computed(function () {
            return parseInt(pageIndex, 10) + 1;
        })
    }));

    return directions;
});

View (for reference):


texts: Regex to parse URLs for their correctness according to RFC 3986

texts:
I recently came to write a regex to parse URLs. Now I wonder, did I miss something? Did I make a mistake or could I have written it cleaner? That's why I'm here.

In order to write the regex, I took this paper as a reference  (together with some Wikipedia articles about URIs/URLs).

//According to http://www.ietf.org/rfc/rfc3986.txt
private static final String URL_UNRESERVED_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String URL_UNRESERVED_SPECIAL_CHARS = "-._~";
private static final String URL_UNRESERVED = URL_UNRESERVED_CHARS + URL_UNRESERVED_SPECIAL_CHARS;
private static final String URL_RESERVED_GEN_DELIMS = ":/?#[]@";
private static final String URL_RESERVED_SUB_DELIMS = "!$&'()*+,;=";
private static final String URL_CHAR_ENCODING_SIGN = "%";

public static final String URL_ALLOWED_CHARS = URL_UNRESERVED + URL_RESERVED_GEN_DELIMS + URL_RESERVED_SUB_DELIMS + URL_CHAR_ENCODING_SIGN;

private static final String REGEX_SCHEME = "[A-Za-z][A-Za-z0-9+.-]*:"; //Also called 'protocol'
private static final String REGEX_AUTHORATIVE_DECLARATION = "/{2}";
private static final String REGEX_USERINFO = "(?:[A-Za-z0-9-._~]|%[A-Fa-f0-9]{2})+(?::(?:[A-Za-z0-9-._~]|%[A-Fa-f0-9]{2})+)?@";
private static final String REGEX_HOST = "(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.){1,126}[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?";
private static final String REGEX_PORT = ":[0-9]+";
private static final String REGEX_PATH = "/(?:[A-Za-z0-9-._~]|%[A-Fa-f0-9]{2})*";
private static final String REGEX_QUERY = "\\?(?:[A-Za-z0-9-._~]+(?:=(?:[A-Za-z0-9-._~+]|%[A-Fa-f0-9]{2})+)?)(?:[&|;][A-Za-z0-9-._~]+(?:=(?:[A-Za-z0-9-._~+]|%[A-Fa-f0-9]{2})+)?)*";
//FRAGMENTs don't need to be parsed as they won't be sent to the server anyways

public static final String REGEX_URL = "(?:" + REGEX_SCHEME + REGEX_AUTHORATIVE_DECLARATION + ")?(?:" + REGEX_USERINFO + ")?" + REGEX_HOST + "(?:" + REGEX_PORT + ")?(?:" + REGEX_PATH + ")*(?:" + REGEX_QUERY + ")?";

The above code snippet is written in Java (which explains for the \\ as they need to be escaped in Strings in order to be taken as literals). I split the regex up into multiple parts in order to increase readability and maintainability (although it technically shouldn't require any).

That would be the regex in its true form as when encountered in the wild:

(?:[A-Za-z][A-Za-z0-9+.-]*:/{2})?(?:(?:[A-Za-z0-9-._~]|%[A-Fa-f0-9]{2})+(?::(?:[A-Za-z0-9-._~]|[%][A-Fa-f0-9]{2})+)?@)?(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.){1,126}[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?::[0-9]+)?(?:/(?:[A-Za-z0-9-._~]|%[A-Fa-f0-9]{2})*)*(?:\?(?:[A-Za-z0-9-._~]+(?:=(?:[A-Za-z0-9-._~+]|%[A-Fa-f0-9]{2})+)?)(?:&|;[A-Za-z0-9-._~]+(?:=(?:[A-Za-z0-9-._~+]|%[A-Fa-f0-9]{2})+)?)*)?

TL;DR Regex above does validate a URL against the defined rules here. I couldn't break it yet, but is it breakable? Can some of it be rewritten in a cleaner fashion?


texts: Refactor multiple condition statements in map function

texts:
I would love some help or some directions with refactoring this block of code. It perfectly works but it kind of looks ugly ;). It was messier but I tried to make it DRY-er.

  const uploadedFiles = images.map((item, index) => {
  if (images.length < 2) {
    if (item.file.name.match(/.(gif)$/i)) {
      return (
        <ImageGif
          key= {index}
          src= {item.blobUrl}
          onClose={this.props.removeImage}
        />
      );
    }

    return (<ImageContainer
      src={item.blobUrl}
      key={index}
      id={index}
      onClose={this.props.removeImage}
    />);
  }

  if (images.length >= 2) {
    if (MAX_SIZE === index + 1) {
      return (<ImageContainer
          src={item.blobUrl}
          key={index}
          id={index}
          onClose={this.props.removeImage}
          hiddenImages={hiddenImages}
        />);
    }
    if (MAX_SIZE !== index + 1) {
      return (<ImageContainer
          src={item.blobUrl}
          key={index}
          id={index}
          onClose={this.props.removeImage}
        />);
    }
  }

  return null;
});

Thank you and have a nice day!


texts: Script for automating regression testing

texts:
I am writing a simple script to automate my regression testing. I am new to bash scripting and my goal is achieve the most efficient and clean code. I have written a simple function to allow me to select which subject I would like to test. This will loop until I select the exit option. Again, this is quite simple; however I am looking for some feedback on how I can improve.

BIO=biology

showMenu () {
    echo "What subject would like to regression test?"
    echo "1) Physics"
    echo "2) Sociology"
    echo "3) Biology"
    echo "4) Quit"
}

while [ 0 ]
do
    showMenu
    read CHOICE
    case "$CHOICE" in

    "1")
        read SUBJECT
        SUBJECT=physics
        echo "LOG: REGRESSION TESTING $SUBJECT" $SUBJECT
        GENERATE_CSS=`lessc /home/developer/oer.exports/css/ccap-$BIO.less > /home/developer/oer.exports/css/ccap-$BIO.css`
        echo "LOG: CSS GENERATION COMPLETE"
        GENERATE_PDF=`python collectiondbk2pdf.py -v -s ccap-$BIO -d ./test-ccap/col$SUBJECT $SUBJECT.pdf -t tempdir/$SUBJECT`
        echo "LOG: GENERATING $SUBJECT PDF WITH $BIO CSS STYLE"
        ;;
    "2")
            read SUBJECT
        SUBJECT=sociology
        echo "LOG: REGRESSION TESTING SOCIOLOGY" $SUBJECT
        GENERATE_CSS=`lessc /home/developer/oer.exports/css/ccap-$BIO.less > /home/developer/oer.exports/css/ccap-$BIO.css`
        echo "LOG: CSS GENERATION COMPLETE"
        GENERATE_PDF=`python collectiondbk2pdf.py -v -s ccap-$BIO -d ./test-ccap/col$SUBJECT $SUBJECT.pdf -t tempdir/$SUBJECT`
        echo "LOG: GENERATING $SUBJECT PDF WITH $BIO CSS STYLE"
        ;;
    "3")
        echo "Biology"
        DIFF=`diffpdf -a --debug=2 /tmp/pdf/diff bio.pdf bio_slicer.pdf`
        echo "LOG: DIFF DEV vs STAGING NOW AVAILABLE FOR PDF VIEW. "
        ;;
    "4")
        echo "Exiting now..."
        exit
        ;;

    esac
done


texts: Exception handling in URL builder method

texts:
I have a method which is part of a request-handling class. It creates a URL, depending on the resource send request.

This is a part of the REST service:

private static URL addQueryToUrl(String qry) {
    try {
        if ("playerProfile".equals(requestingService)) {
            return new URL(PLAYER_URL + qry);
        } else if ("search".equals(requestingService)) {
            return new URL(SEARCH_URL   + qry);
        } else {
            throw new Exception();
        }
    } catch (MalformedURLException e) {
        System.out.println("wrong url format");
    } catch (Exception e) {
        System.out.println("no such a requestingService");
    }
    return null;
}

I have 2 questions:

What exception should I throw if requestingService is not recognized? For now, my method is throwing Exception. Or should I handle such an exception on a higher level, when requestingService has an assigned value?
If no URL is built, what value should I return? NULL? I'm now reading Clean Code by Robert C. Martin and he is stating that returning null is bad practise.


texts:
This is my second attempt to make simple lock using extended assembly.
See https://stackoverflow.com/questions/37241553/locks-around-memory-manipulation-via-inline-assembly/37246263

The code:

static inline void atomic_open(volatile int *gate)
{
    asm volatile (
        "jmp check\n"
        "wait:\n"                      // Set spawning point.
        "pause\n"                      // Stroke your beard. (If you have one.)
        "check:\n"
        "cmp %[open], %[gate]\n"       // Check if gate is open.
        "jne wait\n"                   // If it isn't open, wait. If it is open, go through the gate.
        "lock xadd %[lock], %[gate]\n" // In case you where not alone entering the gate, at least try to be the first one to put the lock.
        "cmp %[lock], %[open]\n"       // Check to see you where the first one who put the lock.
        // "If not, consider thug life..."
        "jne wait\n"                   // If you didn't win, respawn and try again later.
        : [gate] "=m" (*gate)
        : [lock] "r" (1), [open] "r" (0)
    );
}

static inline void atomic_close(volatile int *gate)
{
    asm volatile (
        "pause\n"
        "lock xchg %[lock], %[gate]\n"
        : [gate] "=m" (*gate)
        : [lock] "r" (0)
    );
}

// Usage, example.
volatile int atomic_gate_memory = 0;
void *mymalloc(size_t size)
{
    atomic_open(&atomic_gate_memory);
    void *ptr = malloc(size);
    atomic_close(&atomic_gate_memory);
    return ptr;
}

The question: Will atomic_[open/close] make mymalloc both threadsafe and reentrant?

If no, what is wrong?
If yes, it is still wrong; isn't it?... Give me a good rant about what to consider, what is missing or about better approach. If you want to suggest libraries, please restrict your self to C. I am not experienced enough to bind C++ stuff to other languages, so I often can't use the good stuff over there :'(


texts: Checking to see whether a document can be deleted

texts:
My code looks like this:

public void checkIfCanDelete() throws BusinessException {

    boolean canDelete = canDelete();

    if (canDelete) {

        checkIfLocked();

        if(!editable) {
            throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);
        }

        return;
    }

    if (newDoc) {
        throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_NEW_DOCUMENT);
    }

    if (getSetting().isExcludedFromDeploy()) {
        throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_READ_ONLY_DOCUMENT);
    }

    checkIfLocked();

    // Default Message:
    throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);
}

In my case if canDelete is true, then I have to call checkIFLocked and throw exception if not editable.

Here I think that I have a duplicate code witch is throwing the same exception, or I did called the same method twice in the same method block, which is checkIfLocked.

So is there any way to enhance this code block? Do I need to call the same method twice in the same method block?


texts: Convert 2D list to dict of list of index


texts:
Is there a "best" or more suitable markup to home sliders?

I have the following markup. Since my sliders are related to articles, I decided to put article as the main container.

Note: I am using Owl Slider to convert what is inside .home-slider actually in a slider.

Title

Little Description

        Call to Action Link

Title

Little Description

        Call to Action Link


texts:
I'm doing multithreading at university and we've been asked to implement the producer consumer problem in C.

My code compiles and produces the right result. From debugging it, it seems to be waiting for the semaphores to be freed etc. I'm using Xcode 6.4, hence the need for sem_open() instead of sem_init(). I just have a few questions regarding my code.

Have I done it correctly? Are there any mistakes/bugs?
If I wanted to make buff larger than one, would I set the semaphore fre to have an initial value of size buff? In the producer thread, would I have to call sem_wait(fre) bufftimes before I called sem_post(busy)? And then a similar thing in the consumer thread?

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>

void * producer(void * b);
void * consumer(void * b);

void error(char msg) {
    perror(&msg);
    exit(1);
}

sem_t * fre, * busy;

int size_buff = 1;
char message[] = "Hello!";
int size_msg = sizeof(message);

int main(int argc, const char * argv[]) {

    //declare threads
    pthread_t prod,con;
    int r;

    //create buffer and place it on the stack
    char * buff;
    buff = (char *) malloc(sizeof(char) * size_buff);

    //declare semaphores and initilise them
    char prod_name[] = "/Prod";
    char con_name[] = "/Con";
    fre = sem_open(prod_name, O_CREAT, 0777, 1);
    if ((int) fre == -1)
        error(errno);
    busy = sem_open(con_name, O_CREAT, 0777, 0);
    if ((int) fre == -1)
        error(errno);

    //start threads
    r = pthread_create(&prod, NULL, producer, (void *) buff);
    if (r) {
        error(r);
    }
    r = pthread_create(&con, NULL, consumer, (void *) buff);
    if (r) {
        error(r);
    }

    //unlink semaphores
    sem_unlink(prod_name);
    sem_unlink(con_name);

    pthread_exit(NULL);
    return 0;
}

void * producer(void * b) {
    char * buff = (char *) b;
    int count = 0;

    //loop through message[] and write elements to buffer
    while (count < size_msg) {
        sem_wait(fre);
        strncat(buff,&message[count],1);
        sem_post(busy);
        count++;
    }

    return NULL;
}

void * consumer(void * b) {
    char * recv;
    recv = malloc(sizeof(char) * size_msg);
    char * buff = (char *) b;
    int count = 0;

    //read from the buffer
    while (count < size_msg) {
        sem_wait(busy);
        strncat(recv, buff, 1);
        memmove(buff, buff + 1, 1); //move the elements in the buffer along one, essentailly deleting the element just read
        sem_post(fre);
        count++;
    }
    printf("%s",recv);
    return NULL;
}


texts:
This was a simple IRC bot I threw together a long time ago, found recently, and was curious as to if there were any kind of significant improvements that could be made.

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

public class IRCbot
{
    // server to connect to (edit at will)
    public static string SERVER = "irc.changeme.com";
    // server port (6667 by default)
    private static int PORT = 6667;
    // user information defined in RFC 2812 (IRC: Client Protocol) is sent to the IRC server
    private static string USER = "USER IRCbot 0 * :IRCbot";
    // the bot's nickname
    private static string NICK = "IRCbot";
    // channel to join
    private static string CHANNEL = "#opers";

    static void Main(string[] args)
    {
        NetworkStream stream;
        TcpClient irc;
        string inputLine;
        StreamReader reader;
        StreamWriter writer;

        try
        {
            irc = new TcpClient(SERVER, PORT);
            stream = irc.GetStream();
            reader = new StreamReader(stream);
            writer = new StreamWriter(stream);
            writer.WriteLine("NICK " + NICK);
            writer.Flush();
            writer.WriteLine(USER);
            writer.Flush();

            while (true)
            {
                while ((inputLine = reader.ReadLine()) != null)
                {
                    Console.WriteLine("<- " + inputLine);

                    // split the lines sent from the server by spaces (seems to be the easiest way to parse them)
                    string[] splitInput = inputLine.Split(new Char[] {
                        ' '
                    });

                    if (splitInput[0] == "PING")
                    {
                        string PongReply = splitInput[1];
                        //Console.WriteLine("->PONG " + PongReply);
                        writer.WriteLine("PONG " + PongReply);
                        writer.Flush();
                        //continue;
                    }

                    switch (splitInput[1])
                    {
                        case "001":
                            writer.WriteLine("JOIN " + CHANNEL);
                            writer.Flush();
                            break;
                        default:
                            break;
                    }
                }

                // close all streams (to preserve memory)
                writer.Close();
                reader.Close();
                irc.Close();
            }
        }
        catch (Exception e)
        {
            // shows the exception, sleeps for a little while and then tries to establish a new connection to the IRC server
            Console.WriteLine(e.ToString());
            Thread.Sleep(5000);
            string[] argv = {};
            Main(argv);
        }
    }
}


texts:
Question:
Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in arr1). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.

And my code is:

function updateInventory(arr1, arr2) {

  var newArr = arr1.concat(arr2);

  for(var i = 0; i<newArr.length; i++){
    for(var j = i+1; j<newArr.length; j++){
      if(newArr[i][1] === newArr[j][1]){
          newArr[i][0] += newArr[j][0];
          var index = newArr.indexOf(newArr[j]);
          newArr.splice(index,1);
      }
    }
  }

  return newArr.sort(function(a,b){
    return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0));
  });

}

var curInv = [
  [21, "Bowling Ball"],
  [2, "Dirty Sock"],
  [1, "Hair Pin"],
  [5, "Microphone"]
];

var newInv = [
  [2, "Hair Pin"],
  [3, "Half-Eaten Apple"],
  [67, "Bowling Ball"],
  [7, "Toothpaste"]
];

updateInventory(curInv, newInv);

Output =  [
  [ 88, 'Bowling Ball' ],
  [ 2, 'Dirty Sock' ],
  [ 3, 'Hair Pin' ],
  [ 3, 'Half-Eaten Apple' ],
  [ 5, 'Microphone' ],
  [ 7, 'Toothpaste' ]
];

Can this function be improved?


texts: Detecting line separators and line breaks in Python CSV

texts:
Here is how I'm detecting a field separator and line break in a CSV file for which I do not already know the format. Does this look sufficient, or are there other things I should be adding here?

SEPARATORS=['\x00', '\x01',  '^', ':', ',', '\t', ':', ';', '|', '~', ' ']
LINE_TERMINATORS_IN_ORDER = ['\x02\n', '\r\n', '\n', '\r']

def get_csv_info(f):
    with open(f, 'r') as csvfile:
        line = next(csvfile)
        dialect = csv.Sniffer().sniff(line, SEPARATORS)
        for _terminator in LINE_TERMINATORS_IN_ORDER:
            if line.endswith(_terminator):
                terminator = _terminator
                break
        return (dialect.delimiter, terminator)

get_csv_info('/Users/david/Desktop/validate_headers/artist')
('\x01', '\x02\n')

Note: using the normal csv.Sniffer without params fails most of the time I use it.


texts:
I think the content is too large and I am deeply think about how to refactor it. Does anyone have good advice on refactoring it?

List<AccountEntity> fillNameAccounts = agentDao.getAgentListByIds(accountIdList);
    for (T bean : results)
    {
        for (AccountEntity entity : fillNameAccounts)
        {
            String chineseName = entity.getChineseName();
            String firstName = entity.getFirstName();
            String fillName = StringUtils.isBlank(chineseName) ? firstName : chineseName;
            String entityId = entity.getId().toString();
            if (bean instanceof AgentPostResponseBean)
            {
                if (StringUtils.equals(((AgentPostResponseBean) bean).getParentId(), entityId))
                {
                    ((AgentPostResponseBean) bean).setParentName(fillName);
                }
                if (StringUtils.equals(((AgentPostResponseBean) bean).getPosterId(), entityId))
                {
                    ((AgentPostResponseBean) bean).setPosterName(fillName);
                }
            }
            else if (bean instanceof ImportAgentPostResponseBean)
            {

                if (StringUtils.equals(((ImportAgentPostResponseBean) bean).getParentId(), entityId))
                {
                    ((ImportAgentPostResponseBean) bean).setParentName(fillName);
                }
                if (StringUtils.equals(((ImportAgentPostResponseBean) bean).getPosterId(), entityId))
                {
                    ((ImportAgentPostResponseBean) bean).setPosterName(fillName);
                }
            }
        }
    }


texts: Closing SQL connection for async operations

texts:
The following code executes asynchron on the SQL database. Is the closing of the connection implemented in the right way? Are there any missing features regarding connection handling which need to be added?

public void deleteData(Node node, User user)
        {
            SqlConnection connection = getConnection();
            connection.Open();
            string query = "DELETE FROM NodeUserData WHERE node = @nodeId and userId = @userId;";
            SqlCommand cmd = new SqlCommand(query, connection);
            cmd.CommandType = CommandType.Text;

            try
            {
                cmd.Parameters.AddWithValue("@nodeId ", node.id);
                cmd.Parameters.AddWithValue("@userId", user.id);

                List<Task> asynctasks = new List<Task>();
                asynctasks.Add(cmd.ExecuteNonQueryAsync());
                Task.Factory.StartNew(() => closeConnectionOnFinish(asynctasks, connection));

            }
            catch (Exception ex)
            {
                writeExceptionToLogFile(ex);
            }
        }

And the closeConnectionOnFinish:

public async  void closeConnectionOnFinish(List<Task> _tasks, SqlConnection connection)
        {
            try
            {
                await Task.WhenAll(_tasks);
                connection.Close();
            }
            catch (Exception ex)
            {
                writeExceptionToLogFile(ex);
            }
        }


texts:
I am creating an automated test system (scope bloat - the original intent was a one-off bash automation of a particular test case that has turned into creating a system that will do many other things). I've done a few things similar to this, but somehow never got to using classes; everything was down at the functions level in modules I wrote for past projects.

I'm looking for a simple check/confirmation that I'm approaching this right. It's a communications module intended to connect via telnet to a remote Linux machine, then pull various I2C reads from a device that the Linux machine is connected to.

I want to make sure that I am creating this correctly correctly, and declaring objects correctly so the functions/methods in the class object will perform their individual tasks correctly. I think I'm on the right track but having people a little more experienced take a look couldn't hurt. In particular, I want to make sure I'm setting the class up for instantiation correctly, and declaring self/__init__ in the right way.

Note: the code here worked reasonably well when it was separate functions not gathered under a unifying class structure, but I was mucking about with global declarations which made me nervous, and it took more tweaking than I was happy with.

class Communications: #logs in to the remote as root.
    def __init__(self):
        self.term = telnetlib.open('10.100.100.103')
        print ('logging in now')
        term.read_until(b"ogin: ")
        term.write('root\n')
        time.sleep(3)
        term.read_very_eager()

    #device power-up and power-down
    def node_startup(node):
        if node == 1:
            node_command = 'node_on 1\n'
        elif node == 2:
            node_command = 'node_on 2\n'
        term.write(node_command)
        print (b'powering node', node, 'on\n')

    def node_shutdown(node):
        if node == 1:
            node_command = 'node_off 1\n'
        elif node == 2:
            node_command = 'node_off 2\n'
        term.write(node_command)
        print (b'shutting node', node, ' down')

    #device sample retrieval
    def get_voltage_i2c(bus, device, datapoint, test, node):
        i2c_sample =  term.write('i2cget -y -f %d %d 0x 8b w >> /tmp/%s_%d.txt\n' %(bus, device, test, node))

    def get_current_i2c(bus, device, datapoint, test, node):
        i2c_sample =  term.write('i2cget -y -f %d %d %d %s %d w >> /tmp/%s_%d.txt\n' %(bus, device, datapoint, test, node))

    def get_power_i2c(bus, device, datapoint, test, node):
        i2c_sample =  term.write('i2cget -y -f %d %d %d %s %d w >> /tmp/%s_%d.txt\n' %(bus, device, datapoint, test, node))

    #output-scraper to slurp results from the output files the i2cgets write to. (devnote: incomplete at time of posting)
    def get_sample_results():
        time.sleep(30)
        term.read_very_eager()
        term.write(b'cat ')


texts:
This is my solution to LeetCode – Valid Sudoku in Swift.

class Solution {
    func isValidSudoku(_ board: [[Character]]) -> Bool {
        let count = board.count

        var set = Set<Character>()
        for i in 0..<count{

            //  firstly
            set = Set(board[i])

            var num = board[i].reduce(0 , {(result : Int, char : Character)
                in
                var cent = 0
                if String(char) == "."{
                    cent = 1
                }
                return result + cent
            })

            if num > 0 , count - num != set.count - 1{
                return false
            }
            else if num == 0, set.count != count{
                return false
            }

            // secondly

            set = Set(board.reduce([Character]() , { resultArray, chars in
                return resultArray + [chars[i]]
            }))

            num = board.reduce(0 , {(result : Int, chars : [Character])
                in
                var cent = 0
                if String(chars[i]) == "."{
                    cent = 1
                }
                return result + cent
            })

            if num > 0 , count - num != set.count - 1{
                return false
            }
            else if num == 0, set.count != count{
                return false
            }

            // thirdly
            let characters = board.flatMap{
                return $0
            }

            let fisrtMiddle = ( i/3 ) * 27 + ( i % 3 ) * 3 + 1
            let secondMiddle = fisrtMiddle + 9
            let thirdMiddle = fisrtMiddle + 18
            let arrayThree = [characters[fisrtMiddle - 1], characters[fisrtMiddle], characters[fisrtMiddle + 1],
                                                       characters[secondMiddle - 1], characters[secondMiddle], characters[secondMiddle + 1],
                                                                                characters[thirdMiddle - 1], characters[thirdMiddle], characters[thirdMiddle + 1]]
            set = Set(arrayThree)
            num = arrayThree.reduce(0 , {(result : Int, char : Character)
                in
                var cent = 0
                if String(char) == "."{
                    cent = 1
                }
                return result + cent
            })

            if num > 0 , count - num != set.count - 1{
                return false
            }
            else if num == 0, set.count != count{
                return false
            }
        }

        return true
    }
}

How can I make it shorter in syntax and keep intuitive, like the following Python code?

def isValidSudoku(self, board):
    seen = sum(([(c, i), (j, c), (i/3, j/3, c)]
                for i, row in enumerate(board)
                for j, c in enumerate(row)
                if c != '.'), [])
    return len(seen) == len(set(seen))

The Python code is very Pythonic and short.

How to use Swift syntax power to make my code shorter?

I think Functional is a good choice. RxSwift is welcomed.


texts: Loop each folder and subfolder to get values

texts:
Any tips or improvement to speed my code? I'm looping each file in the specify folder and subfolders. I will open each file and get the values I need and copy it to my activesheet. It is taking quit some time, any tips to help?

FolderName = InputBox("Enter path", "Get File")

Dim fso, oFolder, oSubfolder, oFile, queue As Collection

Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder(FolderName)

Do While queue.Count > 0
    Set oFolder = queue(1)
    queue.Remove 1 'dequeue
    For Each oSubfolder In oFolder.SubFolders
        If UCase(oSubfolder.Name) <> "DO NOT USE" Then
            queue.Add oSubfolder 'enqueue
        Else
        End If
    Next oSubfolder
    Dim lastUsedRow As Long
    lastUsedRow = ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row + 1
    For Each oFile In oFolder.Files
        'Process each file but exclude files such as "~xxxxxx" or thumbs.db or xxxx.tmp files
        If oFile.Type = "Microsoft Excel Worksheet" Then
            If Not oFile.Name Like "*~*" Then
                Dim app As New Excel.Application
                Dim Filename As String
                Filename = oFile.Path
                app.Visible = False 'Visible is False by default, so this isn't necessary
                Dim book As Excel.Workbook
                Set book = app.Workbooks.Add(Filename)
                ActiveSheet.Range("A" & lastUsedRow) = oFile.Name
                ActiveSheet.Range("B" & lastUsedRow) = oFile.DateCreated
                ActiveSheet.Range("E" & lastUsedRow) = book.Sheets("mySheet").Range("D3").Value
                ActiveSheet.Range("F" & lastUsedRow) = book.Sheets("mySheet").Range("G12").Value
                ActiveSheet.Range("G" & lastUsedRow) = book.Sheets("mySheet").Range("C9").Value
                ActiveSheet.Range("H" & lastUsedRow) = book.Sheets("mySheet").Range("C13").Value
                book.Close SaveChanges:=False
                app.Quit
                Set app = Nothing
                lastUsedRow = ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row + 1
            End If
        End If
    Next oFile
Loop


texts:
Someone says that my PHP code is vulnerable to XSS. I asked them what I should do to fix it, but now they don't want to help.

$action=$_REQUEST['action'];
                /* send the submitted data */
    {
    $name=$_REQUEST['name'];
    $email=$_REQUEST['email'];
    $message=$_REQUEST['message'];
    if (($name=="")||($email=="")||($message==""))
        {
        echo "All fields are required, please fill the form again.";
        }
    else{
        $from="From: $name<$email>\r\nReturn-path: $email";
        $subject="Message sent using your contact form";
        mail("email@website.com", $subject, $message, $from);
        echo "Email sent!";
        }
    }
?>


texts: Adding file name information to CSV file columns

texts:
Is there a simple way to combine the functions of this Powershell script?  It would be nice to have it file to one output file instead of several output files.

    GET-DATE
WRITE-EVENTLOG -logname Application -Source BLERG -EventID 1000 -entrytype Information -message "START CBM_PARSE.ps1" -category 1
######################################################################
######################################################################
$SA_Location = "E:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3"
SET-LOCATION $SA_Location
$filenames = @(GET-CHILDITEM $SA_Location -recurse -include *.csv)
$regex = '^([^-]+-[^-]+)-([A-Z])-(\d{4})(\d\d)(\d\d).+'

# $PIPE = ","
$PIPE = "$([char]0x2C)"

# $SLASH = "\"
$SLASH = "$([char]0x5C)"

# $DSLASH = "\"
$DSLASH = "$([char]0x5C)$([char]0x5C)"

foreach ($file in $filenames) {$outfile = "$file" + ".out"
$ReplaceString = ($file | Split-Path -leaf) -replace $regex,'$1|$3-$4-$5|$2:'
((GET-CONTENT $file| Out-String).Substring(7))  | FOREACH-OBJECT -Verbose {
       $_ -replace "\\","\\" `
        -replace $PIPE,"|" `
        -replace "E:",$ReplaceString `
    } | SET-CONTENT  $outfile
}
GET-DATE
WRITE-EVENTLOG -logname Application -Source BLERG -EventID 1002 -entrytype Information -message "END Parsing" -category 1
ECHO "END PARSE"
######################################################################
######################################################################

GET-DATE
WRITE-EVENTLOG -logname Application -Source BLERG -EventID 1000 -entrytype Information -message "START CBM-FS3" -category 1
GET-CONTENT (GET-CHILDITEM "E:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3\*.out") | out-file -encoding "UTF8" "C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3\CBM-FS3.txt"
WRITE-EVENTLOG -logname Application -Source BLERG -EventID 1002 -entrytype Information -message "END CBM-FS3" -category 1
ECHO "END CBM-FS3"
<#
GET-DATE
WRITE-EVENTLOG -logname Application -Source BLERG -EventID 1000 -entrytype Information -message "START CBM-FS56" -category 1
GET-CONTENT (GET-CHILDITEM "C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS56\*.out") | out-file -encoding "UTF8" "C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS04\CBM-FS04.txt"
WRITE-EVENTLOG -logname Application -Source BLERG -EventID 1002 -entrytype Information -message "END CBM-FS56" -category 1
ECHO "END CBM-FS56"
#>
GET-DATE
WRITE-EVENTLOG -logname Application -Source BLERG -EventID 1002 -entrytype Information -message "END CBM_PARSE.ps1" -category 1
ECHO "END END"
######################################################################
######################################################################


texts:
Looking at my code, I feel like it is not instantly clear for someone who did not write it. I feel like readability will be important for me in the future, if I'm ever to write code on an enterprise, or open source project. Do you have any advice as to how I can make this and future C more readable?

#include "datatypes.h"
#include <stddef.h>

//Changes the node's child (if it doesn't exist) to newChild
//or appends newChild to the end of the node's child's sibling list
void addChild ( treeNode *root, treeNode *newChild ) {
  treeNode *temp;
  if ( root->child == NULL ) {
    root->child = newChild;
  } else {
    temp = root->child;
    while ( temp->sibling != NULL ) {
      temp = temp->sibling;
    }
    temp->sibling = newChild;
  }
}

//Returns a new treeNode with default data values or {0,NULL,NULL}
treeNode newNode () {
  treeNode node = {0, NULL, NULL};
  return node;
}

datatypes.h

typedef struct treeNode {
  int n;
  struct treeNode *child;
  struct treeNode *sibling;
} treeNode;

treeNode newNode (); //Returns a treenode with default {0,NULL,NULL}
void addChild ( treeNode *t, treeNode *c ); //Adds child to the given  treeNode


texts: Count pairs in list of integers such that their addition is equal to the input value

texts:
Given a List<int>, the problem I am trying to solve is:
Find the number of unique pairs in List<int> such that their addition is exactly equal to the input value.

The bottleneck is a nested for() loop that I have used to go through the list

// *** OPTIMIZE THIS LOOP ***
for (int i = 0; i < intList.Count - 1; i++)
{
    for (int j = i + 1; j < intList.Count; j++)
    {
        if ((intList[i] + intList[j] == totalValue) &&
              IsPairUnique(intList[i], intList[j]) == true)
        {
            nCombinations++;
        }
    }
}

How can this be made better for performance? I understand 'better' is a subjective word and has no real meaning as such. For a List<int> of size 50000 the code takes about 18 seconds on one of my VM. For 500000 it's way too worst. So, here by 'better' I mean 'faster'. Clearly this problem deserves much less than 18 seconds to solve in my opinion. With 1 Parallel.For() I have managed to get the loop time to 10-11 seconds, but I have a feeling that this whole algorithm needs a fresh set of eyes to look at.

Parallel.For(0, intList.Count - 1,
        i =>
        {
            for (int j = i + 1; j < intList.Count; j++)
            {
                if ((intList[i] + intList[j] == totalValue) && IsPairUnique(intList[i], intList[j]) == true)
                {
                    nCombinations++;
                }
            }
        });

How can I speed this up?
Full code from my console application is as below:

class TestClass
{
    static List<int> compareList = new List<int>();
// GetPossibleCombination method.
// This method finds out the unique number of possible combinations where
// addition of any 2 values from the list is exactly equal to 'totalValue'
static int GetPossibleCombinations(List<int> intList, long totalValue)
{
    // handle edge conditions
    if (intList == null ||
        intList.Count == 0 ||
        intList.Count > 500000 ||
        totalValue > 5000000000)
        return 0;

    compareList.Clear();
    int nCombinations = 0;

    // *** OPTIMIZE THIS LOOP ***
    for (int i = 0; i < intList.Count - 1; i++)
    {
        for (int j = i + 1; j < intList.Count; j++) // start from this element onwards
        {
            if ((intList[i] + intList[j] == totalValue) && IsPairUnique(intList[i], intList[j]) == true)
            {
                nCombinations++;
            }
        }
    }

    return nCombinations;
}

// This method creates a list of possible values we have
static bool IsPairUnique(int v1, int v2)
{
    if (compareList.Contains(v1 * 10 + v2) == true || compareList.Contains(v2 * 10 + v1) == true)
        return false;
    else
    {
        // else add a new one
        compareList.Add(v1 * 10 + v2);
        compareList.Add(v2 * 10 + v1);
    }

    return true;
}

static void Main(string[] args)
{
    int intListSize = 50000; // Optimize it for numbers upto 500,000
    long totalValue = 5000;

    List<int> intList = new List<int>();
    Random r = new Random();

    for (int i = 0; i < intListSize; i++)
    {
        intList.Add(r.Next(0, 10000)); // populate random values.
    }

    Stopwatch sw = new Stopwatch();
    sw.Start();

    // Find the number of unique pairs in 'intList' such that
    // their addition is exactly equal to 'totalValue'
    int res = GetPossibleCombinations(intList, totalValue);

    sw.Stop();
    Console.WriteLine(sw.Elapsed.ToString());
    }
}


texts:
I want to create a Treeview in C# which will group file by prefix (here the prefix is a marked by the separator _). The following files should give this tree:
Files list:

p_a
p_a_test
p_LIG
p_p
p_p_c
p_p_c2
p_p_ccc
p_p_test
p_tres
TestLineGraph1
TestLineGrpah

Corresponding tree:

|--p_
    |--p_a
    |--p_a_test
    |--p_LIG
    |--p_p
    |--p_p_
        |--p_p_c
        |--p_p_c2
        |--p_p_ccc
        |--p_p_test
    |--p_tres
TestLineGraph1
TestLineGraph

And how I do it:

 private GraphUINode(List<string> subNodes, GraphUINode parent, string name, int lvl = 0)
        : base(parent.m_viewDataSubControl)
{
    parent.Nodes.Add(this);
    this.Name = name;
    this.Text = name;

    string currentPrefix = "";
    int pertinentSubNodes = 0;
    while (pertinentSubNodes < subNodes.Count -1 && subNodes[pertinentSubNodes].Split('_').Length < 2+ lvl)
        pertinentSubNodes++;

    for (int i = 0; i <= lvl; i++)
    {
        currentPrefix += subNodes[pertinentSubNodes].Split('_')[i] + "_";
    }
    List<String> children = new List<string>();
    foreach (string child in subNodes)
    {
        // The child is in the same group than the previous one
        if (child.StartsWith(currentPrefix))
        {
            children.Add(child);
        }
        else
        {
            // Create a node only if needed
            if (children.Count > 1)
            {
                 // Create the new node
                new GraphUINode(children, this, currentPrefix, lvl + 1);
                children.Clear();
                children.Add(child);
            }
            else
            {
                if (children.Count == 1)
                {
                    new GraphTemplateNode(this, m_viewDataSubControl, children[0]);
                    children.Clear();
                }
                new GraphTemplateNode(this, m_viewDataSubControl, child);
            }
            currentPrefix = "";
            for (int i = 0; i <= lvl; i++)
            {
                currentPrefix += child.Split('_')[i] + "_";
            }
        }
    }
    if (children.Count == 1)
    {
        new GraphTemplateNode(this, m_viewDataSubControl, children[0]);
        children.Clear();
    }
}

but this looks very dirty. How can I improve it?


texts:
I just recently got back into C++ and did a quick and simple exercise in the Rule of Three. The code for the copy constructor, overloaded assignment operator, and destructor follows below for my class (code is also below), and I was wondering if someone could take a quick look at it and point out anything that I overlooked.

class Coordinate
{
    private:
        int x;
        int y;
        string *name;

    public:
        Coordinate(int X, int Y, string Name)
        {
            this->x=X;
            this->y=Y;
            *(this->name)=Name;
        }

        //COPY CONSTRUCTOR
        Coordinate(const Coordinate& source)
        {
            this->x=source.x;
            this->y=source.y;
            this->name=new string(*(source->name));
        }

        //OVERLOADED ASSIGNMENT OPERATOR
        Coordinate& operator= (const Coordinate& source)
        {
            //check for self-assignment aka Coordinate1=Coordinate1
            if(this==&source)
            {
                return *this;
            }

            this->x=source.x;
            this->y=source.y;
            this->name=*(source->name);

            return *this;
        }

        //DESTRUCTOR
        ~Coordinate()
        {
            delete name;
        }

        void setX(int X)
        {
            this->x=X;
        }

        void setY(int Y)
        {
            this->y=Y;
        }

        void setName(string Name)
        {
            *(this->name)=Name;
        }

        const int getXValue()
        {
            return this->x;
        }

        const int getYValue()
        {
            return this->y;
        }

        const string getName()
        {
            return *(this->name);
        }
};

This post corrects some errors that led to my previous question to be rejected.  I realize that I should have included all the code for my class from the beginning.


texts:
I'm learning Python and I'm building a basic madlib generator. The code below works as expected. I'm just wondering if it uses best practice / can be made better.
def intro():
    print("Welcome to our madlib generator!")
    print("We'll ask you for a serious of words, you'll give us the words, and "
          "we'll make a dope ass story out of it!")
    print("Let's get some info from you first.")
    print("Select the type of madlib you want. ")
    madlib_type = input("1. Short Story\n2. Poem\n")
    return madlib_type

def user_input():
    name = input("Enter a name: ")
    color = input("Enter a color: ")
    animal = input("Enter an animal: ")
    food = input("Enter a food: ")
    item = input("Enter an item: ")
    adjective = input("Enter an adjective: ")
    noun1 = input("Enter a plural noun: ")
    noun2 = input("Enter any noun: ")
    return [name, color, animal, food, item, adjective, noun1, noun2]

class MadlibGenerator:
    def __init__(self, *args):
        self.name = args[0].title()
        self.color = args[1]
        self.animal = args[2]
        self.food = args[3]
        self.item = args[4]
        self.adjective = args[5]
        self.noun1 = args[6]
        self.noun2 = args[7]

    def short_story_generator(self):
        print(f"There once was a person named {self.name}. {self.name} LOVED "
              f"{self.animal}s. They were {self.name}'s favorite animal.")
        print(f"One day, {self.name} was walking down the street wearing "
              f"{self.color} pants and a {self.color} shirt. In fact, all of "
              f"{self.name}'s ")
        print(f"clothes were {self.color}! In one of {self.name}'s hand, "
              f"there was a bright green {self.item}. In the other, there was "
              f"a big {self.food} that {self.name} was waiting to eat!")

    def poem_generator(self):
        print(f"Roses are {self.adjective}")
        print(f"{self.noun1} are blue")
        print(f"I can't start my day without {self.noun2}")

madlib_type = intro()
madlib_input = user_input()
madlib = MadlibGenerator(madlib_input[0], madlib_input[1], madlib_input[2],
                         madlib_input[3], madlib_input[4], madlib_input[5],
                         madlib_input[6], madlib_input[7])
if madlib_type == "1":
    madlib.short_story_generator()
if madlib_type == "2":
    madlib.poem_generator()


texts:
I need a "little" help with an SQL query (MySQL).

I have the following tables:

COURIERS table:

+------------+
| COURIER_ID |
+------------+

DELIVERIES table:

+-------------+------------+------------+
| DELIVERY_ID | COURIER_ID | START_DATE |
+-------------+------------+------------+

ORDERS table:

+----------+-------------+-------------+
| ORDER_ID | DELIVERY_ID | FINISH_DATE |
+----------+-------------+-------------+

COORDINATES table:

+-------------+-----+-----+------+
| DELIVERY_ID | LAT | LNG | DATE |
+-------------+-----+-----+------+

In the real database I have more columns in each table, but for this example the above columns are enough.

What do I need?

An SQL query that returns all couriers [COURIER_ID], their last
delivery [DELIVERY_ID] (based on last START_DATE), the
delivery's last coordinate [LAT and LNG] (based on last DATE) and the remaining orders count (total of orders of the last delivery that have no FINISH_DATE).
A courier can have no deliveries, in this case I want DELIVERY_ID =
NULL, LAT = NULL and LNG = NULL in the result.
A delivery can have no coordinates, in this case I want LAT = NULL
and LNG = NULL in the result.

What was I able to do?

SELECT c.`COURIER_ID`,
       d.`DELIVERY_ID`,
       r.`LAT`,
       r.`LNG`,
  (SELECT COUNT(DISTINCT `ORDER_ID`)
   FROM `ORDERS`
   WHERE `DELIVERY_ID` = d.`DELIVERY_ID`
     AND `FINISH_DATE` IS NULL) AS REMAINING_ORDERS

FROM `COURIERS` AS c
LEFT JOIN `DELIVERIES` AS d USING (`COURIER_ID`)
LEFT JOIN `COORDINATES` AS r ON r.`DELIVERY_ID` = d.`DELIVERY_ID`

WHERE (CASE WHEN
         (SELECT MAX(`START_DATE`)
          FROM `DELIVERIES`
          WHERE `COURIER_ID` = c.`COURIER_ID`) IS NULL THEN d.`START_DATE` IS NULL ELSE d.`START_DATE` =
         (SELECT MAX(`START_DATE`)
          FROM `DELIVERIES`
          WHERE `COURIER_ID` = c.`COURIER_ID`) END)
  AND (CASE WHEN
         (SELECT MAX(`DATE`)
          FROM `COORDINATES`
          WHERE `DELIVERY_ID` = d.`DELIVERY_ID`) IS NULL THEN r.`DATE` IS NULL ELSE r.`DATE` =
         (SELECT MAX(`DATE`)
          FROM `COORDINATES`
          WHERE `DELIVERY_ID` = d.`DELIVERY_ID`) END)
GROUP BY c.`COURIER_ID`
ORDER BY d.`START_DATE` DESC

The problem is that this query is very slow (from 5 to 20 seconds) when I have over 5k COORDINATES and it does not returns all couriers sometimes.


texts:
I wrote a PowerShell script for a superuser question:

  list of all files and directories under a path recursively, without recursing into junction points or links

I have a strong feeling that my code is way too complicated for such a simple task.

function Recurse($path) {

  $fc = new-object -com scripting.filesystemobject
  $folder = $fc.getfolder($path)

  foreach ($i in $folder.files) { $i | select Path }

  foreach ($i in $folder.subfolders) {
    $i | select Path
    if ( (get-item $i.path).Attributes.ToString().Contains("ReparsePoint") -eq $false) {
        Recurse($i.path)
    }
  }
}

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$outputlist = Recurse($scriptPath) | Out-File -Filepath .\outputlist.txt

Short instructions on how to use the script:

Paste the code into a text file and save it as PowerShell (.ps1) script
Place the script inside a folder to list all files+folder recursively without junction folder loops
Execute the script. A new file called outputlist.txt at the same location will appear

Questions:

Can I simplify this PowerShell script anyhow?
Is there a better Out-command where no blank spaces are appended after every line?


texts:
I'm trying to find all possible product of two 3-digit numbers. When I work with small ranges, I'm able to get an output almost instantly but when the ranges are big, it seems to take really long time. I ran the code below and still didn't get an output past 15 minutes. Is there any way to to shorten the time to get the result?

a = []
for x in 100..999
    for y in 100..999
        num = (x * y)
        unless a.include? num
            a.push num
        end
    end
end

p a


texts: Max Contiguous Subarray: Divide and Conquer

texts:
I am conversant with Kadane's Algorithm. This is just an exercise in understanding divide and conquer as a technique.

  Find the maximum sum over all subarrays of a given array of positive/negative integers.

Here is what I have worked on but accumulating sum in solve_partition() looks pretty similar to solve_crossing_partition(), left and right sections. Am I duplicating computation?

I would also appreciate some guidance on the intuition behind moving from mid to low when calculating left_sum: for i in range(m, lo - 1, -1): ...

import math

def max_subarray_sum(A):
    def solve_crossing_partition(m, lo, hi):

        left_sum = -math.inf
        _sum = 0
        for i in range(m, lo - 1, -1):
            _sum += A[i]
            left_sum = max(left_sum, _sum)

        right_sum = -math.inf
        _sum = 0
        for j in range(m + 1, hi):
            _sum += A[j]
            right_sum = max(right_sum, _sum)

        return left_sum + right_sum

    def solve_partition(lo, hi):
        if lo == hi:
            return A[lo]

        max_sum = -math.inf
        _sum = 0

        for i in range(lo, hi):
            _sum += A[i]
            max_sum = max(max_sum, _sum)

        return max_sum

    if not A:
        return 0

    m = len(A) // 2
    L = solve_partition(0, m + 1)
    R = solve_partition(m + 1, len(A))
    X = solve_crossing_partition(m, 0, len(A))

    return max(max(L, R), X)

if __name__ == "__main__":
    for A in (
        [],
        [-2, 1, -3, 4, -1, 2, 1, -5, 4],
        [904, 40, 523, 12, -335, -385, -124, 481, -31],
    ):
        print(max_subarray_sum(A))

Output:

0
6
1479

I followed this ref.


texts: Generate a deck of cards in Clojure / Clojurescript

texts:
I would like to generate a deck of cards:

{:card-id 1 :suit :spade :rank 1}
{:card-id 2 :suit :spade :rank 2}
...
{:card-id 52 :suit :club :rank 13}

And here is my attempt:

(defn new-deck []
  (let [cards (flatten
                 (for [suit [:spade :heart :diamond :club]]
                    (for [rank [1 2 3 4 5 6 7 8 9 10 11 12 13]]
                      {:suit suit :rank rank} )))]
     (map-indexed (fn [idx itm] {:card-id (inc idx)
                                 :suit    (:suit itm)
                                 :rank    (:rank itm)})
                  cards)))

The code works but I think it is awkward. Especially the part where I use map-indexed function to add :card-id to each card.

Any suggestions to improve the code snippet?


texts:
I'm new to Scala and learn it by solving some Project Euler problems. Here is the solution to problem 42 from Project Euler.

The task is to read words from file, then sum ordinal numbers of each character (e.g. sky =19+11+25=55). One need to count all words for which this sum is a triangular number (satisfying \$\frac{n(n+1)}{2}\$ for some \$n\$).

import scala.io.Source
import java.nio.file.Files
import java.nio.file.Paths

def makeTriangleNumber(word:String): Int = {
    word.map(ordinals(_)).reduceLeft(_ + _)
}

val inputFile = Paths.get(args(0));
assert(Files.exists(inputFile))

val ordinals = ((('A' to 'Z').toList) zip Stream.from(1)).toMap
assume(ordinals('Z') == 26)

var triangleNumbers = scala.collection.SortedMap(1 -> 1)
val words = Source.fromFile(inputFile.toUri()).getLines.mkString.replace("\"", "").split(",").toList
var counter = 0

assert(makeTriangleNumber("SKY") == 55)

for (w <- words) {
    var candidate = makeTriangleNumber(w)
    if (!triangleNumbers.contains(candidate) && candidate > triangleNumbers.max._1) {

        var tmp = Stream.from(triangleNumbers.max._2 + 1)
          .map((x) => (x * (x + 1) / 2, x))
          .takeWhile(_._1 <= candidate)

        triangleNumbers = triangleNumbers ++ tmp.toMap
    }
    if (triangleNumbers.contains(candidate)) {
        counter += 1
    }
}
println("The answer is: " + counter)


texts:
I want to create a pytest with a fake utcnow, but also I need to preserve the functionality of all other datetime methods. Simple example here:

import datetime as dt

class FakeTime(dt.datetime):
    fake_time = None

    @classmethod
    def utcnow(cls):
        return cls.fake_time

def str_2_time(str_dt: str) -> dt.datetime:
    """Shortcut to do convert the string to datetime"""
    return dt.datetime.strptime(str_dt, '%Y-%m-%d %H:%M')

def test_patch_datetime():
    for utc_time in ['2019-01-01 10:00', '2019-02-01 13:00', '2019-03-01 16:00']:
        FakeTime.fake_time = str_2_time(utc_time)
        dt.datetime = FakeTime
        assert dt.datetime.utcnow() == str_2_time(utc_time)

Is this the right way?

The method str_2_time just need to show that all other methods of the datetime works fine.