texts:
I'm new to PHP, having coded in Perl and ColdFusion years ago.  In the process of trying to familiarize myself with my new job, I have found some code that would neither seem efficient nor logical, although it does execute properly.

I would like to get feedback about whether one particular piece of code is poorly written, or whether there is in fact a reason it was done this way that is not apparent to someone new to PHP.

The code reads in the contents of a text file, and then sets variables from that file. The input file contains customer records, with fields/columns separated by commas and rows separated by line breaks. After the variables are set, they are sliced and diced in various ways, and at the end of each foreach block, a row is appended to another text file.

The data in the input text file might look something like this:

123456789,MOSName,Bob,Jones,2012 Parakeet Lane
999999999,OtherMOSName,Samantha,Smith,1212 Whatever Street
236751235,YetAnotherMOSName,Tom,Baker,555 Blahblah Boulevard

… and so on.

The below code only includes what is essential to understand the question.

$openit = file('thedirectory/thefilename.txt');

foreach($openit as $values) {

  //acct[0]
  $acct = explode(',', $values, 2);
  //mos[1]
  $mos = explode(',', $values, 3);
  //f_name[2]
  $f_name = explode(',', $values, 4);
  //l_name[3]
  $l_name = explode(',', $values, 5);
  //addr[4]
  $addr = explode(',', $values, 6);

...and so on, for 26 variables.

My inclination would be to simply explode the string once for each row, and place each value in a variable, like:

list($acct, $mos, $f_name, $l_name, $addr) = explode(",", $values);

But instead each variable is being set as an array of N items, where N is the limit attribute of explode, and where the final item includes the entire rest of the string.  Then the actual piece of data is being referenced in the rest of the file using the element of that array where the relevant info is actually stored.  So, acct would be referenced later on in the code as $acct[0], mos would be referenced as $mos[1], etc.

Is this as inefficient and illogical as it seems?  Or what am I missing here? If it is indeed an odd way of doing things, what would have been the motivation to do it this way?


texts:
I was working on a little project that at the end of the script would write to a CSV file. I had to create a function that would combine multiple list elements of the same size into a single one. I would like to see if there is a more efficient way of doing this since I feel the way I did might not be the most efficient one. I created the function due to the need of capturing different number instances from a large CSV file. The reason on hwy I'm using "-" is because it was easier for me to count list elements.

def clean(li):
    tl = len(li)#2
    amount = len(li[0].split(","))
    if tl == 1:
        return ",".join(li)
    else:
        hold = "-," * amount
        hold = hold[:-1]
        d = hold.split(",")
        for i in li:
            con = i.split(",")
            for z, x in enumerate(d):
                if d[z] == con[z]:
                    pass
                elif d[z] > con[z]:
                    d[z] = d[z]
                else:
                    d[z] = con[z]
        return ",".join(d)

a = ['-,-,17,-,-,-,', '-,-,-,17,-,17,']
b = ['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-,5,-,-,-,-,-,-,-,-']
c = ['19,-,-,-,-,-,','-,-,19,-,-,19,','-,-,-,-,19,-,']
ss = clean(a)
se = clean(b)
sq = clean(c)

Output:

-,-,17,17,-,17,-
-,-,-,-,-,-,-,-,-,-,-,-,-,-,-,5,-,-,-,-,-,-,-,-
19,-,19,-,19,19,-


texts: Make password/hash verification algorithm more efficient

texts:
I am trying to guess the paswords from the etc/shadow file(it has 43 user/passwords). And I have been given some hits about the passwords:

Length is between 4 and 8 characters
There can be only 2 numbers and only at the end
Capital letters only in the beginning

So I started just with a small group composed by 4 character with 2 digits in it. But it takes so much time to process:

import crypt
import string
import itertools
import datetime

dir = "shadow3"
file = open(dir, 'r').readlines() #Read all the 43 hashes

username = []
hashed = []
c = 0
cc = 0

for x in file: #Split the hash and the username
    usr, hshd, wtf, iss, this, thing, here, doing, example = x.split(':')
    username.append(usr)
    hashed.append(hshd)
#GRUPO1 4 caracteres 2 numeros
letters = string.ascii_lowercase
digits = string.digits
grupo1=[]
group1=itertools.product(letters,repeat=2)
group1b=itertools.product(digits,repeat=2)
for x in itertools.product(group1,group1b):  #Join the possible iterations
  string=''.join([''.join(k) for k in x])
  grupo1.append(string)
print(len(grupo1))
for y in grupo1:#Get the one of the iterations and try it
  prueba=y
  for x in hashed: #Verify if that iteration is the password to any of the 43 users
    rehashed = crypt.crypt(prueba, x)
    if rehashed == x: #Password is found
        print('La contraseña del usuario ' + username[c] + ' es ' + prueba)
        cc = 1
    c = c + 1
if cc == 0: #after all iterations password is not found
    print('Lo sentimos "' + prueba + '" no es la contraseña de ningun usuario')

How can I improve the efficiency of this? I have a GTX 1070 if it helps for any kind of GPU processing.(I have no idea of this)

Just this small part of 4 characters is taking me for hours, it has still not finished.


texts:
I have joined the Facebook interview recently. And the following question has been asked on the coding interview.

Given a sequence of numbers and a total target, return whether there exists a continuous sub-sequence that sums up to target.
[1, 3, 1, 4, 23], 8 : True (because 3 + 1 + 4 = 8)
[1, 3, 1, 4, 23], 7 : False

I have written the exact pseudo-code to solve the solution.
Which describes the inside of the method. The approach is the sliding window.

The start and end index starts from 0 and through the array it continues to increment the end index and keep adding the existing value array[end] to the temp value if the temp is smaller than the target sum. If every time checks if temp reached the target value, it is it returns true, else if it is bigger form the temp it starts to increment the start index and shrink the window form the beginning. And decreasing the exact value from the temp. And keep checking if it is equal to the target value after it is decreased.

After the interview result came, they told me that "I have solved it wrong because the sequence must be contiguous". I am %100 sure that this is the correct answer, and they saying is I was wrong and I should try 12 months later.

Please put your comment about my solution? What would be the problem to cause misunderstanding?

// [1, 3, 1, 4, 23]

int start  = 0
int end  = 0

int total = 0;
int target = 8;

while(end < arr.length){

  total += arr[end]; // 1 3 1 4 = 9

  while(total>=target){

     total-=arr[start]; // 8

     start++;

     if(total == target){
       return true;
     }

  }
  end++;
}

return false;


texts:
I am trying to write a single function that will read a certain number of bytes from a C file, or the entire file, based on the arguments. I want it to be memory-safe of course, and deal with NULL terminators and the like. Not only that, but it should be efficient.

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

char *read(FILE *file, long bytes) {
    /* This function takes a FILE pointer <file> and reads <bytes> bytes from it. These
     * bytes are returned as a char* back to the calling function and should be freed
     * since they were malloc'd. This function was an attempt to recreate the
     * .read( [bytes] ) method on python file objects */

    /**********************************
     Set bytes to 0 to read entire file
     **********************************/

    long fileSize = 0; // File size to zero before byte check

    if (bytes == 0) {
        fseek(file, 0L, SEEK_END); // seek to end
        fileSize = ftell(file); // find size of file by checking end
        rewind(file); // back to the beginning for reading
    } else {
        fileSize = ++bytes; // extra byte for NULL
    }

    char buffer[16]; // We will read the file 16 bytes at a time
    char *file_out = malloc(fileSize + 1);
    if (file_out == NULL) {
         fputs("Could not allocate enough memory", stderr);
         exit(EXIT_FAILURE);
    }

    while (fgets(buffer, 16, file) != NULL) {
        strncat(file_out, buffer, 16);
    }

    return file_out;
}

Is this efficient enough for large files and fringe cases?


texts: Selecting/ Deselecting All from Checkbox

texts:
$scope.selectAllProctoringUser = function(checked) {
    try {
        for (var k = 0; k < $scope.scheduleUsers.lstOnlineProctoring.length; k++) {
            $scope.scheduleUsers.lstOnlineProctoring[k].selected = checked;
            if (checked) {
                let flag = 0;
                if($scope.selectedUserListOP.length == 0) {
                    $scope.selectedUserListOP.push($scope.scheduleUsers.lstOnlineProctoring[k]);
                    flag = 1;
                } else {
                    angular.forEach($scope.selectedUserListOP, (el, idx) => {
                        if(el.StudentScheduleUsrID === $scope.scheduleUsers.lstOnlineProctoring[k].StudentScheduleUsrID) {
                            flag = 1;
                        }
                    });
                }
                if(flag === 0){
                    $scope.selectedUserListOP.push($scope.scheduleUsers.lstOnlineProctoring[k]);
                }

            } else {
                angular.forEach($scope.selectedUserListOP, (el, idx) => {
                    if(el.StudentScheduleUsrID === $scope.scheduleUsers.lstOnlineProctoring[k].StudentScheduleUsrID) {
                        $scope.selectedUserListOP.splice(idx, 1);
                    }
                });
            }
        }
    } catch(e) {
                console.log('Method: selectAllProctoringUser:  ' + e.message);
      }
}

I had replaced the above with below snippets and working perfectly

$scope.selectAllProctoringUser = function(checked) {
    try {
        $scope.scheduleUsers.lstOnlineProctoring.forEach(x => {
            x.selected = checked;
            if(checked){
                if($scope.selectedUserListOP.filter(m => m.StudentScheduleUsrID == x.StudentScheduleUsrID).length == 0)
                    $scope.selectedUserListOP.push(x);
            } else if(!checked){
                if($scope.selectedUserListOP.filter(m => m.StudentScheduleUsrID == x.StudentScheduleUsrID).length > 0)
                    $scope.selectedUserListOP.splice(x, 1);
            }
        });
    } catch(e) {
                console.log('Method: selectAllProctoringUser:  ' + e.message);
      }
}

If the above code could still get reduced? or written instead making use of filter operator

Are there any use cases, substituting the above code may cause failure or exceptions?

Expecting more solutions from what that I had initially coded


texts: Are nested calls to `asyncio.gather()` dangerous?

texts:
I wrote this ~100 line script recently, where I tried out Python's asyncio library. When it comes to asynchronous programming in Python, I just have 2 days of experience. I spent the last two days reading about it for the first time.
Based on all my readings and understanding, I think, there is no mess-up in the script, but there are some specific parts which I am a little skeptical about because of my inexperience in this area.
To be specific I am doing a asyncio.gather(<unpacking a value here>, return_exceptions=True). This is the relevant function:
async def main():
districts = json.loads(os.environ['DISTRICTS'])
while True:
    start = perf_counter()
    async with aiohttp.ClientSession() as session:
        results = await asyncio.gather(*(process_district(d, session) for d in districts), return_exceptions=True)
        for district, result in zip(districts, results):
            if isinstance(result, Exception):
                error = f"exception occurred when district {district['district_id']} was being processed: {result}"
                print(error)
                await send_telegram(os.environ['BOT_CHAT_ID'], error, session)
    print(f'time taken: {perf_counter() - start} seconds')
    sleep(int(os.environ['SLEEP_SECONDS']))

Now somewhere in the function call hierarchy of process_district(), there comes another asyncio.gather(), without return_exceptions flag. This is the relevant function:
async def send_notifications(chat_ids, cova_18_message, cova_45_message, covi_18_message, covi_45_message, session):
await asyncio.gather(
    send_telegram(chat_ids.get('cova_18'), cova_18_message, session),
    send_telegram(chat_ids.get('cova_45'), cova_45_message, session),
    send_telegram(chat_ids.get('covi_18'), covi_18_message, session),
    send_telegram(chat_ids.get('covi_45'), covi_45_message, session)
)

My script is working all well as expected. However, I am a little bit uncertain if I am just doing anything wrong/bad here. To be specific, some of the worries that I have:

Is it fine where asyncio.gather() is "nested" in the hierarchy call. Can it have any bad implications?
My "inner" asyncio.gather() doesn't have return_exceptions=True. To be honest, this looks completely fine to me, but still, is there any catch / any code smell here? (I have also tested this, where the exceptions raised by the coroutines inside the inner gather() are also being awaited and iterated at the outer gather())
Any other issue that is there with the way my script is written? Other than my inexperience, the only reason I am sceptical about this is, I was not able to find a single example on the wide Internet where people are calling gather() "inside" gather().


texts:
I have implemented a thread safe vector, based on std::thread and std::vector. I am new to many of the patterns used in threading and was wondering if there's a more efficient way the locking can be implemented? Also I'm not sure what the best name is to give variables that just get stored right away (i.e. in).

Here is SafeVector.hpp

#ifndef SAFEVECTOR_HPP
#define SAFEVECTOR_HPP

#include <vector>
#include <mutex>
#include <condition_variable>
#include <string>

class SafeVector {
public:
    SafeVector() : vec(), mut(), cond() {}
    SafeVector(const SafeVector& orig) : vec(orig.vec), mut(), cond() {}
    ~SafeVector() {}

    void insert(std::string in, const int index);
    void push_back(std::string in);
    std::string& operator[](const int index);
    std::vector<std::string>::iterator begin();
    std::vector<std::string>::iterator end();
    std::vector<std::string> toVector();

private:
    std::vector<std::string> vec;
    std::mutex mut;
    std::condition_variable cond;
};

#endif /* SAFEVECTOR_HPP */

Here is SafeVector.cpp

#include <string>
#include <utility>
#include "SafeVector.hpp"

void SafeVector::insert(std::string in, const int index)
{
    std::lock_guard<std::mutex> lock(mut);
    vec[index] = std::move(in);
    cond.notify_one();
}

void SafeVector::push_back(std::string in)
{
    std::lock_guard<std::mutex> lock(mut);
    vec.push_back(std::move(in));
    cond.notify_one();
}

std::string& SafeVector::operator[](const int index)
{
    return vec[index];
}

std::vector<std::string>::iterator SafeVector::begin()
{
    return vec.begin();
}

std::vector<std::string>::iterator SafeVector::end()
{
    return vec.end();
}

std::vector<std::string> SafeVector::toVector()
{
    return vec;
}

Currently, these are the only functions I need to use on vectors but if I decide to implement more, I'm assuming the rest would be done in the same way.


texts: Parsing XML data to be put onto a site with jQuery

texts:
I will preface by saying that this data set is much larger than what I have here. I'm having to loop through an XML file to get data and display it on a site with jQuery. I have to use jQuery because I'm working within a framework that I can't edit so I'm having to manipulate the data after the fact. This is causing the site I'm working on to slow significantly. I know that that's just the nature of what I'm doing but I'm running a loop inside a loop which I know can be pretty slow, especially when deal with 1,000 entries in an XML file. I'm curious if there's a way for me to do this in a more efficient way.

I'm basically looping through the data and on each iteration I'm grabbing that entries attributes and then having to loop through all the data within that iteration to compare the data with the rest of the data in the file. It seems like there's a better way to do this but I can't seem to figure it out.

If you need more clarification, let me know and I will provide it. I've pared the data down quite a bit so it's easier to handle and look at.

My XML is set up like this:

<Data>
    <Category>
        <category_number>1</category_number>
        <parent_number>4</parent_number>
        <category_name>This is a test Category</category_name>
    </Category>
    <Category>
        <category_number>2</category_number>
        <parent_number>3</parent_number>
        <category_name>This is another test Category</category_name>
    </Category>
    <Category>
        <category_number>3</category_number>
        <parent_number>4</parent_number>
        <category_name>This is yet another test Category</category_name>
    </Category>
</Data>

My HTML is set up like this:

This is a parent category. Category 4. A new list will be put in here with this categories child categories.

This is a parent category. Category 2. A new list will be put in here with this categories child categories.

My jQuery is as follows:

$.ajax({
    url: "/sample_url.xml",
    type: "GET",
    dataType: "html",
    success: function(data) {
        var xml = $.parseXML(data);
        $(xml).find('category_number').each(function(){
            category_number = $(this).text();
            var parent_number = $(this).parent().find('parent_number').text();
            var category_name = $(this).parent().find('category_name').text();

            var sub_array = [];

            //GET CATEGORIES SUB-CATEGORIES
            $(this).closest('Data').find('parent_number').each(function(){
                if($(this).text()==category_number){
                    var category_id = $(this).parent().find('category_number').text();
                    sub_array.push('
' + $(this).parent().find('category_name').text() + '
');
                }
            });

            $('ul#category_list').each(function(){
                if($(this).attr('class')==parent_number){
                    $(this).append('

');
                    $('ul#' + category_number).html(sub_array.join(""));
                }
            });
        });
    }
});


texts:
Taking a look at the code, is there a better way in JavaScript to prevent so much repetition. In particular, re declaring the variables like moduleOptions, removeBtn, moveUp?

I tried putting them in their own key values pairs. Unfortunately, that causes them to be called right away, and the selectors that I'm querying are not ready until the toggleModuleOptions.show() and toggleModuleOptions.hide() functions are called.

  var toggleModuleOptions = {
    show: function() {
      var moduleOptions = visualModules.activeModuleContainer.querySelector('.module-options');

      moduleOptions.classList.add('module-options--active');

      removeBtn = visualModules.activeModuleContainer.querySelector('.js-remove');
      removeBtn.addEventListener('click', deleteModule);

      moveUp = visualModules.activeModuleContainer.querySelector('.js-index-up');
      moveUp.addEventListener('click', move);
      moveUp.direction = 'up';

      moveDown = visualModules.activeModuleContainer.querySelector('.js-index-down');
      moveDown.addEventListener('click', move);
      moveDown.direction = 'down';
    },
    hide: function() {
      var moduleOptions = visualModules.activeModuleContainer.querySelector('.module-options');

      if(moduleOptions) {
        moduleOptions.classList.remove('module-options--active');
      }

      removeBtn = visualModules.activeModuleContainer.querySelector('.js-remove');
      removeBtn.removeEventListener('click', deleteModule);

      moveUp = visualModules.activeModuleContainer.querySelector('.js-index-up');
      moveUp.removeEventListener('click', move);

      moveDown = visualModules.activeModuleContainer.querySelector('.js-index-down');
      moveDown.removeEventListener('click', move);
    }
  }


texts: Find a triangle in a graph represented as an adjacency list

texts:
I have a graph represented as an adjacency list. I need to find a triangle in this graph. A triangle is a triple of vertices u, v and w, such that (u, v), (v, w) and (u, w) are edges of the graph. The graph does not necessarily needs to be undirected.

I found the following pseudocode for solving the problem:

function contains-cycle(g):
    for each edge (u, v) in g:
        for each vertex w in g:
            if (v, w) is an edge and (u, w) is an edge:
                return true
    return false

Now, this pseudocode is really easy and intuitive to understand, and I implemented very fast my "contains cycle" function using my adjacency list representation of a graph that I had implemented some time ago.

Note that checking if (v, w) is an edge in an adjacency matrix representation of a graph is a constant time operation, but not in an adjacency list, where the complexity of that operation is linear in the size of the adjacency list.

Thus, with an adjacency matrix representation of a graph, the above algorithm runs roughly in O(n3) time, since iterating through the edges requires O(|V|2) and through the vertices O(|V|) times.

On the other hand, using an adjacency list representation, the time complexity of the "contains cycle" algorithm is even worse, as far as I have understood, unless we can iterate through the edges in linear time with respect to the number of edges. We could do this, if we keep track of a list of all edges in the graph while constructing the graph, but I would like to avoid this, and try to find an alternative solution.

The following is my implementation using Python 3:

def is_an_edge(u, v):
    """Returns true if v is an adjacent node to u.

    Running time complexity: O(number of adjacent nodes to u).

    :type u : GraphNode
    :type v : GraphNode
    """
    for w in u.get_adjacent_nodes():
        if w == v:
            return True
    return False

def find_triangle(g):
    """Returns true if there's a triangle in g.

    A triangle in a graph is a triple of vertices u, v and w,
    such that all three edges  (u, v), (v, w) and (u, w) are in the graph.

    :type g : Graph
    """
    for u in g.get_nodes():
        for v in u.get_adjacent_nodes():
            for w in g.get_nodes():
                if is_an_edge(v, w) and is_an_edge(u, w):
                    return True
    return False

First of all, is my algorithm correct?

Its time complexity should be roughly O(n4), which is very high for a simple idea, algorithm.

Is there a better way to do what I want to achieve without keeping track of all edges of the graph?


texts: Fast case-insensitive hash-code for specific codes

texts:
I'm trying to fix another bottleneck identified with a profiler (dotTrace). This time it's a case insensitive hash-code.

Currently I'm using the StringComparer.OrdinalIgnoreCase as a comparer for a dictionary and a custom  implementaion of an IComparable<string>. With 40 millions calls it costs me ~14 seconds. This is too much as there will be more calls in future. I'd like to replace it with an int to improve the lookup time.

The values I'm working with are in the format and between 1A and 99Z. There will never be other codes.

I've build a proof-of-concept for encoding and decoding these codes that works like that:

I shift each char to the left by 8 bits from left to right: for example 5A and 20F.

               5        A
       2       0        F
-------- ------- --------

The decoder unshifts them and rebuilds the string (mainly for debugging purposes as I actually won't be doing this much). Additionaly if a letter exceeds the A-Z alphabet its case is fixed to upper-case.

static class CaseInsensitiveCoordinate
{
    private const int AlphabetLength = ('Z' - 'A');
    private const int AlphabetsDistance = ('a' - 'Z');
    private const int CaseFix = AlphabetLength + AlphabetsDistance;

    public static int Encode(this string value)
    {
        var result = 0;

        // Assume the code has only two chars.
        result += (int)value[0] << 8;

        // Oh, there are tree, then shift what we have and add the next one.
        if (value.Length == 3)
        {
            result <<= 8;
            result += (int)value[1] << 8;
        }

        // Finally add the letter and fix the casing.
        var letter = (int)value[value.Length - 1];
        if (letter > 'Z')
        {
            letter -= CaseFix;
        }

        return result += letter;
    }

    public static string Decode(this int value)
    {
        // Unshift all values and rebuild the string.
        return
            (value > "9Z".Encode())
                ? new string(new[]
                {
                    (char)((value & 0xFF0000) >> 16),
                    (char)((value & 0xFF00) >> 8),
                    (char)(value & 0xFF)
                })
                : new string(new[]
                {
                    (char)((value & 0xFF00) >> 8),
                    (char)(value & 0xFF)
                });
    }
}

Simple Stopwatch measurements in LINQPad (compiled as release) result in a difference of about ~1.5 seconds for 40 million loops between the string-comparer and my hash-code.

void Main()
{

    var dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase) { ["5A"] = new object() };
    var dic2 = new Dictionary<int, object> { [13633] = new object() };

    var count = 40_000_000;

    var sw = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        var result = dic["5A"];
    }
    sw.Elapsed.Dump();

    sw = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        var result = dic2["5A".Encode()];
    }
    sw.Elapsed.Dump();
}

I call them hash-codes because I'm going to use them as such but at the same time they are a numeric representation of the string-code and they also need to remain sortable (they are use in a SortedHashSet).


texts:
I'm working on a class to parse RSS feeds using SyndicationFeed. (related to Downloading data using HttpClient).  I'm trying to write this so it can be unit-tested, but there's an awful lot of boring setup boilerplate before I get to the important stuff.

My data source sometimes sends invalid RSS XML according to XmlReader (in the pattern of <description>This article ... <mark>keyword</mark> ...</description>), so I need to sanitize the input (for political reasons, I can't just say "this won't work until they fix their end").

I started with the following method, which does a few too many things and isn't very testable.  My important logic starts after the SyndicationFeed.Load() call, but any tests require that all the XML handling works correctly.

public virtual FeedSummary ParseResponse(string data)
{
    var response = new FeedSummary();

    var doc = new XmlDocument();
    doc.LoadXml(data);

    var builder = new StringBuilder();
    var xmlSettings = new XmlWriterSettings();
    xmlSettings.OmitXmlDeclaration = true;
    xmlSettings.ConformanceLevel = ConformanceLevel.Fragment;
    var htmlWriter = XmlWriter.Create(builder, xmlSettings);

    var transformationDocument = new XmlDocument();
    transformationDocument.LoadXml(this.XsltSource);
    //The xslt source can be passed in via the class constructor so
    //I can test this using the identity transform
    var compiledTransform = new XslCompiledTransform(true);
    compiledTransform.Load(transformationDocument);
    compiledTransform.Transform(doc, htmlWriter);

    var reader = XmlReader.Create(new StringReader(builder.ToString()));
    var feed = SyndicationFeed.Load(reader);
    reader.Close();

    var totalResults = feed.ElementExtensions.Single(x => x.OuterName == "totalResults");
    response.TotalResults = Int32.Parse(totalResults.ToString());
    foreach (var item in feed.Items)
    {
        var hits = new List<SearchHit>();
        var searchItem = new SearchHit()
        {
            Title = item.Title.Text,
            ItemUrl = item.Links[0].Uri,
            Description = item.Summary.Text
        };
        hits.Add(searchItem);
        response.TopHits = hits;
    }

    return response;
}

I did try breaking it up into multiple methods, coming together in this one:

public FeedSummary ParseResponse(string rssFeed)
{
    var doc = LoadXml(rssFeed);
    var cleanData = SanitizeXml(doc);
    var feed = CreateFeed(cleanData);
    return ParseFeed(feed);
}

This is better than the first one in that each step can be tested independently, but my top-level method still has the same testability problems.  I'd appreciate any thoughts on improving code organization, especially with respect to improving testability.


texts:
I have created this program about using a singly linked list class that implements several functions: Add, Display and Sort.

Could you suggest me how to make my code better and which functions to include in the future?

#include <iostream>
using namespace std;
// ----------------------------------------------------
class Node {
private:
    int value;
    Node *next;
public:
    Node(int v) { value = v; next = NULL; }
    void Add(int v);
    void Print();
    void SortValues();
    void SortNodes();
};
// ----------------------------------------------------
void Node::Add(int v)
{
    Node *newItem = new Node(v);
    Node *temp = this;
    while (temp->next != NULL)
        temp = temp->next;
    temp->next = newItem;
}
void Node::Print()
{
    Node *temp = this;
    while (temp != NULL)
    {
        cout << "  " << temp << " : " << temp->value << endl;
        temp = temp->next;
    }
}
void Node::SortValues()
{
    Node *swapCandidate = next;
    Node *current;
    Node *min;
    //    L* temp;
    // Look at every value
    while (swapCandidate != NULL)
    {
        current = swapCandidate;
        min = swapCandidate;
        // ------------------------------
        while (current != NULL)
        {
            if (current->value < min->value)
            {
                min = current;
            }
            current = current->next;
        }
            if(min != swapCandidate)
            {
                int tempV = min->value;
                min->value = swapCandidate->value;
                swapCandidate->value = tempV;
            }
         // ------------------------------
         swapCandidate = swapCandidate->next;
         }
     }
     // ----------------------------------------------------
void main()
{
// Sort - moving values
Node *myList = new Node(0);
myList->Add(15);
myList->Add(3);
myList->Add(20);
myList->Add(1);
myList->Print();
myList->SortValues();
cout << "------------------------------" << endl;
    myList->Print();
system("pause");
}


texts: Basic folder tree with a list of strings

texts:
I am building up a basic folder tree with a list of strings in the form /root/node/node/node. Here is the basic algorithm I am using currently to build this collection and fill in my TreeGridView:

// This method gets the list of folders and leaves, then trims out any folder paths
// that are already encompassed in a larger folder path, the idea is that it causes
// less work when adding the actual tree nodes (I may be wrong in this assumption)
List<string> BuildFinalList()
{
    // This list is a collection of root folder paths and leaf folder names
    // i.e. pair("/root/node/node", "node"), pair("/root/node", "node)
    List<KeyValuePair<string, string>> folders = GetListOfFolders();
    var paths = new List<string>();
    foreach(var folder in folders)
    {
        var leaf = folder.Value;
        var root = folder.Key;
        paths.Add(string.Concat(root, "/", leaf);
    }
    paths.Sort(_INVERSE_LENGTH_COMPARE); // this sorts the list longest to shortest

    // Iterate the computed paths from longest to shortest, if a path is not
    // encompassed by an existing path in the final list, add it to the
    // final list, otherwise just move to the next path
    var finalList = new List<string>();
    foreach(var path in paths)
    {
        bool found = false;
        foreach(var item in finalList)
        {
            if (item.StartsWith(path, StringComparison.Ordinal))
            {
                found = true;
                break;
            }
        }

        if (!found)
        {
            finalList.Add(path);
        }
    }
    return finalList;
 }

Once I have the final list built, I then add the nodes to the tree (for simplification, I have removed the calls to end update and begin update of the tree that contains the root node):

void FillTreeNodes(TreeNode root)
{
    var rootText = root.Text;
    var rootTextLength = rootText.Length;
    var nodeStrings = BuildFinalList();
    foreach(var nodeString in nodeStrings)
    {
        var roots = nodeString.Split(new char[] { '/' },
            StringSplitOptions.RemoveEmptyEntries);

        // The initial parent is the root node
        var parentNode = root;
        var sb = new StringBuilder(rootText, nodeString.Length + rootTextLength);
        for(int rootIndex = 0; rootIndex < roots.Length; rootIndex++)
        {
            // Build the node name
            var parentName = roots[rootIndex];
            sb.Append("/");
            sb.Append(parentName);
            var nodeName = sb.ToString();

            // Search for the node
            var index = parentNode.Nodes.IndexOfKey(nodeName);
            if (index == -1)
            {
                 // Node was not found, add it
                 var temp = new TreeNode(parentName, 1, 1);
                 temp.Name = nodeName;
                 parentNode.Nodes.Add(temp);
                 parentNode = temp;
            }
            else
            {
                 // Node was found, set that as parent and continue
                 parentNode = parentNode.Nodes[index];
            }
        }
    }
}


texts: jQuery click handlers to show one of four containers

texts:
I have a navigation bar that when the list elements are clicked their respective body container appears and the other body containers disappear.

navigation

HOME

ABOUT

PROJECTS

CONTACT

body containers:

home

about

projects

contact

JQuery:

$(document).ready(function () {
    $("#home").click(function(){
        event.preventDefault();
        $("#aboutBodyContainer").hide();
        $("#projectsBodyContainer").hide();
        $("#contactBodyContainer").hide();
        $("#homeBodyContainer").fadeIn(1500);
    });
    $("#about").click(function(){
        event.preventDefault();
            $("#homeBodyContainer").hide();
            $("#projectsBodyContainer").hide();
            $("#contactBodyContainer").hide();
            $("#aboutBodyContainer").fadeIn(1500);
    });
    $("#projects").click(function(){
        event.preventDefault();
        $("#homeBodyContainer").hide();
        $("#aboutBodyContainer").hide();
        $("#contactBodyContainer").hide();
        $("#projectsBodyContainer").fadeIn(1500);
    });
    $("#contact").click(function(){
        event.preventDefault();
        $("#homeBodyContainer").hide();
        $("#projectsBodyContainer").hide();
        $("#aboutBodyContainer").hide();
        $("#contactBodyContainer").fadeIn(1500);
    });
});

As you can see the functions are almost identical. Is there a way I can reduce the amount of code here?


texts: Traversing javascript/json based on a dot-separated lookup string

texts:
I have an object of arbitrary depth, and a string (or array) containing the keys which have to be traversed to get to the value.

As far as I know, there's no method to get to the value directly:

var object = {
    user: {name: 'bob'},
    'user.name': 'error'
};

object['user.name']; // contains 'error'

And the usual:

object['user']['name'];

is not possible without doing some very dirty eval stuff, because you do not know how far you will need to traverse through the object beforehand.

So I think this is only solvable using a recursive function:

var object = {
    company: {
        users: [
            {name:'alice',age:'20'},
            {name:'bob',age:'22'},
            {name:'eve',age:'30'},
        ]
    }
};

lookup = function recurse(array,object) {
    var next = (array.length) ? object[array.shift()] : object;
    return (next instanceof Object && next[array[0]]) ? recurse(array,next) : next;
}

var search = 'company.users.0.name';
lookup(search.split('.'), object);

I think this works well enough, but would love some feedback.

Efficiency is important here, could I rewrite the function to shave of a few milliseconds somewhere? Are there any pitfalls, bugs or exceptional cases to consider?


texts:
I have files in subfolders on a network drive. I want to create a list of files, and insert that list into an Oracle table.

I can successfully iterate through the files in the subfolders and do the insert:

Loop through a user-defined list of subfolders called subfolder_list (I only want the files in specific subfolders; not all of the subfolders)
Loop through the files in each subfolder
Using an ArcSDESQLExecute class in the ArcPy site package, insert each file name into the records table

import arcpy
import os

db_conn_folder = r'C:\connection\folder\connection.sde'
conn = arcpy.ArcSDESQLExecute(db_conn_folder)

folder = r'\\my\network\folder'
subfolder_list = [r'\DRAWINGS', r'\DOCUMENTS', r'\VIDEOS']

#Delete all records in the table
db_exec = conn.execute('delete from records')

#Loop through the list of subfolders
for i in subfolder_list:
    #loop through the files in the subfolder
    for filename in os.listdir(folder + i):
        #insert the file names into the table
        db_exec = conn.execute('insert into records (file_name) values (' + filename + '\')')

#Commit the insert statements
db_exec = conn.execute('commit')

print "Complete."

The SQL is a little hard to read with all the python parsing and formatting. Plain-language SQL would look like this:

delete from records;
insert into records (file_name) values ('plan_profile_1.tif');
commit;

While the code works just fine, I'm wondering, can it be improved?

(I can count the number of Python scripts I've written on one hand.)


texts: SIGCONT Handler for terminal application

texts:
I'm writing a C++ application for POSIX environment with terminal-based User Interface. I'd like to make my application's UI be consistent between Ctrl-Z and fg(i.e: SIGSTOP and SIGCONT).

Here is a minimal example (without using longjmp. this code uses C and POSIX headers only, but entire application will be C++):

#include <cstdio>
#include <cstdlib>
#include <csignal>
#include <unistd.h>

void PrintMessage() {
    printf("Press q to quit");
}

sig_atomic_t signalCheck;

void SigCONTHandler(int sig) {
    if(sig != SIGCONT) {
        return;
    }
    printf("From Signal Handler\n");
    fflush(stdout);

    if(signalCheck != 0) {
        PrintMessage();
    }
}

int main() {
    setbuf(stdout, NULL);
    signal(SIGCONT, SigCONTHandler);

    int ch = 0;
    while(true) {
        PrintMessage();
        signalCheck = 1;
        ch = getchar();
        signalCheck = 0;
        if(ch == 'q') {
            break;
        }
        if(ch == EOF) {
            printf("I asked you to process q.\n");
            return EXIT_FAILURE;
        }
    }
    return EXIT_SUCCESS;
}

Usage(Ubuntu 16.04, g++ 5.4, TERM=linux):

$ ./app
Press q to quit
Press q to quit
Press q to quit
Press q to quit
Press q to quit^Z
[2]+  Stopped                 ./app
$ fg
./app
From Signal Handler
Press q to quit
Press q to quitq

This code works as intended, but I feel this code is Bad. signalCheck variable keep own state to check whether the application need to print PrintMessage() or not. However, if a application become complex, I don't think I can print whole thing to stdout in SigContHandler. Moreover, it won't work without setbuf(stdout, NULL), so I'm trying to make it with longjmp to restore state.

#include <cstdio>
#include <cstdlib>
#include <csignal>
#include <csetjmp>
#include <unistd.h>

sigjmp_buf jumpBuffer;

void PrintMessage() {
    printf("Press q to quit");
}

void SigCONTHandler(int sig) {
    if(sig != SIGCONT) {
        return;
    }
    printf("From Signal Handler\n");
    siglongjmp(jumpBuffer, 1);
}

int main() {
    // setbuf(stdout, NULL);
    signal(SIGCONT, SigCONTHandler);

    int ch = 0;
    while(true) {
        if(sigsetjmp(jumpBuffer, 1) == 0) {
            PrintMessage();
            ch = getchar();
            if(ch == 'q') {
                break;
            }
            if(ch == EOF) {
                printf("I asked you to process q.\n");
                return EXIT_FAILURE;
            }
        }
    }
    return EXIT_SUCCESS;
}

This code works, and I don't need to turn off stdout buffer, but this code also looks bad.

If I need to choose one of them, what I need to choose it? Is it portable from latest Linux to old Unix box?


texts: Helper class to send emails with attachments on Android

texts:
I use this EmailTools helper class inside an Android app to send data as an email attachment, by calling send(context, deviceName, recordedContent), where the parameters are:

context: an instance of Context, in order to:

create Intent.ACTION_SEND for launching an existing email app to send emails
get elements from string.xml to format the subject
get the app's version to include in the message body

deviceName: a String, the name of the device where the data is coming from.
recordedContent: a String, the recorded data, to send as attachment.

Is there a better way? How would you improve this?

public abstract class EmailTools {

    private static final String TAG = EmailTools.class.getSimpleName();

    private static final String MESSAGE_TYPE = "message/rfc822";

    public static void send(Context context, String deviceName, String recordedContent) {
        String subject = String.format(context.getString(R.string.fmt_subject_recorded_data), deviceName);
        String message = String.format(context.getString(R.string.fmt_recorded_from), deviceName);
        message += getPackageInfo(context);

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType(MESSAGE_TYPE);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.putExtra(Intent.EXTRA_TEXT, message);
        addAttachmentToIntent(context, deviceName, recordedContent, intent);
        launchEmailApp(context, intent);
    }

    private static String getPackageInfo(Context context) {
        String packageName = context.getPackageName();
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info;
            if (manager != null) {
                info = manager.getPackageInfo(packageName, 0);
                if (info != null) {
                    return String.format("\n\n--\n[App: %s Version: %d/%s]",
                            packageName, info.versionCode, info.versionName);
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Could not get package info", e);
        }
        return "";
    }

    private static void addAttachmentToIntent(Context context, String deviceName, String recordedContent, Intent intent) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("_yyyyMMdd_HHmm");
        String filename = deviceName + dateFormat.format(new Date()) + ".dat";
        try {
            FileOutputStream ostream = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
            ostream.write(recordedContent.getBytes());
            ostream.close();
            File attachment = context.getFileStreamPath(filename);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(attachment));
        } catch (IOException e) {
            Log.e(TAG, "could not create temp file for attachment :(", e);
        }
    }

    private static void launchEmailApp(Context context, Intent intent) {
        try {
            context.startActivity(Intent.createChooser(intent, context.getString(R.string.email_client_chooser)));
        } catch (ActivityNotFoundException ex) {
            Toast.makeText(context, context.getString(R.string.no_email_client), Toast.LENGTH_SHORT).show();
        }
    }
}


texts: Recursive Django filter to output a list from user hierarchy

texts:
I need to create an HTML unordered list (to display with jstree) to display the hierarchy of users, along with a list underneath the user's "subusers" of their comments. Each user could have many users underneath him, and each of those users could have the same, so I used a recursive filter to accomplish this. However, this has lead to code that feels very repetitive, besides small differences, and it seems to me that surely something could be reduced. I have already identified some repeated code (extracted to _output_comments below), but I would hope I could do more somehow.

Note before the code: User has a foreign key to itself, with subusers as the related_name, and Comment has a foreign key to User.

from django import template

register = template.Library()

@register.filter
def unordered_user_list(user):
    """
    Takes a user and returns an HTML unordered list (without surrounding
 tags) of
    users and comments under it.
    """
    html = ""
    if len(user.subusers.all()) > 0:
        html += "
" + user.name
        if len(user.comment_set.all()) > 0:
            html += "
"
            for subuser in user.subusers.all():
                html += unordered_user_list(subuser)
            html += "
Comments
"
            html += _output_comments(user.comment_set.all())
        else:
            for subuser in user.subusers.all():
                html += "
" + unordered_user_list(subuser) + "
"
        html += "
"
    elif len(user.comment_set.all()) > 0:
        html += "
" + user.name + "

Comments
"
        html += _output_comments(user.comment_set.all())
    else:
        html += "
" + user.name + "
"
    return html

def _output_comments(comment_list):
    output = ""
    for comment in comment_list:
        output += "
" + comment.name + "
"
    output += "

"
    return output

Finally, I would appreciate any other pointers, since this is my first filter. It seems straightforward enough, but for all I know this could be a completely inappropriate use of a filter.


texts:
I have a jQuery script that checks for the strength of a password. The code looks like this (with more more of those "blocks"):

if(passwordLC && lessThan12Password)
{
    $('.passwordStrenght').animate({width:'75px',height:'5px'},200).show();
    $('.passwordStrenght').css('background-color',red);
    $('#password').css('border-color',green);
    $('.passwordStrenghtInfo').text(weak).show();
    passwordErrors = true;
}else

if(passwordUC && lessThan12Password)
{
    $('.passwordStrenght').animate({width:'75px',height:'5px'},200).show();
    $('.passwordStrenght').css('background-color',red);
    $('#password').css('border-color',green);
    $('.passwordStrenghtInfo').text(weak).show();
    passwordErrors = true;
}else

if(passwordN && lessThan12Password)
{
    $('.passwordStrenght').animate({width:'75px',height:'5px'},200).show();
    $('.passwordStrenght').css('background-color',red);
    $('#password').css('border-color',green);
    $('.passwordStrenghtInfo').text(weak).show();
    passwordErrors = true;
}else

And it goes on and on...

Is there a way to reduce all that code to something simpler and efficient, or am I stuck with those horrible "blocks" of repeated code?


texts: Chaining Internal Class Methods in Python

texts:
I'm learning object-oriented programming in Python. I've created a class RepositoryMaker that contains all methods required to create a Git repository. The idea is to be able to create a single instance of this class with a constructor that only requires pertinent info to create a new repo.

My code looks like this:

class RepositoryMaker:
    """Creates new Azure DevOps repositories"""
    def __init__(self, project_name, repo_name):
        self.project_name = project_name
        self.repo_name = repo_name
        with open("./repo_request_body.json", "r") as file:
            self.data = json.load(file)

    def get_project_id(self):
        """Returns the Azure DevOps project ID for a project name"""
        _request_object = make_request(
            "_apis/projects/",
            self.project_name,
            "?api-version=5.1-preview.1",
            request_method = "get"
            )
        return _request_object.get("id")

    def update_project_id(self):
        """Updates JSON dictionary with new ID"""
        new_id = self.get_project_id()
        self.data["project"]["id"] = new_id

    def update_repo_name(self):
        """Updates JSON dictionary with new repo name"""
        self.data["name"] = self.repo_name
        return self.data

    json_content_type = {
        'Content-Type': 'application/json',
        'Authorization': 'Basic XXXXXXXXXXXXXXXX'
        }

    def create_repository(self):
        """Creates a new repo under the specified project"""
        self.update_project_id()
        repo_request_body = self.update_repo_name()
        make_request(
            self.project_name,
            "/_apis/git/repositories",
            "?api-version=5.1-preview.1",
            request_method = "post",
            data = json.dumps(repo_request_body),
            headers = self.json_content_type
        )

x = RepositoryMaker(project_name, repo_name)
x.create_repository()

My concern is chaining together class methods internally within the class. For example, create_repository() is calling update_project_id() which is calling get_project_ID().

Is this convention acceptable within Python? Is there a better way to group together a set of related functions than using a class?


texts: Showing values from different fields in an array with ternary

texts:
This small piece of code shows the value of different fields of an array.
I'm looking for a way to improve this nested ternary function. An if statement solution would be obvious, so I'm wondering if there is something more elegant to solve it.
<button type="button" onclick="myFunction()">Check</button>

Output
Abba: 1 Mars: 4 Nexus: 6


texts: Accurate && precise location data within a timeframe (session)?

texts:
Scenario
A session would start & end within a time frame. Within this time frame,  the device would be moving within a constraint environment. The movement would be extremely slow (slow-walking to stillness).
This session could (& would) be entered & exited several times, although doing just a single session might be sufficient for the user.
Objective
Once this session is complete, it is the intention to have a location that would help any other user to get to that location.  So during the session, a single location data would be recorded.  The objective is to have the most accurate & precise single location data.
Device: any iOS device
Required parameters

Latitude
Longitude
Horizontal Accuracy
Altitude
Vertical Accuracy

I have a class called as LocationData.cs, where data is being populated whenever there is an update.
// LocationData.cs
internal static class LocationData
{
    internal static double Altitude = DummyValue;
    internal static double VerticalAccuracy = DummyValue;
    internal static double HorizontalAccuracy = DummyValue;
    internal static ISN_CLLocationCoordinate2D Coordinate = new ISN_CLLocationCoordinate2D(0,0);
}

Now using the data available, how to figure the best accurate & precise location?
Here is my approach. The following method runs through the entire session.
private IEnumerator examineForAccurateAndPreciseLocationData()
{
    do
    {    // Starts when session starts
        assignHorizontalLocationValuesAppropriately();
        assignVerticalLocationValuesAppropriately();

        // This do-while loop runs every 1 second
        yield return new WaitForSeconds(1f);
    } while (CreateSessionBuffer.ISrunning == true);
    // ends when session is complete
}

private void assignHorizontalLocationValuesAppropriately()
{
    if (LocationData.HorizontalAccuracy < 0)
    { return; }// Just in case if there is an absence of reliable data

    // If accuracy is less than a positive number, it assigns an immediate value
    if (XPHeader.Location.HorizontalAccuracy < System.Double.Epsilon)
    {
        XPHeader.Location.HorizontalAccuracy = LocationData.HorizontalAccuracy;
        XPHeader.Location.Coordinate.Latitude = LocationData.Coordinate.Latitude;
        XPHeader.Location.Coordinate.Longitude = LocationData.Coordinate.Longitude;
    }
    else if (XPHeader.Location.HorizontalAccuracy > LocationData.HorizontalAccuracy)
    { // if there is a better accuracy, then it assigns the value that is available
        XPHeader.Location.HorizontalAccuracy = LocationData.HorizontalAccuracy;
        XPHeader.Location.Coordinate.Latitude = LocationData.Coordinate.Latitude;
        XPHeader.Location.Coordinate.Longitude = LocationData.Coordinate.Longitude;
    }
}

private void assignVerticalLocationValuesAppropriately()
{
    if (LocationData.VerticalAccuracy < 0)
    { return; }

    if (XPHeader.Location.VerticalAccuracy < System.Double.Epsilon)
    {
        XPHeader.Location.VerticalAccuracy = LocationData.VerticalAccuracy;
        XPHeader.Location.Altitude = LocationData.Altitude;
    }
    else if (XPHeader.Location.VerticalAccuracy > LocationData.VerticalAccuracy)
    {
        XPHeader.Location.VerticalAccuracy = LocationData.VerticalAccuracy;
        XPHeader.Location.Altitude = Geo.LocationData.Altitude;
    }
}

Thank you for your time.


texts: Makefile that is a wrapper for a package.json & docker-compose files

texts:
I've got the following Makefile..

.PHONY: install install-prod clean

MODULE := ./node_modules/.bin
COMPOSE := docker-compose -f docker-compose.yml

install:
    @echo "--- Installing dependencies!"
    npm install

install-prod:
    @echo "--- Installing production dependencies!"
    npm install --only=production

build:
    @echo "--- Babelify-ing code!"
    npm run build

run:
    @echo "--- Building Docker and running app!"
    ${COMPOSE} up --build -d app

test:
    @echo "--- Running tests"
    npm run test

coverall:
    @echo "--- Running tests & reporting to Coverall!"
    npm run coverall

clear:
    @echo "--- Clearing everything!"
    ${COMPOSE} down

It's a simple one, but in essence, it wraps commands in a package.json and a docker-compose.yml for an express app so it makes calls in a CI Pipeline easier to understand and maintain.

Would love some feedback about whether it can be optimized, cleaner, or potentially smaller. Anything really :)


texts:
For a website I'm working on, I had to get all the unique entries in an array and count their occurrence. It is possible a certain entry is only found once, but it can also be found 20 times. So I designed the following bit of code:

for ($i = 0; $i < count($nodes); $i++)
{
    for ($j = 0; $j < count($nodes[$i]); $j++)
    {
        if (!array_key_exists($nodes[$i][$j], $uniekenodes))
        {
            $uniekenodes[$nodes[$i][$j]] = 1;
        }
        else
        {
            $uniekenodes[$nodes[$i][$j]] += 1;
        }
    }
}

The $nodes array contains the the entries returned from the database. And the $uniekenodes array contains the unique entries and how many times they occured in the $nodes array.

This is my first php script (on a drupal webpage by the way) and as such I don't know that much about php. I'm pretty confident there is probably a more a efficient way to do this, using php-specific functions. Any and all tips are welcome!

EDIT: I might have to clarify the structure of the arrays:

$nodes has two dimensions. The first dimension is just a key for the second dimension. This one contains an array of drupal nodes for each key.

$uniekenodes uses the nodes from $nodes as a key and the value is how many times the node occured in $nodes

EDIT 2:

I printed the arrays, as requested by Boris Guéry:

Array
(
[0] => Array //Each of these contains node id's returned by a query
    (
        [0] => 12
        [1] => 11
        [2] => 10
        [3] => 9
        [4] => 8
        [5] => 7
    )

[1] => Array
    (
        [0] => 10
        [1] => 9
        [2] => 8
        [3] => 7
    )

[2] => Array
    (
    )

[3] => Array
    (
        [0] => 11
        [1] => 10
        [2] => 9
        [3] => 8
        [4] => 7
       )
)

    Array //This one uses the node ids from the previous array as keys, the values are the number of occurences.
    (
        [12] => 1
        [11] => 2
        [10] => 3
        [9] => 3
        [8] => 3
        [7] => 3
    )


texts: Initialize an object with a key at runtime

texts:
Often I want to construct an object with a runtime-generated key.

Here's how I have been doing it:

function make_obj(key, func, val){
  let foo={};
  foo[key] = func(val);
  return foo;
}

Usage:

make_obj('food', x=>`I like ${x}`, 'soup'); // {food: 'I like soup'}

Is there a shorter way to do this?


texts:
I created the following program which takes a molecular formula as an input, eg CH3COOH and returns the molar mass of the compound:
#! /usr/bin/env python3
element_weights = {
    'H': 1.00794,
    'He': 4.002602,
    'C': 12.011,
    'O': 15.999,
    'Ts': 294.0,
    'Og': 294.0,
}

def tokenize(string):
    position = 0
    tokens = []
    striter = iter(string)

    character = next(striter)

    while True:
        try:
            token = character

            if character in "()":
                character = next(striter)
            elif character.isnumeric():
                while (character := next(striter)).isnumeric():
                    token += character

            elif character.isupper():
                while (character := next(striter)).islower():
                    token += character
            else:
                raise ValueError("Can't parse")

            tokens.append(token)

        except StopIteration:
            tokens.append(token)
            tokens.append("EOF")
            return tokens

def get_composition(tokens_list):
    composition = {}

    tokens = iter(tokens_list)
    token = next(tokens)

    while True:
        if(token == "EOF"):
            break

        num_parens = 0

        if token == "(":
            num_parens = 1
            substr_tokens = []

            while num_parens > 0:
                token = next(tokens)

                if token == "EOF":
                    raise ValueError(f"Unbalanced Parens, tokens: {tokens_list}")
                elif token == "(":
                    num_parens += 1
                elif token == ")":
                    num_parens -= 1

                if (num_parens > 0):
                    substr_tokens.append(token)

            substr_tokens.append("EOF")

            substr_composition = get_composition(substr_tokens)

            if (token := next(tokens)).isnumeric():
                substr_composition = {k: int(token) * v for k,v in substr_composition.items()}

            for k,v in substr_composition.items():
                if k in composition:
                    composition[k] += v
                else:
                    composition[k] = v
            break

        if token == ")":
            raise ValueError(f"Unbalanced Parens, tokens: {tokens_list}")

        if token not in element_weights:
            raise ValueError(f"Can't find element {token}, tokens {tokens_list}")

        element = token

        if (token := next(tokens)).isnumeric():
            element_count = int(token)
            token = next(tokens)
        else:
            element_count = 1

        if element in composition:
            composition[element] += element_count
        else:
            composition[element] = element_count

    return composition

def convertToAMU(element_count):
    return sum(element_weights[k] * v for k,v in element_count.items())

if __name__ == "__main__":
    import sys

    if(len(sys.argv) > 1):
        print(convertToAMU(get_composition(tokenize(sys.argv[1]))))
    else:
        print(f"Usage: {sys.argv[0]} [chemical_formula]")


texts: Sorting alphabetically ascending and descending using .sort()

texts:
I have created this basic use case of .sort() for my own reference. I am asking for a review to see if there are bad practices present or areas that could be optimised.

Is my use of modifying the array correct? Do I need to place the newly sorted list into a new array?
Using .map() I found it was parsing it as a string. Is insertAdjacentHTML() the right method to use here?

const listArea = document.getElementById('listArea');
const btnAsc = document.getElementById('asc');
const btnDes = document.getElementById('des');

// The Original Array
let architects = [
  "Lloyd Wright",
  "Hadid",
  "Mies van der Rohe",
  "Le Corbusier",
  "Foster",
  "Gaudi",
  "Piano",
  "Gropius",
  "Niemeyer",
  "Aalto",
  "Saarinen",
]

// Empty Array to Store Sorted Array
let sortedList = [];

// Click Events for the sort buttons
btnAsc.addEventListener('click', () => sortAsc(architects));
btnDes.addEventListener('click', () => sortDes(architects));

// Sort the array in ascending order
function sortAsc(arr) {
  // Clear the sortedList array
  sortedList.length = 0;

  // Convert each item in the architects array to lower case
  for(const element of arr) {
    // Push these lowercase elements into the sortedList array
    sortedList.push(element.toLowerCase());
  }
  sortedList.sort();
  populateList(sortedList);
}

function sortDes(arr) {
  sortedList.length = 0;
  for(const element of arr) {
    sortedList.push(element.toLowerCase());
  }
  sortedList.sort().reverse();
  populateList(sortedList);
}

function populateList(arr) {
  // Empty out the listArea of all content
  while(listArea.firstChild) {
    listArea.removeChild(listArea.lastChild);
  }
  // Map each item in the supplied array to an li, and remove comma at end of each
  let listArchitects = arr.map(item => `<li>${item}</li>`).join('');
  listArea.insertAdjacentHTML('beforeend', listArchitects);
}

window.addEventListener('onload', populateList(architects));
#listArea {
  text-transform: capitalize;
}

    <button id="asc">Sort Ascending</button>
    <button id="des">Sort Descending</button>


texts: Fastest way to "Replace" "auto fill" and then loop in Excel VBA

texts:
I am wondering if there's any way to improve the performance of this simple "replace" / "autofill" loops that I created in excel?

Sub Macro1()

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayStatusBar = False

For i = 1 To 50
Do

Sheets("Sheet1").Select

'Range("Q1:Q6").Value are random generated number using randbetween (=RANDBETWEEN(3,103))
'save the random created value to Range("U1:U6")
Sheet1.Range("U1:U6").Value = Sheet1.Range("Q1:Q6").Value

Range("AA1").Select

    'Column u1 to u6 are random values generated using =RANDBETWEEN(3,103).
'example of  Range("aa1") Pre-entered formula: =a5+b95+c48+d29+e62+f29
'replace the "a5" in range("aa1") with "a?", with the "?" being the random number in U1.
Selection.Replace What:="a" & Range("t1") & "+", Replacement:="a" & Range("u1") & "+", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

    'replace the "B95" in range("aa1") with "a?", with the "?" being the random number in U2.
Selection.Replace What:="b" & Range("t2") & "+", Replacement:="b" & Range("u2") & "+", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

    'replace the "C48" in range("aa1") with "a?", with the "?" being the random number in U3.
Selection.Replace What:="c" & Range("t3") & "+", Replacement:="c" & Range("u3") & "+", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

    'replace the "D29" in range("aa1") with "a?", with the "?" being the random number in U4.
Selection.Replace What:="d" & Range("t4") & "+", Replacement:="d" & Range("u4") & "+", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

    'replace the "E62" in range("aa1") with "a?", with the "?" being the random number in U5.

Selection.Replace What:="e" & Range("t5") & "+", Replacement:="e" & Range("u5") & "+", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

    'replace the "F29" in range("aa1") with "a?", with the "?" being the random number in U6.
Selection.Replace What:="f" & Range("t6") & ",", Replacement:="f" & Range("u6") & ",", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

'Autofill the modified formula in aa1 to aa1301.
Range("AA1").AutoFill Destination:=Range("AA1:AA1301")
'Manual re-calulate the autofills.
'Manual re-generate the random number

Calculate

    "Copy the number from U1:U6 (the =randbetween(3,103) to T1:T6 to save the random generated number.
'
Sheet1.Range("T1:T6").Value = Sheet1.Range("U1:U6").Value

                         Loop Until Range("ac3") = 1 And Range("h8") >= 8 And Range("o3") = 0 And Range("o4") <> 0

Next i

 Application.Calculation = xlCalculationAutomatic
 Application.ScreenUpdating = True
 Application.EnableEvents = True
 Application.DisplayStatusBar = True

Beep

End Sub

Any better way to speed up the "replace" and the "autofill" or the whole macro even? It's pretty simple, just now fast enough!

Thanks


texts:
In Groovy 1.8.6 I need to move a line just before another one. I'm interested in any improvements.

fileToChange = new File('.classpath')
linesToKeep = []
fileToChange.eachLine {
    if (it.contains('line to move')) {
        lineToMove = it
    } else {
        linesToKeep.add(it)
    }
}
fileToChange.withWriter { out ->
    linesToKeep.each {
        if (it.contains('line to recognize')) {
            out.writeLine(lineToMove)
        }
        out.writeLine(it)
    }
}


texts:
var timeToWait = TimeSpan.FromSeconds(20);
var interval = TimeSpan.FromMinutes(5);
var t = new Timer(s =>
    {
        tracker.ProcessAuditLogs();
    }, null, timeToWait, interval);

I'm looking to run a timer or an indefinite period of time, as long as my program/service is running. Will the above work in a production environment?


texts: Recursively replace string placeholders with parameterized phrases

texts:
I've written a python script to replace certain placeholders in a text with defined phrases. Some of the phrases might contain placeholders themselves, so the script needs to recursively replace them. Additionally the placeholders might allow parameters that need to be inserted at certain positions.

The current approach feels a little slow, because I'm iterating over the text much. It also fails (and crashes) if not enough parameters are provided for a parameterizable placeholder.

import re

parameters_regex = "(?:\[(.*)\])?"

def expand_message(message):
  """Recursivly replaces any occurencys of building blocks with its text."""
  for key, value in phrases.items():
    match = re.search(key + parameters_regex, message)
    if match:
      replacement = ""
      if (match.group(1)):
        parameters = match.group(1).split(",")
        replacement = value.format(*parameters)
      else:
        replacement = value
      replacement = expand_message(replacement)
      message = message.replace(match.group(0), replacement)
  return message

def format_numerators(message):
  """Replaces the numerator placeholders with the actual numerator."""
  numerator = 1
  while ('#.)' in message):
    message = message.replace('#.)', str(numerator) + ".)", 1)
    numerator+=1
  return message

def format_message(message):
  """Formats and returns the message."""
  message = expand_message(message)
  message = format_numerators(message)
  return message

This is how I'm testing it at the moment:

phrases = { }
phrases["bb:WORKDAY"] = "bb:GET_UP\nbb:BRUSH_TEETH\nbb:GO_TO_WORK[train]\nbb:GO_HOME"
phrases["bb:FRIDAY"] = "bb:WORKDAY\nbb:GO_OUT[cinema,John]\nbb:GO_HOME"
phrases["bb:WEEKEND"] = "bb:GET_UP\nbb:GO_OUT[park,Mary]\nbb:GO_HOME"

phrases["bb:GET_UP"] = "#.) Get out of bed."
phrases["bb:BRUSH_TEETH"] = "#.) Brush your teeth."
phrases["bb:GO_TO_WORK"] = "#.) Take the {} and go to work."
phrases["bb:GO_HOME"] = "#.) Go home."
phrases["bb:GET_UP"] = "#.) Get out of bed."
phrases["bb:GO_OUT"] = "#.) Go to the {} with {}."
phrases["bb:GET_UP"] = "#.) Get out of bed."

print(format_message("bb:WORKDAY"))
print("\n")
print(format_message("bb:FRIDAY"))
print("\n")
print(format_message("bb:WEEKEND"))

  1.) Get out of bed.
  2.) Brush your teeth.
  3.) Take the train and go to work.
  4.) Go home.

  1.) Get out of bed.
  2.) Brush your teeth.
  3.) Take the train and go to work.
  4.) Go home.
  5.) Go to the cinema with John.
  6.) Go home.

  1.) Get out of bed.
  2.) Go to the park with Mary.
  3.) Go home.


texts:
I'm supposed to make a program that will tell me the number of the day of a certain date. So I input the date, and it will tell me which number day it is. (i.e: 1.1.2014 would be day 1, and 30.4.2012 would be 121) The program in its current state works, but it looks a little sloppy (or I'm just too self-conscious). I'm somewhat new to programming and was wondering if I can improve it, or if I can make it less sloppy.

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

valid(int day, int month, int year)
{
    int st[12]={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int copy[12]={31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if(year % 4 != 0)
        {
        if(day < 1 ||  day > st[month-1] || month < 1 || month > 12 || year < 0)
            return 0;
        else
        return 1;
    }
    else
        if(day < 1 ||  day > copy[month-1] || month < 1 || month > 12 || year < 0)
            return 0;
        else
            return 1;

}

int main()
{
    int day, month, year, sum;
    scanf("%d", &day);
    scanf("%d", &month);
    scanf("%d", &year);
    printf("Date is %d.%d.%d", day, month, year);
    sum = day;
    int st[12]={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int copy[12]={31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if(valid(day, month, year) == 1)
        {
        if(year % 4 == 0)
            for(int i = 0; i < month; i++)
                sum = sum + copy[i-1];
        else
            for(int i = 0; i < month; i++)
                sum = sum + st[i-1];
        printf("\nDay number is %d", sum);
        }
    else
        printf("\nInvalid date");

}

The function valid checks whether my date is valid, so that I cannot input a wrong date. I also check for leap years inside my main program. I have an array which has the number of days in every month, and another one for leap years.


texts:
I'd like some opinions about my approach at using SQLite databases in android. Everything seems to work very well, but there may be something wrong that I hadn't noticed.

I don't like working with create/alter table statements in code, so I prefer creating my database with some SQLite client out there and putting it in assets folder.  I use some logic to decide when the database must be replaced and which records need to be kept, then use this code in a class called DbManager:

private static SQLiteDatabase _db = null;

public static Object lock = new Object();

private static SQLiteDatabase getDB() {
    if (_db == null) {
        _db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
    }

    return _db;
}

//this is the approach used for insert operations, but is the same for update, delete etc
public static boolean insert(String tableName, ContentValues values) {
    try {
        return getDB().insert(tableName, null, values) >= 0;
    } catch (Exception e) {
        LogHelper.WriteLogError("error in DB_manager.insert function", e);
        return false;
    }
}

public static synchronized void beginTransaction(String who) {
    LogHelper.WriteLogDebug("starting transaction by " + (who == null ? "null" : who));
    try {
        //in this way if a transaction is still executing it waits untill the previus ends.
        //obviously every time i call DbManager.beginTransaction the call at DbManager.endTransaction is in the finally statment
            if (_db.inTransaction()) {
                LogHelper.WriteLogInfo("DB IS IN TRANSACTION");
                synchronized (lock) {
                    lock.wait();
                }
            }
            getDB().beginTransactionWithListener(new SQLiteTransactionListener() {
                @Override
                public void onRollback() {
                    synchronized (lock) {
                         LogHelper.WriteLogInfo("onRollback listener invoked");
                         lock.notifyAll();
                    }
                }

                @Override
                public void onCommit() {
                    synchronized (lock) {
                        LogHelper.WriteLogInfo("onCommit listener invoked");
                        lock.notifyAll();
                    }
                }

                @Override
                    public void onBegin() {
                        // TODO Auto-generated method stub
                    }
                });
            } catch (Exception e) {
                LogHelper.WriteLogError("error calling begin transaction by " + (who == null ? "null" : who), e);
            }
        }

        public static void endTransaction(boolean commitChanges, String who) {
            LogHelper.WriteLogDebug("ending transaction by " + (who == null ? "null" : who));
            try {
                if (commitChanges)
                    getDB().setTransactionSuccessful();
                getDB().endTransaction();
            } catch (Exception e) {
                LogHelper.WriteLogError("error calling end transaction by " + (who == null ? "null" : who), e);
            }
        }


texts:
I have some code here that I am very unhappy with. The task I am trying to accomplish is this.

Given a 2d vec like this:

[[0 2 0] [1 3 5] [3 3 0]]

which can contain positive ints including zero I want to remove all lines that are greater zero.

Where the definition of line is the following:

  A line is represented by the position n in every vec inside the 2d
  vec.

So my example above has three lines:

[0 1 3], [2 3 3] and [0 5 0].

The line that I want to remove from it according to my algortihm is [2 3 3] because every element is greater than zero.

So my 2d vec would now look like this:

[[0 0] [1 5] [3 0]]

And finally I want to pad the vecs to their original size filling them with zero for every removed line, so that it looks finally like this:

[[0 0 0] [0 1 5] [0 3 0]]

This is what I came up with:

(defn in?
  "true if seq contains elm"
  [seq elm]
  (some #(= elm %) seq))

(defn not-in?
  "true if seq does not contain elm"
  [seq elm]
  (not (in? seq elm)))

(defn all-greater-zero-at
  "Given a 2-d vec [[0 1] [0 2]] return true if all elements at 'at' are
  greater than zero"
  [v at]
  (not-in? (map #(if (> (nth % at) 0) true false) v) false))

(defn to-be-removed
  "Returns a seq of positions to be removed (0 3 4)"
  [v width]
  (reduce (fn [a b] (if (all-greater-zero-at v b) (conj a b) a)) [] (range width)))

(defn remove-at
  "Removes an element from a 1d vec"
  [v at]
  (into [] (concat (subvec v 0 at) (subvec v (+ at 1) (count v)))))

(defn insert-at
  "inserts an element into a 1d vec"
  [v elm at]
  (into [] (concat (subvec v 0 at) elm (subvec v at (count v)))))

(defn remove-and-replace-all-at
  [v at]
  (map #(insert-at (remove-at % at) [0] at) v))

(defn replace-full-by-zero [v width]
  (reduce (fn [a b] (remove-and-replace-all-at a b)) v (to-be-removed v width)))

(defn remove-zeros [v at]
  (reduce (fn [a b] (conj a (remove-at b at))) [] v))

(defn fill-with-zeros
  "Takes a 2d vec and pads ith with zeros up to width"
  [v width]
  (map #(into [] (concat (take (- width (count (first v))) (repeat 0)) %)) v))

(defn clean-grid
  "removes all full lines"
  [fbz tbr]
  (loop [acc fbz tbr tbr i 0]
    (if (empty? tbr)
      acc
      (recur (remove-zeros acc (- (first tbr) i)) (rest tbr) (inc i)))))

(defn remove-full-lines [v width]
  (let [fbz (replace-full-by-zero v width)
        tbr (to-be-removed v width)
        cleaned-grid (clean-grid fbz tbr)]
    (into [] (fill-with-zeros cleaned-grid width))))

This seems like a lot of code for such a "simple" algorithm and I assume there are a lot of better ways to do that, but just did not come up with a better one, so, please, go ahead and fix it, if you want to.


texts:
In this exercise I have to do this:

  Modify the program so that no matter what number the user thinks of (1-100) the computer can guess it in 7 or less guesses.

I'm just a beginner in Java and I'd like to know what you think about my code:

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    Random rand = new Random();
    int randNum = 0;
    int upperLimit = 100;
    int lowerLimit = 1;
    String myAnswer = "";

    do {
        randNum = rand.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;
        System.out.println("I think it's " + randNum);
        myAnswer = in.nextLine();

        if(myAnswer.equals("tl")) {  //too low
            lowerLimit = randNum + 1;
        }
        else if(myAnswer.equals("th")) { // too high
            upperLimit = randNum - 1;
        }
    }while(!myAnswer.equals("y"));

    in.close();
    System.out.println("YAAAY! :D");
}

I think it's too slow, because sometimes it takes the computer more than 7 times to guess a number.


texts: Compare two sheets and copy new and delete duplicates in excel

texts:
I have two sheets  named source and solution and I have to perform following activities.

Copy new records from source to solution.
Update records if rows present in source and have updated data.
Delete rows from solutions if rows not present in source file.

I have written following vba code.

Sub processDuplicate()
    Application.ScreenUpdating = False
    'Declare variables
    Dim Sample As String, test As String
    Dim var As Variant, iRow As Long, iRowL As Long, RowsRange As String
    Dim Row As Long, FoundDup As Range, SalesSampleOrderClmn As Variant
    test = "test"
    Sample = "Sample"

    Dim CountTempNoDup As Integer
    Dim CountTempDup As Integer

    SalesSampleOrderClmn = Application.Match("Sales", Sheets(Sample).Rows(1), 0)
    Debug.Print SalesSampleOrderClmn

       'Set up the count as the number of filled rows in the first column of Sheet1.
       iRowL = Worksheets(Sample).Cells(Rows.count, SalesSampleOrderClmn).End(xlUp).Row
        Debug.Print iRowL
       'Cycle through all the cells in that column:
       For iRow = 2 To iRowL
       'Call subRemoveNotRequiredRows(TempData, SaleSamples)
       '(CompareFrom As String, DeleteFrom As String)
          Set FoundDup = Worksheets(test).Range("D:D").Find(Cells(iRow, SalesSampleOrderClmn), LookIn:=xlValues, lookat:=xlWhole)

        If FoundDup Is Nothing Then
            CountTempNoDup = CountTempNoDup + 1
            Worksheets(Sample).Cells(Row, ColumnNumber).EntireRow.Delete
        Else:
           CountTempDup = CountTempDup + 1
           RowsRange = "A" & iRow & ":M" & iRow
             Worksheets(test).Range(RowsRange).Copy Worksheets(Sample).Range(RowsRange)
             Worksheets(test).Cells(iRow, SalesSampleOrderClmn).EntireRow.Delete
        End If
       Next iRow
       Debug.Print CountTempNoDup; "No Dup"
       Debug.Print CountTempDup; "Dup"
    'Application.ScreenUpdating = True
    Worksheets(test).Rows(1).EntireRow.Delete
    Worksheets(test).UsedRange.Copy
 'Sheets(Test).Copy After:=Worksheets(Sample).Cells(Rows.count, 1).End(xlUp)
    Worksheets(Sample).Cells(Rows.count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
    Worksheets(test).Delete
End Sub

I'm facing performance issues in excel and I need help to increase performance and its correctness.

I have one problem with deleting entire row. It's not deleting entire row on till column L.

Worksheets(Sample).Cells(Row, ColumnNumber).EntireRow.Delete


texts:
I want to print a nice loading message with these three fading dots, while the main thread does some heavy IO stuff. This is why I implemented this:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdbool.h>

static bool            loadingStop;
static pthread_mutex_t loadingMutex;

void *loadingDots(void *message);

int main() {
  loadingStop = false;

  // MUTEX
  pthread_mutex_init(&loadingMutex, NULL);

  // ATTRIBUTE
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  // THREAD
  pthread_t loadingThread;
  pthread_create(&loadingThread, &attr, loadingDots, (void *)"Loading (main, does something long)");

  pthread_attr_destroy(&attr);

  // SOMETHING TIME CONSUMING
  usleep(8000000);

  // PLEASE 'LoadingDots' TO STOP
  pthread_mutex_lock(&loadingMutex);
  loadingStop = true;
  pthread_mutex_unlock(&loadingMutex);

  // WAIT FOR IT TO FINISH
  pthread_join(loadingThread, NULL);
  pthread_mutex_destroy(&loadingMutex);

  printf("This is printed after 'LoadingDots' savely quit.\n");

  return 0;
}

void *loadingDots(void *message)
{
  int c = 0;

  while (1) {
    switch (c) {
    case 0:
      printf("\r%s   \r%s", (char *)message, (char*)message);
      break;
    default:
      putchar('.');
      break;
    }

    fflush(stdout);
    usleep(1000000);

    c = (c+1) % 4;

    pthread_mutex_lock(&loadingMutex);
    if (loadingStop) { break; };
    pthread_mutex_unlock(&loadingMutex);
  }

  putchar('\n');
  pthread_exit(NULL);
}


texts:
I have put together a simple Javascript accordion, though the Javascript code I think could possibly be slimmed down. I would welcome any feedback anyone has on what I have done, and any advice to improve.

HTML

Accordion 1

Cras malesuada ultrices augue molestie risus.

Accordion 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae at placeat nesciunt nostrum accusamus debitis fuga similique quisquam, rerum temporibus, quod asperiores nulla, eveniet libero earum eaque harum inventore minima ipsum saepe omnis. Officia, est, maiores. Reprehenderit odio perspiciatis voluptates commodi ex at praesentium laborum deleniti libero, architecto sit optio repellat est molestiae beatae, magnam qui voluptatibus. Ducimus mollitia dignissimos minus sapiente quidem, animi adipisci laboriosam aliquam asperiores facere. Repellat recusandae doloribus incidunt voluptatibus quibusdam rem delectus inventore nisi, laudantium. Doloribus eum vero, consequuntur nisi enim quam non odio dignissimos praesentium nostrum magnam consequatur totam reprehenderit quaerat. Saepe, blanditiis fugit?

Accordion 3

Vivamus facilisisnibh scelerisque laoreet.

SCSS

div.accordion {
  .accordion-content {
    max-height: 0px;
    overflow: hidden;
    transition: max-height 400ms;
    &.active {
      overflow: auto;
    }
  }
}

JavaScript

document.addEventListener('DOMContentLoaded', function() {

  function toggle(){
    if (this.nextElementSibling.classList.contains('active')) {
      this.nextElementSibling.classList.remove('active');
      this.nextElementSibling.removeAttribute('style');
      this.classList.remove('active');
    }
    else {
      var elementHeight = this.nextElementSibling.scrollHeight;
      this.nextElementSibling.classList.add('active');
      this.nextElementSibling.style.maxHeight = elementHeight + 'px';
      this.classList.add('active');
    }
  }

  var accordion = document.querySelector('.js div.accordion');
  var header = accordion.getElementsByClassName('accordion-header');

  for (var i = 0; i < header.length; i++) {
    header[i].addEventListener('click', toggle);
  }

});


texts: Drag and drop GUI with native JavaScript

texts:
Currently I'm engaged with implementing a Drag and Drop GUI.
I've discovered that there a not many resources (tutorials, etc.) available. So I wrote this:

function Cursor(cssSelector, rightLimit, bottomLimit) {
    var element = document.querySelector('#square');
    var styles = window.getComputedStyle(square);
    var x = 0;
    var y = 0;
    var fromLeft = 0;
    var fromTop = 0;
    var pushed = false;
    var limits = {
        top: 0,
        right: rightLimit,
        bottom: bottomLimit,
        left: 0
    }

    // Uses the offsetX and the offsetY of the
    //  mousedown event.
    this.setCoordinates = function(left, top) {
      if (!fromLeft && !fromTop) {
        fromLeft = left;
        fromTop = top;
      }
    }

    this.togglePushed = function() {
        pushed ? pushed = false : pushed = true;
    }

    this.getPushed = function() {
        return pushed;
    }

    // Uses the offsetX and the offsetY of the
    //   mousemove event.
    this.moveCursor = function(offsetX, offsetY) {
      // How much have the x and the y coordinate
      //   changed since the mousedown event?
      var tmpX = offsetX - fromLeft;
      var tmpY = offsetY - fromTop;

      if ((x + tmpX) <= limits.right && (x + tmpX) >= limits.left &&
          (y + tmpY) >= limits.top && (y + tmpY) <= limits.bottom) {
        // If the values are valid then store them ...
        x += tmpX;
        y += tmpY;
        // ... and use them to move the element.
        element.style.left = x + 'px';
        element.style.top = y + 'px';
      }
    }
  }

  var cursor = new Cursor('#square', 550, 450);

  square.addEventListener('mousedown', function(ev) {
    cursor.togglePushed();
    cursor.setCoordinates(ev.offsetX, ev.offsetY);
  });

  document.body.addEventListener('mouseup', function(ev) {
    cursor.togglePushed();
  });

  square.addEventListener('mousemove', function(ev) {
    if (cursor.getPushed()) {
      cursor.moveCursor(ev.offsetX, ev.offsetY);
    }
  });
body {
  background-color: #eefafa;
}

#wrap {
  width: 600px;
  margin: 50px auto;
}

#panel {
  height: 500px;
  position: relative;
  background-color: rgba(150, 150, 150, 0.2);
  border-radius: 3px;
}

#square {
  width: 50px;
  height: 50px;
  background-color: orangered;
  border: 1px solid teal;
  border-radius: 3px;
  position: absolute;
  top: 0px;
  left: 0px;
}

.instruct {
  font-size: 125%;
  font-weight: bold;
  font-family: helvetica;
}

      Click the square. Keep the mouse-button pushed and
        move the pointer slowly.

There's also a demo on CodePen.


texts:
I'm self-learning C now, and I want to find out if my code is good and clean or kinda messy.
For this exercise, the program tells if the text which was inserted has the keyword "asd", without using functions from string.h. If so, it returns how many times it was found.
it's not a big program, but I want to make sure it's clean and good so I don't pick up any bad practices.

#include "stdafx.h"
#include <stdio.h>

char findInStr(char *str, char *find) {
    unsigned char howMany = 0, strCounter = 0, findCounter = 0;
    do {
        if (findCounter == 3)
            howMany++;
        if (str[strCounter] == find[findCounter])
            findCounter++;
        else
            findCounter = 0;
        strCounter++;
    } while (str[strCounter-1] != '\0');
    return howMany;
}

int main() {
    char str[60];
    char find[5] = "asd";
    char found;

    printf("enter text: ");
    gets_s(str, 60);

    found = findInStr(str, find);
    if (found)
        printf("found!!! %d\n times", found);
    else
        printf("not found\n");

    return 0;
}


texts: Hackerrank problem -"Another Prime Problem"

texts:
I came across this issue in the problem titled: Another Prime Problem. Here's my solution with JavaScript which passed test case-1, but for other test cases it led to timeout.
function processData(input) {
       input=input.split('\n');
       input.shift();
       for(var i=0;i<input.length;i++){
          values(input[i]);
       }
    }
    function values(num){
       var sum=0;
       num=num.split(' ');
       for(var i=num[0];i<=num[1];i++){
           for(var j=2;j<=i;j++){
               if(i%j==0 && isprime(j)){
                   sum+=j;
               }
           }
       }
       console.log(sum)
    }
    function isprime(val){
       let flag=1;
       for(var i=2;i<val;i++){
            if(val%i==0){
               flag=0;
            }
       }
       if(flag==1){
          return true;
       }
       else{
           return false;
       }
    }

What's the issue in this code that leads to timeout?
The above program has a very bad time complexity, I guess due to multiple loops and functions, but not being much experienced with algorithms this is only solution I can think of right now. Any help would be appreciated.
Additional info:
Problem statement in a nutshell: find the sum of prime factors of each number in the range [X,Y].
Input Format:
The first line contains T denoting the total number of testcases.
First line of each testcase contains two integers X and Y.
Constraints:
1 ≤ T ≤ 10000
2 ≤ X ≤ Y ≤ 10^5
Output Format:
Sum of prime factors of each number in the range [X, Y].
Currently my code calculates the sum of primes (i know this cause I'm able to pass first test case) but the remainder of test cases lead to Timeout.


texts:
Task

Write an implementation that determines the count of happy numbers between a given start and end value.

Implementation

public class HappyNumberCounter {

  public static int getLastDigit(final long number) {
    return Math.toIntExact(number % 10);
  }

  public static long digitSquareSumCalculator(final long number) {
    int remainder = getLastDigit(number);
    long quotient = number / 10;
    long digitSum = remainder * remainder;
    while (quotient > 0) {
      remainder = getLastDigit(quotient);
      quotient = quotient / 10;
      digitSum = remainder * remainder;
    }

    return digitSum;
  }

  public static long countHappyNumbersInRange(final long startInclusive, final long endInclusive) {
    final Map<Long, Boolean> happyNumbers = new HashMap<>();
    long count = 0;
    for (long index = startInclusive; index <= endInclusive; index++) {
      long number = index;

      // case 1: already been cached
      // case 2: has not been cached
      // case 3: has not been cached but starts with 1 or 4
      // case 4: has not been cached and does not start with 1 or 4

      Boolean isHappy = happyNumbers.get(number);
      if (isHappy == Boolean.TRUE) {
        count++;
      } else if (isHappy == null) {
        long lastDigit = getLastDigit(number);
        if (lastDigit == 1) {
          happyNumbers.put(number, Boolean.TRUE);
          count++;
        } else if (lastDigit == 4) {
          happyNumbers.put(number, Boolean.FALSE);
        } else {
          final List<Long> numbers = new ArrayList<>();
          while (lastDigit != 1 && lastDigit != 4 && isHappy == null) {
            numbers.add(number);
            number = digitSquareSumCalculator(number);
            isHappy = happyNumbers.get(number);
            lastDigit = getLastDigit(number);
          }

          for (final Long num : numbers) {
            happyNumbers.put(num, isHappy);
          }

          if (isHappy) {
            count++;
          }
        }
      }
    }
    return count;
  }

}

Feedback

I feel like my implementation is too long (i.e. there's too much logic happening in one method), but I can't seem to find any natural break points.


texts:
This code is to solve the problem as mentioned here:

private void assignNeighbors(Node n){
      ArrayList<Node> current = new ArrayList<BinaryTree.Node>();
      if(n!=null) current.add(n);
      while(!current.isEmpty()){
          ArrayList<Node> parents = current;
          current = new ArrayList<BinaryTree.Node>();
          for(Node parent: parents){
              if(parent.left!=null && parent.right!=null){
                  parent.left.neighbor = parent.right;
              }
              if(parent.left!=null)current.add(parent.left);
              if(parent.right!=null) current.add(parent.right);
          }
      }
  }

Expected output is basically: Node:Neighbor

Node class:

public class Node{
        Node left,right;
        Node parent,neighbor; //parent is for some other problems I am solving. It's not related to this question.
        int data;

        Node(int d){
            left = null;
            right = null;
            parent = null;
            data = d;
            neighbor = null;
        }
    }


texts: Session expiration handler using PHP and jQuery

texts:
At this point i am interested to see other techniques on handling session timeouts.

What are some good improvements on this script to detect when a session is no longer valid?

Important definitions:

  session.gc_maxlifetime - (default 1440 seconds) defines how long an
  unused PHP session will be kept alive. For example: A user logs in,
  browses through your application or web site, for hours, for days. No
  problem. As long as the time between his clicks never exceed 1440
  seconds. It's a timeout value.

  session.cookie_lifetime - *This value (default 0, which means until the browser's next restart) defines how long (in seconds) a session
  cookie will live. Sounds similar to session.gc_maxlifetime, but
  it's a completely different approach. This value indirectly defines
  the "absolute" maximum lifetime of a session, whether the user is
  active or not. If this value is set to 1*60*60, every session ends after an
  hour.*

Problems to address:

Session timeout
Cookie timeout
Browser deleted cookies / cleared history

SESSION_handler.php

<?php
class SESSION_handler{
public static $gc_maxlifetime;
public static $cookie_lifetime;
function __construct(){
    self::$gc_maxlifetime = ini_get('session.gc_maxlifetime');
    self::$cookie_lifetime = ini_get('session.cookie_lifetime');
    if(session_status() == PHP_SESSION_NONE) {
        session_start();
    }
}
public function get($session_key){
    if(session_status() == PHP_SESSION_NONE) {
        if(!empty($_SESSION[$session_key])){
            $_SESSION['time_at_last_session'] = time();
            return $_SESSION[$session_key];
        }
    }
    return undefined;
}
public function set($session_key, $session_value){
    if(session_status() == PHP_SESSION_NONE) {
        $_SESSION[$session_key] = $session_value;
        $_SESSION['time_at_last_session'] = time();
        return $_SESSION[$session_key];
    }
    return undefined;
}
public function session_expired(){
    if(
        time() - ((!empty($_SESSION['time_at_last_session']))? $_SESSION['time_at_last_session'] : 0) >= self::$gc_maxlifetime ||
        session_status() == PHP_SESSION_NONE ||
        !isset($_COOKIE[session_name()])
        ){
        return true;
    }
    return false;
}
}
?>

is_session_expired.php

<?php
    $SESSION = new SESSION_handler();
    if($SESSION->session_expired()){
        echo "true";
    }else{
        echo "false";
    }
?>

AJAX

<script type="text/javascript">
    $(document).ready(function(){
        (function(){
            tmp_ = arguments.callee;
            window.setTimeout(function(){
                $.ajax({
                    url:'/php/is_session_expired.php',
                    success: function(session_expired){
                        if(session_expired == "true"){
                            alert("session has expired");
                        }else{
                            console.log('session has not expired');
                        }
                    }
                });
            });
        })();
    })
</script>