Checking to see if a string is alphabetic public class Alphabet {

 public static void main(String[] args) {
 checkAlphabetic("fdsfsfds+");

 }

 public static boolean checkAlphabetic(String input) {
 char[] chars = input.toCharArray();
 int count = 0;

 for (int i = 0; i < input.length(); i++) {
 if (Character.isLetter(chars[i])) {
 count = 1;
} else {

count = 0;
break;
}
}

if (count >= 1) {
System.out.println("alphabetic word");
return true;
} else {
System.out.println("word is not alphabetic");
return false;
}

}
  }

I know people will say to use regex as it's more efficient but our tutor wanted us to use loops, as we haven't learned about regex yet (old school course).

It's not harder than this:

public static boolean checkAlphabetic(String input) {
    for (int i = 0; i != input.length(); ++i) {
        if (!Character.isLetter(input.charAt(i))) {
            return false;
        }
    }

    return true;
}

The idea is to return false as soon as you encounter a character c for which Character.isLetter returns false. If no such, return true since the string does not contain non-letter characters.


Synchronization of two lists I'm looking for a better more efficient way to write some code I have where I"m synchronizing two lists.  Basically, the first list is a list of devices I need to check.  The second list is a list of devices that I have already checked with dates.  I need to synchronize the two lists so I only check devices that are new or out of date based on the date.  I also need to delete any devices that have been removed.

Here is my current code that works fine, it just looks and feels SO clunky.

public IEnumerable<AssetBlob> Synchronize(IEnumerable<AssetBlob> assets, string id) {
      //Get list of devices already checked in lineitemsmap
      List<AssetBlob> items = new List<AssetBlob>();
      IEnumerable<LineItemsMap> lineItems = auditRepo.GetLineItemsMap(id).DeviceResults;
      List<LineItemsMap> deleted = new List<LineItemsMap>();

      //put new items into list
      items.AddRange((from t0 in assets
                      join t1 in lineItems on t0.Id equals t1.BlobId into t1_join
                      from t1 in t1_join.DefaultIfEmpty()
                      where t1 == null
                      select t0).ToList());

      //list of existing items that need updated
      items.AddRange((from t0 in assets
                      join t1 in lineItems on t0.Id equals t1.BlobId
                      where t0.Imported > t1.Created
                      select t0).ToList());

      deleted.AddRange((from t0 in assets
                        join t1 in lineItems on t0.Id equals t1.BlobId
                        where t0.Imported > t1.Created
                        select t1).ToList());

      //Delete items in lineitems that don't exists in assets list
      deleted.AddRange((from t0 in lineItems
                        join t1 in assets on t0.BlobId equals t1.Id into t1_join
                        from t1 in t1_join.DefaultIfEmpty()
                        where t1 == null
                        select t0).ToList());

      if (deleted.Any()) {
        auditRepo.RemoveLineItemMaps(deleted);
      }

      return items;
    }

Any suggestion or improvements would be great.  Thank you.

I haven't tested this due to time constraints, and lack of knowledge of the data, but from my understanding of the problem, this should work.

I have taken the linq join queries, two for the insert, two for the delete and created two IEnumerable.Where clauses, one for insert, one for delete.  The two sets of criteria are combined in an OR statement within the .Where statement.

The one thing I wasn't sure on is if the original list needed to be returned.  That wasn't clear in the original code.  If it does need to be returned, that's an easy change to implement.

EDIT: Changed to do work per Kyles suggestion in comments.

public IEnumerable<AssetBlob> Synchronize(IEnumerable<AssetBlob> assets, string id)
{
    var assetsList = assets.ToList();

    //Get list of devices already checked in lineitemsmap
    IEnumerable<LineItemsMap> lineItems = auditRepo.GetLineItemsMap(id).DeviceResults;

    var items =
        assetsList.Where(
            existingAsset =>
                // ExisingItems that need updating
                // Any returns true if any of the items in a list meet the criteria
                lineItems.Any(lineItem => lineItem.BlobId == existingAsset.Id && existingAsset.Imported > lineItem.Created) ||
                // New items that need inserting.
                // All returns true if all of the items in a list meet the criteria
                // therefore All == !Any
                lineItems.All(lineItem => lineItem.BlobId == existingAsset.Id)).ToList();

    var deleted =
        lineItems.Where(lineItem =>
                        assetsList.Any(existingAsset => existingAsset.Imported > lineItem.Created) ||
                        assetsList.All(existingAsset => existingAsset.Id != lineItem.BlobId)).ToList();

    // If there is a foreach in RemoveLineItemMaps you can probably remove this check.
    // Just cleans up the code a little, and the foreach will take care of this check.
    if (deleted.Any())
    {
        auditRepo.RemoveLineItemMaps(deleted);
    }

    return items;
}


Detecting arrays with enough entries in common I have made a function called testing. This function tests whether five numbers from each sub-array of $source are included in $dataArray sub-arrays, at least $limit times. If so, it returns the source sub-array as a string; else it returns "x". Please see or try the example below if this description isn't clear.

And now it comes: this function works properly but with large quantity of sub-arrays in $sourceArray it is relatively slow (13 mins for 100000 tests on i7-7700K, PHP/7.1.4).

Is there any way to make this function more effective and quicker? Is there any noticeable bad construction / leak which may have an immediate impact on performance?

<?php

$dataArray=array(array(8,25,32,33,37,43),array(6,10,16,32,33,44),array(18,33,36,37,41,46),array(3,4,20,29,31,43),array(2,9,13,15,19,30),array(14,21,22,29,44,49),array(3,7,9,24,44,49),array(4,6,18,35,45,48));
// and so on - circa 4000 sub-arrays

$sourceArray=array(array(3,4,6,14,16,21,22,25,26,31,32,34,41,45,47,49),array(5,8,11,15,16,18,25,26,32),array(1,2,6,16,17,18,19,22,32,33,40,44,49),array(5,8,11,15,16,18,25,26,32),array(4,12,15,16,20,23,30,37,41,44));
// and so on - 10M+ sub-arrays (variable quantity)

function testing($dataArray, $source, $limit) {

$guessedArray = array();
foreach ($dataArray as $data) {
    $counter = 0;
    foreach ($source as $number) {
        if (in_array($number, $data)) {
            $counter++;
        }
    }
    array_push($guessedArray, $counter);
}

$guessedArray = array_count_values($guessedArray);
ksort($guessedArray);

if ($guessedArray[5] >= $limit) {
    return implode("-", $source);
  } else {return "x";}
}

foreach ($sourceArray as $oneArray) { // just example but $sourceArray's sub-arrays must be processed one by one
$result = testing($dataArray, $oneArray, 1);
echo "$result<br />";
}

/*
Result:
x
x
1-2-6-16-17-18-19-22-32-33-40-44-49
x
x

-> because only the third sub-array in $sourceArray contains five numbers located in $dataArray's sub-arrays for at least $limit times
(in this example $limit = 1)
*/

?>

This testing routine runs three to four times faster on the test data:

function testing($dataArray,$source,$limit)
{
  $matchesFound = 0;
  foreach ($dataArray as $data)
  {
    $counter = 0;
    foreach ($data as $number)
    {
      if (!in_array($number,$source)) $counter++;
      if ($counter == 2) break;
    }
    if ($counter == 1) $matchesFound++;
    if ($matchesFound >= $limit) return implode("-", $source);
  }
  return "x";
}

A big assumption is that $dataArray only contains arrays of 6 numbers and you will always look for 5 matching numbers.

The improvement is that I stop looping as soon as I know whether there is a match or not. You simply loop over all the data. So the real speed improvement depends heavily on the data. My guess is that it can perform even better on the complete data set.

More can probably be gained if your question was more informative.


Codility: MaxZeroProduct - complexity issues My solution scored 100% correctness, but 0% Performance.
I just can't figure out how to minimize complexity time.

Problem:

Write a function:

int solution(int A[], int N);

that, given an array of N positive integers, returns the maximum number of trailing zeros of the number obtained by multiplying three different elements from the array. Numbers are considered different if they are at different positions in the array.

For example, given A = [7, 15, 6, 20, 5, 10], the function should return 3 (you can obtain three trailing zeros by taking the product of numbers 15, 20 and 10 or 20, 5 and 10).

For another example, given A = [25, 10, 25, 10, 32], the function should return 4 (you can obtain four trailing zeros by taking the product of numbers 25, 25 and 32).

Assume that:

N is an integer within the range [3..100,000];
each element of array A is an integer within the range [1..1,000,000,000].

Complexity:

expected worst-case time complexity is \$O(N*log(max(A)))\$;
expected worst-case space complexity is \$O(N)\$ (not counting the storage required for input arguments).

Solution:

the idea:

factorize each element into pairs of 5's and 2's
sum each 3 pairs into one pair - this costs \$O(N³)\$
find the pair who's minimum coordinate value is the biggest
return that minimun coordinate value

the code:

int solution(int A[], int N) {
    int fives = 0, twos = 0, max_zeros = 0;
    int(*factors)[2] = calloc(N, sizeof(int[2])); //each item (x,y) represents the amount of 5's and 2's of the corresponding item in A

    for (int i = 0; i< N; i++) {
        factorize(A[i], &fives, &twos);
        factors[i][0] = fives;
        factors[i][1] = twos;
    }

    //O(N^3)
    for (int i = 0; i<N; i++) {
        for (int j = i + 1; j<N; j++) {
            for (int k = j + 1; k<N; k++) {
                int x = factors[i][0] + factors[j][0] + factors[k][0];
                int y = factors[i][1] + factors[j][1] + factors[k][1];
                max_zeros = max(max_zeros, min(x, y));
            }
        }
    }
    return max_zeros;
}

void factorize(int val, int* fives, int* twos) {
    int tmp = val;
    *fives = 0, *twos = 0;

    if (val == 0) return;
    while (val % 5 == 0) { //factors of 5
        val /= 5;
        (*fives)++;
    }
    while (val % 2 == 0) { //factors of 2
        val /= 2;
        (*twos)++;
    }
}

I can't figure out how else i can iterate over the N-sized array in order to find the optimal 3 items in time \$O(N*log(max(A)))\$.

You don't need to perform a full search.  Instead, we can transform it into a simple 2D geometry problem.  Consider the values as vectors in the "two" and "five" directions (which is equivalent to what you've already done).  For the example [25, 10, 25, 10, 32], we have two vectors 0,2, two of 1,1, and one of 5,0.

Now, you're looking for the sum of vectors that maximises the smaller dimension.  We can start by choosing the value with the largest minimum dimension (that's one of the 1,1 vectors).  From there, choose the next value that maximises the minimum dimension (the other 1,1).  From there, neither of the alternatives increases the minimum dimension, so our first partial result is 2.

Next, backtrack and choose the next-best value (5,0).  Now, the best value to add to this (to exceed the current best) is one with a large "five" dimension, namely (0,2).

This reasoning should now lead you to a way to order the array (or multiple copies of the array) so that we can short-circuit as many branches of this backtracking as possible (i.e. be able to say "with this position, we'll never see a value that can improve our score; finish this branch now").


Retrieve notifications and share across browser tabs The idea of this code is to poll the server every 15 seconds to check for and update the notifications indicator. However, I'm not convinced I've done it right, as sometimes it seems to take an unusual amount of time to propagate across tabs and some users have reported that notifications "get stuck" and don't update at all. So here's the code, I think everything's right, but maybe I missed something.

$(function() {
    var LSping = "notify_lastping",
        LSresult = "notify_result",
        poll, interval = 15*1000,
        notif_icon = $("#notifs>a"),
        notif_body = $("#notifications");

    if( notif_icon.length < 1) return;

    var notbox = null,
        lastping = -1,
        running = false;

    function startPoll() {
        var delay = interval;
        if( lastping == -1) {
            delay = (+localStorage[LSping]+interval || 0) - Date.now();
            if( delay < 100) delay = 100;
        }
        lastping = localStorage[LSping] || 0;
        if( poll) clearTimeout(poll);
        poll = setTimeout(getNotifications,delay);
    }
    function getNotifications() {
        // storage event should reset the poll and update notices for us,
        // but just to be sure...
        if( lastping != (localStorage[LSping] || 0)) {
            updateNotifications(
                JSON.parse(localStorage[LSresult] || '{"html":"","count":0}'),
                true
            );
            return startPoll();
        }

        // inform other tabs that I'm on this
        localStorage[LSping] = Date.now();

        if( !running) {
            running = true;
            ajax("/notices").success(function(r) {
                running = false;
                localStorage[LSresult] = JSON.stringify(r);
                updateNotifications(r);
            }).failure(function(r) {
                running = false;
                return true; // use default error handler for AJAX callback
            });
        }

        startPoll();
    }
    function updateNotifications(r,fromStorage) {
        if( !fromStorage) {
            var oldids = notif_body.find("[data-id]").map(function() {return this.getAttribute("data-id");}).get();
        }
        notif_icon.attr("data-count",r.count);
        notif_body.html(r.html);
        document.title = (r.count ? "["+r.count+"] " : "")+document.title.replace(/^\[\d+\]\s*/,"");

        if( !fromStorage) {
            var newids = notif_body.find("[data-id]").map(function() {return this.getAttribute("data-id");}).get();
            var diff = $(newids).not(oldids).get(); // damn jQuery can do some weird stuff XD
            if( diff.length > 0) {
                // play notification sound if selected by user settings
            }
        }
    }

    getNotifications();

    $(window).on("storage",function(e) {
        e = e.originalEvent;
        if( e.key == LSping) {
            startPoll();
        }
        if( e.key == LSresult) {
            updateNotifications(JSON.parse(localStorage[LSresult]),true);
        }
    });
});

As far as I can tell there's no reason for the "loop" to stop. getNotifications() calls startPoll() regardless of the AJAX result. But like I said, maybe I missed something.

I would try to also add a complete callback function to set running to false. It handles ( ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror")) Those should be handled by error and success but something is going on, so give it a shot?

Other than, your code is quite solid, I ran JSHint over it, and it got very few hits.

You never actually use notbox
You probably want to declare oldids before that if loop

Other than that

The naming is definitely a mixed bag, I would stick everywhere with lowerCamelCase ( lastping -> lastPing, notif_body -> notificationsBody ( or consider notificationsElementor perhaps just notifications )
You are using one liner ifs without curly braces.

Final thought, are you at any point rebuilding the DOM? If you rebuild the DOM (specifically any of the elements captured by notif_ico and notif_body), then your code stops working.


Replace fixed width values over 530px with 100% using RegEx Our site sends users transactional html emails. That content is then stored in a DB for retrieval when the user visits the mailbox section of our site.

The emails which get sent contain media queries in the header, which are lost as our system only pulls in the  of the content.

This is why I need to convert at fixed widths that are greater than 530px.

This is my take on replacing fixed widths >= 530px inside then content.

message.replace(/((?:m(?:in|ax)-)?width)\s*(\:\s?|=)\s*(['"\0])?\s*([1-9]\d{3,}|5[3-9][0-9]|[6-9][0-9]{2})(\s*(cm|in|mm|pc|pt|px|q)|(?!%|vw|vh|vmin|vmax|em|ex|ch|rem))[ ]*/gi, '$1$2100%')

It matches both HTML width attributes and CSS based properties that are fixed width values.

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

https://regex101.com/r/hdMYGn/6/

Example HTML:

<table align="center" class="container float-center" style="border-spacing: 0; border-collapse: collapse; padding: 0; vertical-align: top; background: #ffffff; width: 580px; margin: 0 auto; Margin: 0 auto; float: none; text-align: center;" width="580">

Disclaimer

As pointed out in a comment by Thomas Ward, RegEx should not be used to parse HTML or CSS. This answer should only be taken as a review of your regular expressions only, and doesn't imply that I recommend using RegEx to parse HTMl/CSS.

As mentioned by Phrancis, you may use DOM manipulation methods to iterate over elements and set styles on them. Or, you can also use CSS to set styles to containers, such that the elements inside it respect the cascaded styles. For example, setting max-width on container and overflow will make the width of the container fixed and show scroll bars when content inside it overflows.

If you add more context regarding how and where this RegEx is being used, there might be better ways than RegEx. Please edit the question to add more context.

Review

(\:\s?|=)\s*: In this group, it is matching either : followed by optional space or = symbol. : has no special meaning in regular expression i.e. it is not meta-character thus there is no need to escape it. Next, \s? is not required here. As there is \s* after the group, it'll match any number of spaces followed by the one of the symbol from the group. So, \s? can be safely removed.

After making these changes the group will become (:|=)\s*.

It is also observed that character class is faster than OR in groups. Check the demo for [:=] and (:|=) for same input data. Notice the number of steps required to finish match. Character class took 12 steps while group with OR condition took 30 step which is more than twice of the character class.

Now, after using character class the group will become [:=]\s*

Similarly, in other character class 0 is escaped as \0 which is not necessary and can be safely removed.

Let's look at the group (\s*(cm|in|mm|pc|pt|px|q)|(?!%|vw|vh|vmin|vmax|em|ex|ch|rem)).

This matches the unit f or the width property. First, \s* to match space is used. Space cannot be used between the value and unit in CSS. That'll make the property invalid and will not be applied.

After that, there are two groups of units separated by |-OR. These two can be combined in one as (cm|in|mm|pc|pt|px|q|%|vw|vh|vmin|vmax|em|ex|ch|rem).

At the end of regex, [ ]* is used to match any number of spaces. This can be simply written as *(Note this is space followed by *). What is there is a tab instead of space? \s* will solve the problem.

Oh wait, that space is not used anywhere, so it can be removed from regex.

Mistake

If you look closely at the input and output string, you'll notice that the regex is removing single and double quotes from the attribute styles.

width='530' has become width=100%'.

To solve this, simply add $3 in the replacement part. The replacement will be now $1$2$3100%.
Another one is that the regex leaves width: 600rem; which is not intended.

This will be solved when two groups of units are combined. But, this will create an issue of not matching unit-less values like width: 600. By adding empty option in group using | will solve the problem(notice the end of group). Here's how the group will look like

(cm|in|mm|pc|pt|px|q|%|vw|vh|vmin|vmax|em|ex|ch|rem|)

Improvements

Does the above changes really improve the regex?

The above changes brings the number of steps to 1630 from 1881 with one increase in match(rem).

RegEx: ((?:m(?:in|ax)-)?width)\s*([:=])\s*(['"0])?\s*([1-9]\d{3,}|5[3-9][0-9]|[6-9][0-9]{2})(cm|in|mm|pc|pt|px|q|%|vw|vh|vmin|vmax|em|ex|ch|rem|)

Replacement: $1$2$3100%

Demo

UPDATE:

  The emails which get sent contain media queries in the header, which are lost as our system only pulls in the of the content.

The media queries related to email can be stored in a separate CSS file and it can be included on the page where email content is shown on your site.

You can also remove all the inline styles from email content HTML and put them in separate CSS file. When sending email, include this CSS file in HTML and when showing the content in your site, include other CSS file. This will show the content correctly in respective sites.


Convert oOo to Brainfuck and vice-versa This program was inspired by a Code Golf challenge that I wanted to do properly. It simply converts oOo to Brainfuck and vice-versa.

The oOo language basically uses UPPER / lower case information in groups of 3 to encode a Brainfuck program. For further info see the Esolang wiki page of oOo.

The main problem with this code is that I feel like there is repetition in the encode / decode functions because they seem to contain similar type of information. I am also worried that I did not declare any types as Haskell is type-centric.

import qualified Data.Char as C
import qualified Data.List.Split as L
import qualified Test.QuickCheck as Q
import qualified Test.HUnit as T

oToBrain :: String -> String
oToBrain = map chunkToBrain . L.chunksOf 3 . filter isAlphabetic

brainToO :: String -> String
brainToO = concatMap singleCharToO

singleCharToO :: Char -> String
singleCharToO x = case x of
  '>' -> "ooo"
  '<' -> "ooO"
  '[' -> "oOo"
  ']' -> "oOO"
  '-' -> "Ooo"
  '+' -> "OoO"
  '.' -> "OOo"
  ',' -> "OOO"
  _ -> ""

isAlphabetic :: Char -> Bool
isAlphabetic = (`elem` ['a'..'z']) . C.toLower

chunkToBrain :: String -> Char
chunkToBrain [a, b, c] = case  (C.isUpper a, C.isUpper b, C.isUpper c) of
  (False, False, False) -> '>'
  (False, False, True ) -> '<'
  (False, True,  False) -> '['
  (False, True,  True ) -> ']'
  (True,  False, False) -> '-'
  (True,  False, True ) -> '+'
  (True,  True,  False) -> '.'
  (True,  True,  True ) -> ','
chunkToBrain _ = error "`oOo` chunks can only be 3 chars long"

brainChars :: Q.Gen String
brainChars = Q.listOf (Q.elements "<>[]+-.,")

doubleConversionIsId :: Q.Property
doubleConversionIsId = Q.forAll brainChars $ \x -> x == (oToBrain . brainToO) x

main = do
  T.assertEqual "Wiki example" ",[>,]<[.<]+" (oToBrain "PROgRam reVERsES giVeN iNPut sEqUENcE")
  Q.quickCheck doubleConversionIsId

import qualified Data.Char as C
import qualified Data.List.Split as L
import qualified Test.QuickCheck as Q
import qualified Test.HUnit as T

The qualified import here is good, but your module header is missing. Since there is no documentation you don't want to export some functions, for example the partial chunkToBrain.

oToBrain :: String -> String
oToBrain = map chunkToBrain . L.chunksOf 3 . filter isAlphabetic

While this might seem correct, the combination of chunkToBrain and L.chunksOf doesn't end well. According to esolangs, oOo code may have a non-divisible number of letters. The remaining ones are discarded. More on that later on chunkToBrain.

brainToO is fine, but isAlphabetic isn't, as elem ['a'..'z'] is C.isAsciiLower:

isAlphabetic = C.isAsciiLower . C.toLower

We will now take a look at your source of duplication, singleCharToO and chunkToBrain. Both suffer from somewhat the same problem: you need to define the map from Brainfuck instructions to oOo instructions and vice-versa. So let's define them:

oOoCode :: [String]
oOoCode = ["ooo", "ooO", "oOo", "oOO", "Ooo", "OoO", "OOo", "OOO"]

bfCode :: [Char]
bfCode  = [  '>',   '<',   '[',   ']',   '-',   '+',   '.',   ',']

bf2oOo :: [(Char, String)]
bf2oOo = zip bfCode oOoCode

oOo2bf :: [(String, Char)]
oOo2bf = zip oOoCode bfCode

Now singleCharToO is

singleCharToO x = fromMaybe "" (lookup x bf2oOo)

where fromMaybe is from Data.Maybe. You can use maybe "" id instead if you don't want to import another module.

Now to chunkToBrain. We will write a single helper beforehand:

toO :: Char -> Char
toO x = if C.isUpper x then 'O' else 'o'

I think you can already guess what happens next:

chunkToBrain :: String -> Maybe Char
chunkToBrain xs = lookup xs oOo2bf

You can of course use other data structures with better asymptotic complexity, but since there are only \$2^3\$ instructions this might be an overkill and should be benchmarked.

But wait a minute: the return type has changed. That's because the text is allowed to have superflous characters. "oOoOO" and "oOo" are the same programs in oOo. This leads to a slight change in oToBrain:

oToBrain = mapMaybe chunkToBrain . L.chunksOf 3 . filter isAlphabetic

Where mapMaybe is again a function from Data.Maybe, that discards Nothing from the list. This version of oToBrain has the right semantics, it doesn't throw an error.

Last but not least, your tests are sufficient for this code, although you should include tests that have oOo programs with a length that's not divisible by three.

  I am also worried that I did not declare any types as Haskell is type-centric.

At this point, we're slowly drifting out of the simple exercise and completely into parsing, pretty printing and (possibly) interpretation. What's a fitting data type for your code? No, let's have a look at the greater picture. What's a fitting data type for a Brainfuck or oOo program?

type Program = [Instruction]
data Instruction = IncVal | DecVal
                 | IncPos | DecPos
                 | Put    | Get
                 | Repeat Program

You'll notice that this will only allow syntactic correct programs, e.g. those that have the right pairings of [ and ]. You can use StartRepeat and EndRepeat instead, but that could make evaluation tricky.

You can then define two parsers:

-- or any other type with an erroneous state
oOoParser :: String -> Either String Program
bfParser  :: String -> Either String Program

Getting code again can be done similar to your previous code, although you need to apply the codegen recursively for Repeat.

toBF  :: Program -> String
tooOo :: Program -> String

The conversions can be defined in terms of the other four:

bf2oOo, oOo2bf :: String -> Either String String
bf2oOo = fmap toBF . oOoParser
oOo2bf = fmap tooOo . bfParser

This approach also allows you to define your own evaluation function without worrying about the loops:

eval :: Program -> String -> String
eval prog input = ...

But that's out of scope of this answer. Note that eval gets harder if you don't use the recursive Repeat variant, but parsing gets easier (and vice-versa).


Custom ostream for a println-like function I am writing a plugin in C++ that uses C API that gives me a single logging function with this signature:

typedef void(*println_t)(const char* text);

I want to wrap this type of a function in a nice ostream to use all C++ formatting features. Having read it is best to use streambuf for this, I made this code:

//println_buf.h

#include <string>
#include <sstream>

class println_buf : public std::streambuf
{
    typedef void(*println_t)(const char* text);
    println_t logfunc_;

    std::string buffer;
public:
    println_buf(println_t logfunc) : logfunc_(logfunc)
    {

    }

    println_buf(const println_buf &) = delete;
    println_buf(println_buf &&);
    println_buf& operator=(const println_buf &) = delete;
    println_buf& operator=(println_buf &&);

    virtual std::streamsize xsputn(const char* s, std::streamsize n) override;
    virtual int overflow(int c) override;
    virtual int sync() override;
};

//println_buf.cpp

#include "println_buf.h"

using namespace std;

println_buf::println_buf(println_buf &&o) : logfunc_(o.logfunc_), buffer(std::move(o.buffer))
{

}

println_buf& println_buf::operator=(println_buf &&o)
{
    logfunc_ = o.logfunc_;
    buffer = std::move(o.buffer);
    return *this;
}

streamsize println_buf::xsputn(const char* s, streamsize n)
{
    streamsize start = 0;
    for (std::streamsize i = 0; i < n; i++)
    {
        if (s[i] == '\n')
        {
            buffer.append(s + start, s + i);
            sync();
            start = i + 1;
        }
    }
    buffer.append(s + start, s + n);
    return n;
}

int println_buf::overflow(int c)
{
    char ch = traits_type::to_char_type(c);
    if (ch == '\n')
    {
        sync();
    } else {
        buffer.append(1, c);
    }
    return c;
}

int println_buf::sync()
{
    logfunc_(buffer.c_str());
    buffer.clear();
    return 0;
}

Usage:

println_t logfunc = ...;
println_buf buffer(logfunc);
std::ostream stream(&buffer);
stream << "Hello world" << std::endl;

It should be noted that println_t includes a newline automatically in the actual output, but I want to have to specify the line separator in C++.

My concern is that the function should not be called with a string containing \n, but the string must be passed to the function only if it originally ended with \n, and be buffered otherwise. Also endl should cause the function to be called immediately.

I'll review more later but a basic comment first.

Rather than write just the println_buf class I would also write the println_stream class that internally has a println_buf.

class println_stream: std::ostream
{
    // Make this a private class.
    // You don't need to leak implementation details.
    // As far as anybody else is convered it is just std::streambuf
    class println_buf { /* STUFF */ };

    println_buf     buf;
    std::streambuf* oldBuf = nullptr;
    public:
        println_stream()
            // You can't pass the buf to the ostream constructor
            // here as it has not been constructed yet.
            // There are ways but lets keep it simple for now.
        {
            // I did not do the work with logfunc
            // Have not read that bit yet.
            // But you get the idea I hope.
            oldBuf = rdbuf(&buf);
        }
        ~println_stream()
        {
            // Can't remember if it is required.
            // But I would always set back the original buffer.
            rdbuf(oldBuf);
        }
};

int main()
{
   println_stream stream;
    stream << "Hello world\n";
}


Swift main thread style I run into issues where I forget to run UI changes on the main thread.

I've just fixed an issue for loading and unloading an activity indicator and fixed it with the following code:

if active {
    DispatchQueue.main.async {
        UIApplication.shared.keyWindow?.startIndicatingActivity()
    }
} else {
    DispatchQueue.main.async {
        UIApplication.shared.keyWindow?.stopIndicatingActivity()
    }
}

Now an alternative is this code:

DispatchQueue.main.async {
    if active { UIApplication.shared.keyWindow?.startIndicatingActivity()
    } else { UIApplication.shared.keyWindow?.stopIndicatingActivity()
    }
}

Now which one is right / more maintainable for the future?

From a processing efficiency perspective, they are largely indistinguishable. But if I were forced to choose between these two approaches, I might lean towards the latter, wrapping the whole if-else test in a single dispatch to the main queue, for two reasons:

There is a timing issue:

Let’s assume you ran this from a background thread and active was false, so you asynchronously dispatch the activity indicator update back to the main queue. What if, by the time the main queue gets to the dispatched block, that active is now true? Do you still really want to turn off the activity indicator? No, you almost certainly want to treat the combined test of active and the corresponding updating of the activity indicator as a single operation.
There is a thread safety issue:

When dealing with this boolean (and I’m assuming it’s a simple boolean, not wrapped in some synchronization mechanism), you should think about how you ensure thread-safe access to it. One really should synchronize access to one’s properties when writing multi-threaded code, and the first approach makes it unclear from which thread are you retrieving active (much less from which thread(s) is it being updated). One very simple synchronization technique to ensure that all reads and writes to active are done on the main queue, which, by virtue of being a serial queue, ensures thread-safety.

A few observations regarding other possible patterns/considerations:

You might want to consider whether, rather than writing a routine that you manually call to check active and update the activity indicator accordingly (meaning that every time you update active, you have to remember to call this routine), whether you might prefer to just supply the active property an observer that does the updating of the activity indicator for you. If you can have your property automatically trigger the UI update, then it eliminates the possibility of them getting out of sync.
There are special concerns if the changes to active are happening very quickly:

First, if active changes are happening extremely quickly (e.g. thousands of times per second), you risk flooding the main queue. You can address these sorts of issues with things like dispatch sources.
Second, even if it’s only a couple of times per second, you might want to avoid starting and stopping the activity indicator too quickly (because it yields a spinner that is constantly restarting, yielding a “Max Headroom” style of stuttering effect). For example, if active changes every ¼ second, and keeps doing that for 10 seconds, you may want to just want to keep the spinner going for that full 10 seconds, not starting and stopping it repeatedly. You can accomplish this by programming some latency in the “stop activity indicator” routine. E.g. when active is set to false, add non-repeating timer to stop the activity indicator in ½ second, but only after canceling any prior timer, if any. Likewise, when active is set to true, only “start” the activity indicator if you know it’s not already started.

Bottom line, be aware that the right implementation might depend upon the frequency of changes.


Tweets per second, using linked list This is a TalentBuddy Challenge

  Your task is to
  write a function that prints to the standard output (stdout) the highest number of tweets recorded between each second in the array and the past windowSize seconds before it

  Note that your function will receive the following arguments:

  TweetsPerSecond
  which is an array of integers representing the number of tweets recorded every second

  WindowSize
  which is the integer number mentioned above

I've ran my code on talentbuddy, and I think their back-end is broken, because it says my test case fails from missing data (far down the line), and when I run the test on my machine with the same inputs it prints out the right amount and correct data, in 30-80 Milliseconds. SO IT WORKS.

I am looking for a general review of my code and practices. Keep in mind that efficiency is key here.

I've added useful comments to document the flow of the program (even though they make it look ugly)

class Node
{
    public Node Next;
    public int Value;
}

public static void TweetsPerSecond(int[] tweetsPerSecond, int windowSize)
{
    Node head  = null; // Front of the window (where values fall out)
    Node max   = null; // Node with max value in the window
    Node check = null; // Starting node of list of Nodes to be checked against the max
    Node back  = null; // End of the window (where new values are put in)

    int count = 0; // Count of numbers in the window
    string[] maxes = new string[tweetsPerSecond.Length]; // Max values to be printed to the console.
    for (int i = 0; i < tweetsPerSecond.Length; i++)
    {
        // If this is our very first number being added, create new head node
        // Else append a new node to the back of the list, and set it to be the next checked node against the max
        if (head == null) max = back = head = new Node() { Value = tweetsPerSecond[i] };
        else check = back = back.Next = new Node() { Value = tweetsPerSecond[i] };

        // If we have filled up the window with values
        if (count + 1 > windowSize)
        {
            // If the maximum value is falling out of the window
            if (head == max)
            {
                // Maximum value is defaultly set to the first value in the window
                max = head.Next;
                // And we set the next nodes to be tested against this new max to be all nodes in the window after the max
                check = max.Next;
            }
            head = head.Next;
        }
        else count++;

        // Start our checking with the set CHECK node, which is typically just the most recently added node, unless our max fell out of the window
        Node next = check;
        while (next != null)
        {
            // If this node being checked is higher than our highest found value, then set this node to be the highest (MAX), and check the next.
            if (next.Value > max.Value) max = next;
            next = next.Next;
        }

        // Store our found max node in an array.
        maxes[i] = max.Value.ToString();
    }
    File.WriteAllLines("out.txt", maxes);
    //Console.WriteLine(string.Join(Environment.NewLine, maxes));
}

First of all, I think there is an off-by-one error in your code. From my understanding of the question, the correct output for

var tweetsPerSecond = new[] { 1, 3, 2 };
var windowSize = 1;

would be { 1, 3, 3 }, while your code gives the answer { 1, 3, 2 }.

Also a window size of 0 throws a NullReferenceException.

While there are minor stylistic complaints I would focus on in a normal code review, I believe the bigger picture is that you are using the wrong data structures for this problem.

You are duplicating the information stored in tweetsPerSecond, an array, in a linked list. You don't need this duplication, you can just index into the array.

Second, to find the maximum in a range in the array, you are iterating through the entire range. Using a skip list would change this from an \$O(n)\$ operation to an \$O(1)\$ operation, with adding and removing elements being \$O(\log n)\$.

Assuming an implementation of a SkipList<T> class, the algorithm would look like this:

public static IEnumerable<int> TweetsPerSecond(int[] tweetsPerSecond, int windowSize)
{
    var size = windowSize + 1;
    var skipList = new SkipList<int>(size);
    for (var i = 0; i < tweetsPerSecond.Length; i++)
    {
        if (skipList.Count == size)
        {
            skipList.Remove(tweetsPerSecond[i - size]);
        }

        skipList.Add(tweetsPerSecond[i]);
        yield return skipList.Last;
    }
}

If you don't want to go to the trouble of implementing a skip list, I think you can fake it with a combination of SortedSet<T> and Dictionary<TKey, TValue>. I couldn't find guarantees of the run time of the relevant operations on MSDN, but it runs much faster on this test input:

var tweetsPerSecond = Enumerable.Range(0, 100000).Reverse().ToArray();
var windowSize = 10000;

Here is the sample code (possibly buggy):

public static IEnumerable<int> TweetsPerSecond(int[] tweetsPerSecond, int windowSize)
{
    var size = windowSize + 1;
    var bag = new SortedBag<int>();
    for (var i = 0; i < tweetsPerSecond.Length; i++)
    {
        if (i > windowSize)
        {
            bag.Remove(tweetsPerSecond[i - size]);
        }

        bag.Add(tweetsPerSecond[i]);
        yield return bag.Max;
    }
}

private class SortedBag<T>
{
    private readonly Dictionary<T, int> count = new Dictionary<T, int>();
    private readonly SortedSet<T> set = new SortedSet<T>();

    public void Remove(T value)
    {
        count[value] = count[value] - 1;
        if (count[value] == 0)
        {
            this.set.Remove(value);
            this.count.Remove(value);
        }
    }

    public void Add(T value)
    {
        int occurrences;
        if (this.count.TryGetValue(value, out occurrences))
        {
            this.count[value] = occurrences + 1;
            return;
        }

        this.count[value] = 1;
        this.set.Add(value);
    }

    public T Max
    {
        get { return this.set.Max; }
    }
}

Edit: there's a better solution with \$O(n)\$ complexity. I had great fun thinking about this problem, and would recommend anyone reading this post to think it through further before clicking that link.


Very simple OS in Assembly I made a very simple OS in Assembly. But my code is too long. I want to make my code shorter.
Here is my code:
    BITS 16

start:
    mov ax, 07C0h
    add ax, 288
    mov ss, ax
    mov sp, 4096

    mov ax, 07C0h
    mov ds, ax

    mov si, text_string
    call print_string

    jmp $

    text_string db 'OS', 0

print_string:
    mov ah, 0Eh

.repeat:
    lodsb
    cmp al, 0
    je .done
    int 10h
    jmp .repeat

.done:
    ret

    times 510-($-$$) db 0
    dw 0xAA55

Makefile:
DIR=build build
$(shell mkdir -p $(DIR))
$(shell nasm -f bin OS1.asm -o build/OS1.flp)
$(shell mkisofs -no-emul-boot -o build/OS1.iso -b OS1.flp build)

Can I make this code shorter? Is it possible to do? If it is, how?
(This code may be updated in my GitHub account.)

Can I make this code shorter?

If you use the ORG 7C00h directive, then loading the segment registers will be shorter code.
You can choose to setup the stack below the bootloader and shave off that addition. Even if you leave the stack where you placed it before (above the bootloader), with SS=0 the change would become mov sp, 9E00h.
You avoid having to load the string address (and the need to come up with suitable label names) if you store the actual string directly beneath the call instruction and have the print_string routine jump back to behind the terminating zero.
This technique becomes more interesting if more than 1 string is to be printed.

    BITS  16
    ORG   7C00h

start:
    cld                          <--- Not shorter but better!
    xor   ax, ax
    mov   ds, ax
    mov   ss, ax
    mov   sp, 7C00h

    call  print_string
    db    'OS', 0
    jmp   $

print_string:
    pop   si
    mov   bx, 7                  <--- Not shorter but better!
    mov   ah, 0Eh
.repeat:
    cs lodsb ; Need CS override since SI is an offset in code segment!
    cmp   al, 0
    je    .done
    int   10h
    jmp   .repeat
.done:
    jmp   si

    times 510-($-$$) db 0
    dw 0xAA55

The CS segment override on the LODSB instruction is required unless you know that DS == CS. Many bootloaders will have a far jump at the top to ensure that this is the case. e.g. jmp 0000h:7C05h as the very first instruction. This will set CS=0.
Not shorter but better

Adding a CLD instruction makes sure that the LODSB instruction will function correctly.
Passing all the required parameters to the BIOS.Teletype function is best. BH is DisplayPage and BL is GraphicsColor. If you know that the screen is in a text video mode then you can drop the setting for BL and just write mov bh, 0 to select the video page.


Secure INSERTs with MySQLi Is this code well protected, and if not, could you tell me how it might be exploited and how to secure it?

if(isset($_POST['vrsta_predmeta']) AND !empty($_POST['vrsta_predmeta']) AND

isset($_POST['res_text']) AND isset($_POST['glavni_dug']) AND isset($_POST['res']) AND isset($_POST['zaklj']) AND isset($_POST['povjerilac']) AND isset($_POST['duznik']) AND isset($_POST['predmet_zaveden'])){

$racunob =  trim($_POST['rac']);
$obrazlozenje = trim($_POST['obr']);
$ob_text = trim($_POST['res_ob']);
$res_text = trim($_POST['res_text']);
$vrsta_pre = trim($_POST['vrsta_predmeta']);
$izvrsenje = trim(strtolower($_POST['res']));
$obrazac = trim($_POST['zaklj']);
$povjerilac = $_POST['povjerilac'];
$duznik = $_POST['duznik'];
$datum= trim($_POST['predmet_zaveden']);
 foreach($povjerilac as $key){
 $lica = $db -> prepare("INSERT INTO p_lica(povjerilac, doc_br, dokument_vlasnik) VALUES('$key', '$dok_broj', '$ses_val')");

}

foreach($duznik as $key1){
 $lica1 = $db -> prepare("INSERT INTO d_lica(duznik,doc_br, dokument_vlasnik) VALUES('$key1', '$dok_broj', '$ses_val')");

}

$insert_dok = $db -> prepare("INSERT INTO document_tbl(dokument_vlasnik,dokument_broj,vrsta_dokumenta,zakljucak, resenje_izvrsenja,datum,resenje_text,obrazlozenje,obtext,racunob) VALUES('$ses_val','$dok_broj', '$vrsta_pre','$obrazac','$izvrsenje','$datum','$res_text','$obrazlozenje','$ob_text','$racunob')");
if($lica -> execute() AND $insert_dok -> execute() AND $lica1 -> execute()){

   $lica -> close();
   $lica1 -> close();
   $insert_dok -> close();

  echo '<script>new Messi(\'Dokument uspjesno dodat.\', {title: \'Obavjestenje\', titleClass: \'success\', buttons: [{id: 0, label: \'Close\', val: \'X\'}]});</script>';
header('location:login.php');
  }else{
   echo '<script>new Messi(\'Dokument uspjesno dodat.\', {title: \'Obavjestenje\', titleClass: \'anim warning\', buttons: [{id: 0, label: \'Close\', val: \'X\'}]});</script>';
}

}

No, this code is not secure, as you are using prepared statements wrong. See here for correct usage of mysqli prepared statements (you should not ever have user supplied input in the prepare statement, it is only for SQL syntax; add the user input via bind later on).

For example, your code might look like this:

$sql = $db->prepare('INSERT INTO p_lica (povjerilac, doc_br, dokument_vlasnik) VALUES(?, ?, ?)'); // note that there is no user input in prepare
$sql->bind_param('iss', $key, $dok_broj, $ses_val); // s for string, i for integer. use d for double, b for blob

foreach($povjerilac as $key) { // set values for $key, which is bound to the first ? parameter
    $sql->execute(); // insert new row with current key
}
$sql->close();

(see also here or here)

Misc

formatting: your code is very badly formatted. If this is just a copy-paste error it's ok, but otherwise, you should definitely fix it.
variable names: the standard is to use english names, if you can.
your header call seems wrong. From the documentation: Remember that header() must be called before any actual output is sent. You should also use a complete URL.


Parsing a string using a regex and doing a mathematical calculation if there is a match This is my first time writing anything in C#/.NET. I have written a simple function that takes a string, splits it, compares each split value with a regex and if it matches it'll take the second part of the string, which is a double and rounds it and than replaces the old value in the string with the new rounded value. However I feel like this code could be much cleaner but since I have no experience I'm not sure how. I would appreciate any tips so I can improve my skills

public static void Main()
{
        String pattern = "FL2 (77) Flashing,77,a=1.875,A=90.0,b=3.625,B=95.0,c=1.375,C=175.0,d=2.5,hem=0.5,16GA-AL,";
        string[] fParams = pattern.Split(',');
        Regex regex = new Regex("([a-zA-Z]=.*?)");

        for (int i = 0; i < fParams.Length; i++)
        {
            if (regex.IsMatch(fParams[i]))
            {
                Console.WriteLine("true " + fParams[i]);
                if (fParams[i].Any(char.IsUpper))
                {
                    Console.WriteLine("upper case", fParams[i]);
                    string[] param = fParams[i].Split('=');
                    // Note in actual program I do more complex calculations
                    Double value = Math.Round(Convert.ToDouble(param[1]));
                    pattern = pattern.Replace(fParams[i], param[0]+"="+Convert.ToString(value));
                }
                else
                {
                    Console.WriteLine("lower case", fParams[i]);
                    string[] param = fParams[i].Split('=');
                    // Note in actual program I do more complex calculations
                    Double value = Math.Round(Convert.ToDouble(param[1]) * 2) / 2;
                    pattern = pattern.Replace(fParams[i], param[0] + "=" + Convert.ToString(value));
                }

            }
        }

        //return pattern;
}

Here is the link to the fiddle

There is a wonderful overload of the Regex.Replace method that takes a MatchEvaluator delegate which does exactly what you need it to:
var pattern = "FL2 (77) Flashing,77,a=1.875,A=90.0,b=3.625,B=95.0,c=1.375,C=175.0,d=2.5,hem=0.5,16GA-AL,";
var regex = new Regex("(?<label>[a-zA-Z]+)=(?<value>[^,]+)", RegexOptions.ExplicitCapture);

var result = regex.Replace(pattern, m =>
{
    // Edited - as Paparazzi noted in the comments, I missed
    // the fact that the calculation was different for uppercase
    // and lowercase...

    var newValue = m.Groups["label"].Value.Any(char.IsUpper)
        ? Math.Round(Convert.ToDouble(m.Groups["value"].Value))
        : Math.Round(Convert.ToDouble(m.Groups["value"].Value) * 2) / 2;

    return $"{m.Groups["label"].Value}={newValue}";
});

I've used a few things that might be new to you:

ExplicitCapture specifies that the only valid captures are explicitly named or numbered groups of the form (?…) See documentation
String interpolation - see documentation
var which is implicit typing

I appreciate that the Regex might be more complicated than you're comfortable with but it simply says that I'm looking for 2 groups seperated by an = sign. The label group and the value group. You can then access these by name in the match evaluator. The [^,]+ means match one or more of any character which is not a comma.
Edit:
You don't actually need the ExplicitCapture option - sorry, I modified your Regex and the first iteration had an extra set of () around it. I'll leave it in the answer as it's something that's worth knowing about.


Print distinct car names with count in descending order After reading this question, it jumped to me that many said that the solution to the problem is over-engineered / overkill.

Here I solve the same problem in Python in a more compact way. I think that this solution is compact enough. If you still think that this is overkill for the problem, please tell me. Any kind of other code review is welcome too.

"""
Item list analyzer

Given a file with an element in each line,
for each item this programme will print the number of times
it appears in the text file. It will also sort the items
from the most frequent to the least frequent.

Example:
    example.txt:
        spam \n spam \n eggs \n spam \n foo \n baz \n eggs
        # "\n" should be actual newlines not the "\n" string

    Ouput:
        ('spam', 3)
        ('eggs', 2)
        ('baz', 1)
        ('foo', 1)

"""
import operator

FILENAME = "cars.txt"

def return_frequncy_dict(lst):
    """
    Given a list as input returns a
    dict containg the items as keys and
    the number of occurencies of each item as
    values.

    >>> return_frequncy_dict(["a","b","c","b","b","a"])
    {'a': 2, 'c': 1, 'b': 3}
    """
    return {i:lst.count(i) for i in lst}

def sort_by_value(dict_):
    """
    As the frequency is the value, to sort by frequency we
    must sort by value. Standard sorting goes from the smallest
    to the biggest, we want the reverse of it.

    Credit for this function goes to
    http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
    """
    return reversed(sorted(dict_.items(), key=operator.itemgetter(1)))

if __name__ == "__main__":
    with open(FILENAME,"r") as f:
        data = f.read()

    item_list = data.splitlines()
    item_list = [item.lower() for item in item_list]
    item_list = [item.strip() for item in item_list]

    for j in sort_by_value(return_frequncy_dict(item_list)):
        print(j)

I'm sure that someone who knows more Python than me will be able to provide more feedback, but I see a couple of issues.

The first is that the core of this functionality is implemented by collections.Counter. We can just write this:

def frequency(lst):
    counter = Counter(lst)
    return reversed(sorted(counter.items(), key=lambda x:x[1]))

The second issue is with these lines:

item_list = [item.lower() for item in item_list]
item_list = [item.strip() for item in item_list]

We can just write

item_list = [item.lower().strip() for item in item_list]

Or as @janos suggested,

item_list = [item.lower().strip() for item in data.splitlines()]


function to append "a" or "an" to the front of a number as appropriate Input: any integer

Output: that integer in number format (commas) with a leading a or an as appropriate with the rules of English

After a bit of groping around I hacked out the following PHP function, and am looking for any advice on code structure and optimization. Thank you!

function prefixAAnToNumber($num) {
    $prefixAn = array(8, 11, 18, '8', '11', '18');
    $verAn = 'an ' . number_format($num);
    $verA = 'a ' . number_format($num);

    if (in_array($num,$prefixAn)) {
        return $verAn;
    } else if (strlen($num) > 1) {
        $numComma = number_format($num);
        if (substr($numComma,0,1) == '8') {
            return $verAn;
        } else if (in_array(substr($numComma,0,2), $prefixAn) && substr($numComma,2,1) == ',') {
            return $verAn;
        } else {
            return $verA;
        }
    } else {
        return $verA;
    }
}

Example usage:

$num = 11;
for ($i = 0; $i < 10; ++$i) {
    echo '<p>'.$num.' -> "';
    echo prefixAAnToNumber($num);
    echo ' kg shipment"</p>';
    $num = $num * 10;
}

Output:

11 -> "an 11 kg shipment"

110 -> "a 110 kg shipment"

1100 -> "a 1,100 kg shipment"

11000 -> "an 11,000 kg shipment"

110000 -> "a 110,000 kg shipment"

1100000 -> "a 1,100,000 kg shipment"

11000000 -> "an 11,000,000 kg shipment"

110000000 -> "a 110,000,000 kg shipment"

1100000000 -> "a 1,100,000,000 kg shipment"

11000000000 -> "an 11,000,000,000 kg shipment"

Rather than having many return statements I would keep the logic that determines whether it should be 'a' or 'an' together.  I think it is actually easier to understand reading the ANDs and ORs than spread out if and else statements.

I prefer not to create temporary variables that are not used for anything - so I wouldn't create $verA and $verAn.  I do however create a variable for $numComma.  By having this we avoid calling number_format more than is necessary.

This is how it looks my way:

function prefixAAnToNumber($num)
{
    $prefixAn = array(8, 11, 18, '8', '11', '18');
    $numComma = number_format($num);

    if (in_array($num, $prefixAn) ||
    (strlen($num) > 1 &&
     (substr($numComma, 0, 1) == '8' ||
      (in_array(substr($numComma, 0, 2), $prefixAn) &&
       substr($numComma, 2, 1) == ','))))
    {
        return 'an ' . $numComma;
    }

    return 'a ' . $numComma;
}


Coin flip simulator with GUI from random import randint
from time import sleep
from sys import (exit, argv)
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QToolTip, QPushButton, QApplication, QWidget, QLabel)
from PyQt5.QtGui import (QIcon, QPixmap, QFont)

#Creates the main widget which will contain everything else
class coinflipsimulator(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        #Creates the QLabel 'coin' which will contain the image of the coin
        self.coin = QLabel(self)
        #Uses QPixmap to place a random coin image (head or tail) into the QLabel 'coin'
        self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        self.coin.move(0.5, 0.5)

        #Creates the button that will activate the simulated coin flip when clicked and labels it 'Flip' using QPushButton
        self.btn = QPushButton('Flip', self)
        #Selects the font/font size for the label on the QPushButton 'btn' using QFont
        self.btn.setFont(QFont('SansSerif', 20))
        #Creates a tooltip when user hovers over the QPushButton 'btn' using QToolTip
        self.btn.setToolTip('Click to Flip Coin')
        #Selects the font/font size for the QToolTip above on the QPushButton 'btn' using QFont
        QToolTip.setFont(QFont('SansSerif', 10))
        #Connects the QPushButton 'btn' to the function 'flipcoin' to activate when the button is clicked
        self.btn.clicked.connect(self.flipcoin)
        self.btn.resize(166, 43)
        self.btn.move(-2, 161)

        #Sets where on the screen the window will open and the size of the window respectively using x and y coordinates
        self.setGeometry(1427, 30, 162, 201)
        #Locks the size of the window and make it impossible for the user to change it
        self.setFixedSize(self.size())
        self.setWindowTitle('Coin Flip Simulator')
        #Sets the window icon to the image file 'icon.png' located in the same folder as the source file
        self.setWindowIcon(QIcon('icon.png'))
        self.show()

    def flipcoin(self):
        #Sets the image inside the Qlabel 'coin' to a coin flipping animation...aspect ratio is ignored to get the animation to fit inside the window correctly
        self.coin.setPixmap(QPixmap('coin_flipping_animation.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        #Processes any change made to the program/window in this case the change of the image in the Qlabel 'coin'
        QApplication.processEvents()
        #Pauses the execution of any more code for 0.5 seconds
        sleep(0.5)
        #Sets the image inside the QLabel 'coin' to a random coin image (head or tail) into the QLabel 'coin'
        self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        #Processes the second change to the QLabel 'dice'
        QApplication.processEvents()

if __name__ == '__main__':

    #Begins the execution of the QApplication

    app = QApplication(argv)
    ex = coinflipsimulator()
    ex.show()
    exit(app.exec_())

This is the first GUI I have completed since I started learning to code. It is a simple program which simulates a die roll when the user clicks a button. I am quite proud of myself even though I know it's nothing great still I am always open to advice and suggestions.

Nice program, so only some tips:

First of all, you comments are very useful for you as a beginner but without them your code is much nicer:

class coinflipsimulator(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.coin = QLabel(self)
        self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        self.coin.move(0.5, 0.5)

        self.btn = QPushButton('Flip', self)
        self.btn.setFont(QFont('SansSerif', 20))
        self.btn.setToolTip('Click to Flip Coin')
        QToolTip.setFont(QFont('SansSerif', 10))
        self.btn.clicked.connect(self.flipcoin)
        self.btn.resize(166, 43)
        self.btn.move(-2, 161)

        self.setGeometry(1427, 30, 162, 201)
        self.setFixedSize(self.size())
        self.setWindowTitle('Coin Flip Simulator')
        self.setWindowIcon(QIcon('icon.png'))
        self.show()

    def flipcoin(self):
        self.coin.setPixmap(QPixmap('coin_flipping_animation.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        QApplication.processEvents()
        sleep(0.5)
        self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        QApplication.processEvents()

if __name__ == '__main__':

    app = QApplication(argv)
    ex = coinflipsimulator()
    ex.show()
    exit(app.exec_())

Follow the DRY principle (Don't Repeat Yourself). In your code is 2 times the same statement

self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))

In them you repeatedly construct one of two picture names:

coin_1.png
coin_2.png

Why not create a list or a tuple of them, e. g.

COINS = ('coin1.png', 'coin_2.png')

(note the use of uppercase letters for its name as a signal that it will not change) and instead of the

randint(1, 2)

use

choice(COINS)

Or - even better - create the list or tuple of 2 QPixmap objects and apply the choice() function on it?

Hard-coded file names (as the 2 mentioned above) are spread in your code so it will be more difficult to search for them in the case for the need of change them.

What about give all of them (together with other constants) appropriate names near the start of your, e. g.

ICON = 'icon.png'
SLEEP_TIME = .5

and then use those names?

You may even create constants for parameter lists of functions / methods - as you use the same again and again - and then use them, e. g.

SCALED_PARMS = 162, 302, Qt.KeepAspectRatio, Qt.FastTransformation

and then use them in the form

.scaled(*SCALED_PARMS)     # This is only the part of your command

(note the asterisk (*) in front of them for unpacking the ones).


Maths Q&A game in JavaScript This used to be university work now I put it our here for review purposes.

Could this be constructed better?
Is there any easier path, performance-wise?
Could this be optimised?
Which features and functionalities could/should be added to this game?

<!doctype html>

    <title>Math.floor</title>

 Math.floor: The Maths Game

You ask some unreasonable division questions.

That is answerable by the special string Infinity, but not infinity.

The expected answer is NaN, but responding with NaN will not work.

  10 / 3 = 3.33333333 is INCORRECT. The correct answer is 3.3333333333333335


Code to pass json data with WCF REST POST I have a WCF REST POST that has JSON data as input,

IService.cs:

 [OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
void ImportJSON(Stream request);

IService.svc:

 public void ImportJSON(Stream request)
    {
        using (var reader = new StreamReader(request))
        {

            var resultStream = reader.ReadToEnd();
            var model = JsonConvert.DeserializeObject<dynamic>(resultStream);
            var resHeaders = model.Headers;
            var resValues = model.Values;
            string str = "";
            string strValues = "";
            foreach (var item in resHeaders)
            {
                str = str + item.Header + ";";
            }
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendLine(str);
            foreach (var item in resValues)
            {
                strValues = item.value + ";";
                stringBuilder.AppendLine(strValues);
                strValues = "";
            }
            System.Guid guid = Guid.NewGuid();
            var path = HttpContext.Current.Server.MapPath("~/App_Data/tmp/" + guid.ToString() + ".csv");
            using (StreamWriter writetext = new StreamWriter(path))
            {
                writetext.WriteLine(stringBuilder);
            }
        }
    }

An exemple of JSON data:

{
    "Headers": [{"Header":"CA"},{"Header":"PE"},{"Header":"AMOUNT"}],
    "Values": [{"value":"toto;tata;titi"}, {"value":"A;2019;S100"}, {"value":"A;2019;S100"}, {"value":"A;2019;S300"},
                {"value":"A;2013;S23"}, {"value":"A;2013;S200"}, {"value":"A;2013;S200"}, {"value":"A;2019;S100"}]
}

In fact, I don't use any classe : I use anonyme data directly, and I use dynamic on the Deserialization JSON,

I have my result as I wish : I get all the data from JSON then I saved all data in a txt/csv  file, My result:

CA;PE;AMOUNT;
toto;tata;titi;
A;2019;S100;
A;2019;S100;
A;2019;S300;
A;2013;S23;
A;2013;S200;
A;2013;S200;
A;2019;S100;

Is my code is correct?

Are there any impact affect performance ?

And is there any problem if I have very long JSON data ?

And if there are any advise or feedback for my code.

Is my code is correct?

Yes, but it needs just some tweaks in some areas. The only part I need to noted is when you declaring a StringBuilder and you're creating multiple string objects then append them to the StringBuilder. for this, you misused the StringBuilder, and what you need to do, is to use StringBuilder directly, and don't create strings outside the StringBuilder. Everything else looks fine to me.

for the dynamic part, it's fine to use dyanmic then using strong typed objects if you know the exact structure of the returned JSON. You'll only lose some of debugging auto-complete feature (aka code IntelliSense), and everything must be written manually. If you don't use any castings (like what you've know), the datatype will be assigned at run-time (the compiler will decide it). But it'll be better to cast objects when needed.

  Are there any impact affect performance ?

Performance-wise, it actually performs almost same as strong typed objects with a slight margin of difference, you'll hardly even notice it. So, don't think too much about it.

  And if there are any advise or feedback for my code,

Yes, you can simplify it :

public void ImportJSON(Stream request)
{
    using (var reader = new StreamReader(request))
    {

        var model = JsonConvert.DeserializeObject<dynamic>(reader.ReadToEnd());

        var stringBuilder = new StringBuilder(string.Empty);

        foreach (var item in model.Headers)
        {
            stringBuilder.Append($"{(string)item.Header};");
        }

        stringBuilder.AppendLine();

        foreach (var item in model.Values)
        {
            stringBuilder.AppendLine($"{(string)item.value};");
        }

        var path = HttpContext.Current.Server.MapPath($"~/App_Data/tmp/{Guid.NewGuid().ToString()}.csv");

        // you can use it directly in new StreamWriter(HttpContext.Current.Server.MapPath($"~/App_Data/tmp/{Guid.NewGuid().ToString()}.csv"))

        using (var writetext = new StreamWriter(path))
        {
            writetext.WriteLine(stringBuilder);
        }

    }
}


Reading from a serial port I'm receiving data from a serial port in C, using Serial Programming Guide for POSIX Operating Systems as a guide.

The data I receive should be always 10 bytes in length but I want to be sure that, if there is any error (more or less bytes received), reading will clear buffer before the next data arrive, so that there is always proper data in the buffer to be processed. I'm using select to monitor serial file descriptor and local socket. I figured out that I can clean serial buffer in case there was something left from previous transmission, when device is not sending for some period of time.

Question is: is this the right solution?

main.c:

loop_num=0;
si_processed=0;
while(TRUE) {
    /* copy fd_set for select */
    tmp_input=input;

    n = select(max_fd,&tmp_input,NULL,NULL,NULL/*&timeout*/);

    /* See if there was an error */
    if (n<0)
        perror("select failed");
    else {
        /* We have input */
        if (FD_ISSET(serial_fd, &input)) {
            if(!process_serial(serial_fd))
                loop_num++;
        }
        if (FD_ISSET(local_socket, &input))
            process_socket(local_socket);
    }
    if(loop_num>10) {
        /* clear buffer */
        si_processed=0;
        loop_num=0;
    }
    fflush(stdout);
    usleep(20000);
}

serial_port.c

char serial_buffer[256];

int process_serial(int serial_fd) {
    int bytes;
    int n,i;
    char tmp_buffer[32];

    ioctl(serial_fd, FIONREAD, &bytes);
    if(!bytes)
        return 0;

    n=read(serial_fd, tmp_buffer, sizeof(tmp_buffer));
    for(i=0;i<n;i++) {
        serial_buffer[si_processed+i]=tmp_buffer[i];
    }
    si_processed+=n;
    if(si_processed>=INPUT_BYTES_NUM/* defined as 10 */) {
        serial_buffer[si_processed]='\0';
        printf("read:%s\n",serial_buffer);
        si_processed=0;
        fflush(stdout);
    }
    return 1;
}

Some more info. I'm querying device every 5 seconds for data, and it should always respond with 10 bytes packets: so data should come fairly quickly into serial buffer, and then a few seconds of silence; sometimes however the device can send data on its own, I don't know when, but also as a 10 bytes packets.

I was doing some test with my program and minicom connected on the other side.

Until I was sending data like

1234567890

1234567890

program was reading what it supposed to read:

1234567890

Problem arises when I send on minicom:

12345678901234567890

Usually what was read was:

1234567890123456

so next, when I wrote on minicom proper data:

1234567890

program was reading

7890123456

and every next read was bad because of leftovers in buffer from previous read.

When I added clearing buffer after 1 or 2 seconds when nothing is read, then I'm sure any leftovers are cleared before next transmission.

I read about this VMIN settings but decided against because of this leftovers.

Also this data 1234567890 is just an example. In fact 10 bytes consist of:

Byte #1 - always some constant to mark begining of transmission like 0xA5
Byte #2 through #9 byte - data
Byte #10 - control sum from all previous bytes.

So after I have 10 bytes packet received I can verify if it has proper data or is somehow corrupted: so if one transmission fails, I should be ok, especially when I can clear the buffer before next data coming in.

The code you posted contains no error-recovery at all. It's a bit off-topic on this site to ask how to implement a new feature (error-recovery); but I'll try.
It's not clear what your communication protocol looks like. It might be:

A continuous stream of bytes, to be split into packets of 10
10-byte packets, with a measurable delay between packets, no reply expected
10-byte packets, after which silence until there is a reply, perhaps with a retry if there no reply

I'll assume it isn't 1. because that has little opportunity for error-recovery: if a byte were ever lost then you wouldn't know where the boundary is between "packets", if it's a continuous stream of bytes, unless you use 'framing' and 'escape sequences' in the data.
So I'll assume that it's 2. or 3.. In either case, what's important is:

There are 10 bytes received (probably received quickly with little or no delay between bytes)
There is then a delay (no bytes received) after those 10 bytes.

Setting Read Timeouts looks interesting. It may be your best algorithm: set VMIN to say that you want to receive no more or less than exactly 10 bytes when you read.
However that may have a problem:

However, the timeout only applies to the first character read, so if for some reason the driver misses one character inside the N byte packet then the read call could block forever waiting for additional input characters.

You don't say why you want error-recovery after losing a character: perhaps you sometimes get overruns in the driver, or bit parity errors from the serial port?
"Setting Input Parity Options" talks about handling the parity errors:

Replace/mark the byte with an error byte
If you do this then you can be more sure that you will get 10 bytes; but you can only do it if the protocol allows you to recognize an illegal byte value.

Or remove the error byte
If you do this then you must be able to recover from getting 9 bytes sometimes.

The data I receive should be always 10 bytes in length but I want to be sure that, if there is any error (more or less bytes received), reading will clear buffer before the next data arrive, so that there is always proper data in the buffer to be processed.

Reading should empty the buffer, if your sizeof(tmp_buffer) is bigger is the number of bytes queued in the driver. However:

It depends on the read mode (e.g. a read may block forever instead of clearing the buffer, if VMIN is set to non-zero)
If there are, somehow, very many received bytes enqueued in the driver, then you may have to read repeatedly until the driver is empty.
Immediately after you read, there may be more bytes in the driver: for example if the serial port is flow-controlled, reading from the driver allows the device to send again / send more.

Whether you can clear the buffer "before the next data arrive" is difficult to say: I don't know when the next data is supposed to arrive.
Depending on how you handle parity errors, maybe bytes are never lost. If bytes are sometimes lost then you may want to implement logic like:
read_10_bytes:
  read (waiting forever) until some bytes are returned
  if 10 bytes were read then return
  if less than 10 bytes were read, then:
    set an expiry timer
    loop doing the following
  read more bytes
  if you read 10 bytes before the timer expires, then clear the timer and return
  if the timer expires before you read 10 bytes, then discard the bad bytes and return

Instead of actually setting a timer, above, perhaps loop doing a blocking-read-with-timeout (which either reads the bytes, or expires).
As well as handling too few bytes (above), you could modify the above to check for receiving more than 10 bytes: after you receive 10 bytes, do another blocking-read-with-small-timeout to verify that there are no more bytes to receive. If there are extra bytes, then read them all before returning to the 'waiting-for-next-10-bytes' state (otherwise, these extra bytes will mess up your next 10-byte packet).

I think there's an obvious bug in the code. After you read 16 bytes, you completely clear your serial_buffer by zeroing si_processed, and you then think "success!" after each next 10 bytes you read.
Instead you should:

If you read too much data, don't discard the extra bytes: instead use memmove to move them to the beginning of the buffer (assuming they're the start of the next packet), and then read the subsequent bytes into the vacant space after them.

Something like:
// after reading and processing a 10-byte packet
if (si_processed > 10) // already have the start of the next packet
{
     // move start of next packet to start of buffer
     memmove(serial_buffer, serial_buffer+10, si_processed - 10);
     // not 0: remember how many start bytes we already have
     si_processed -= 10;
}

After you read any bytes, verify whether the start byte is your 0xA5 value, and discard the bytes if not.

Something like:
if (si_processed > 0) // have some bytes
{
    int i;
    for (i = 0; i < si_processed; ++i)
        if (serial_buffer[i] == 0xA5) // found start of packet
            break;
    if (i > 0)
    {
        // start of packet is not start of buffer
        // so discard bad bytes at the start of the buffer
        memmove(serial_buffer, serial_buffer+i, si_processed - i);
        si_processed -= i;
    }
}


A Note class which plays a note and stops it after specific period of time This code plays a note for a specific period of time using NAudio.dll 1.3.8.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Midi;
using System.Threading;

namespace SoundVision
{
    class Note
    {
        public Note(MidiOutWrapper midi_output,int number, int duration, int volume=127, int channel=0)
        {
            if (midi_output == null)
                return;
            //midi_output is not null because it's referenced in this constructor and therefore cannot be collected
            //Check for disposed is not to rely on disposed resources in Send function
            lock (midi_output)
            {
                if (!midi_output.disposed)
                    midi_output.Send(MidiMessage.StartNote(number, volume, channel).RawData);

                Timer t = new Timer(_ =>
                {
                    lock (midi_output)
                    {
                        if(!midi_output.disposed)
                            midi_output.Send(MidiMessage.StopNote(number, 0, channel).RawData);
                    }
                },
                null, duration, Timeout.Infinite);
            }

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Midi;

namespace SoundVision
{
    class MidiOutWrapper:MidiOut
    {
        public MidiOutWrapper(int device) : base(device)
        {
            disposed = false;
        }

        public bool disposed { get; private set; }
        //kill() is called only during locking of object, so in Note midi_output can't become disposed inside lock
        public void kill()
        {
            disposed = true;
            Reset();
            Close();
        }
    }
}

Why is this a class? It contains no data and has no methods; the only thing it has is a constructor. This would be more suitable as a method.

Let's step back and look at the desired behaviour:

  This code plays a note for a specific period of time.

Here is the simplest way I can think of to achieve this:

public static async Task PlayNoteAsync(
    MidiOut midiOut,
    int note,
    TimeSpan duration,
    int volume = 127,
    int channel = 0)
{
    midiOut.Send(MidiMessage.StartNote(note, volume, channel).RawData);
    await Task.Delay(duration).ConfigureAwait(false);
    midiOut.Send(MidiMessage.StopNote(note, volume, channel).RawData);
}

We just:

Start playing the note
Wait the desired amount of time
Stop playing the note

Much of the original code is concerned with whether or not the MidiOut object has been disposed. I don't believe it should be the responsibility of this method to check if the MidiOut has been disposed; I would suggest instead to restructure the client code such that MidiOut is not disposed until the notes have stopped playing (or play has been cancelled, see below). Unfortunately, it's hard to be more specific about how to do this without an example of the client code. I would also recommend removing the MidiOutWrapper class.

You might want to support cancellation with a CancellationToken:

public static async Task PlayNoteAsync(
    MidiOut midiOut,
    int note,
    TimeSpan duration,
    int volume = 127,
    int channel = 0,
    CancellationToken cancellationToken = default(CancellationToken))
{
    // Consider using cancellationToken.ThrowIfCancellationRequested(); here.
    midiOut.Send(MidiMessage.StartNote(note, volume, channel).RawData);

    try
    {
        // Task.Delay will throw a TaskCanceledException if the
        // cancellationToken is signalled before the wait period is over.
        await Task.Delay(duration, cancellationToken).ConfigureAwait(false);
    }
    finally
    {
        midiOut.Send(MidiMessage.StopNote(note, volume, channel).RawData);
    }
}

Finally, I think this is a suitable candidate for being an extension method.


Testing class that transforms JSON into a spreadsheet I am creating unit tests but the class uses objects that have long JSON. What can I do to improve the readability of this?

In tests, only insert those JSON really needed for the test. The class I tested is responsible in turn that JSON in a modified spreadsheet (xlsx) and it seems difficult to maintain the code.

@Test
public void testBuildSheet_validSheet_NoMedia() throws Exception {
    BasicDBObject specPlanilha = (BasicDBObject) JSON.parse("{\"spec_veiculo\" : \"BuscaDescontos\" , \"spec_canal\" : \"Homepage\" , \"spec_formato\" : \"SuperBanner\" , \"spec_linha-criativa\" :  null  , " +
            "\"spec_tamanho\" : \"728x90\" , \"spec_extensao\" : \"jpg/png\" , \"peca_peso\" : \"50kb\" , \"imagem_peso\" : \"50kb\" , " +
            "\"peca_flash\" : \"4 até 10\" , \"peca_clicktag\" : \"on (release) {\\n  getURL(_root.clickTAG, '_blank');\\n}\" , " +
            "\"peca_framerate\" : \"24fps\" , \"peca_tempo\" : \"30s\" , \"spec_observacoes\" :  null  , " +
            "\"peca_nome\" : \"Whirlpool_LinhaBranca_BuscaDescontos_Homepage_SuperBanner_-.jpg\" , \"extras\" : " +
            "{ \"linha\" : \"10\" , \"Rich Media\" : \"Não\" , \"Link Especificação\" : \"http://portal.agenciaclick.com.br/midiaSP/Midia/Lists/Tabela%20de%20Especificao%20e%20Formato%20de%20Peas/DispForm.aspx?ID=3405&Source=http%3A%2F%2Fportal%2Eagenciaclick%2Ecom%2Ebr%2FmidiaSP%2FMidia%2FLists%2FTabela%2520de%2520Especificao%2520e%2520Formato%2520de%2520Peas%2FSites%2Easpx\" ," +
            " \"Data Entrega Mídia\" :  null  , \"Data Disparo/Subida\" :  null }}");
    List<BasicDBObject> listSpec = new ArrayList<>();
    listSpec.add(specPlanilha);
    BasicDBObject specFields = (BasicDBObject) JSON.parse("{\"peca_nome\": \"Whirlpool_LinhaBranca_BuscaDescontos_Homepage_SuperBanner_-.jpg\",\n" +
            "      \"extras\": {\n" +
            "        \"linha\": \"10\",\n" +
            "        \"Rich Media\": \"Não\",\n" +
            "        \"Link Especificação\": \"http://portal.agenciaclick.com.br/midiaSP/Midia/Lists/Tabela%20de%20Especificao%20e%20Formato%20de%20Peas/DispForm.aspx?ID=3405&Source=http%3A%2F%2Fportal%2Eagenciaclick%2Ecom%2Ebr%2FmidiaSP%2FMidia%2FLists%2FTabela%2520de%2520Especificao%2520e%2520Formato%2520de%2520Peas%2FSites%2Easpx\",\n" +
            "        \"Data Entrega Mídia\": null,\n" +
            "        \"Data Disparo/Subida\": null\n" +
            "      }}");

    ValidacaoResultado myValidation = new ValidacaoResultado().setId("123")
            .setResultadoConsolidado("NO_MEDIA")
            .setResultado(new BasicDBObject())
            .setSpec(specFields);
    oknok.validacao.entities.Planilha planilha = new Planilha()
            .setPath(PlanilhaWorkbook.class.getClass().getResource("/planilhaWorkbook/T001.xlsx").getPath())
            .setNomeHash("noMediaTest.xlsx")
            .setSpec(listSpec);

    List<ValidacaoResultado> myList = new ArrayList<>();
    myList.add(myValidation);

    File actual = planilhaWorkbook.buildSheet(myList, planilha);
    SoftAssertions soft = new SoftAssertions();

    soft.assertThat(actual.getName()).isEqualTo(planilha.getNomeHash());
    soft.assertAll();
}

Ideally,
the source data and the expected result of the function under test are both visible inside the test case.
That readers can see clearly what is being tested and what the function does.

When the source and result data are relatively big,
it's better to not include in the test case,
but to keep in files in test resources.
This is usually not great, as readers lose visibility of what's really being tested,
but if large data pollutes the test case making it unreadable,
that's a worse option.

In your case, only the source data (json) is in the test case,
the result (xlsx) is outside.
In this case,
since the JSON is pretty unreadable in the code,
I recommend to move it to a resource file, like you did with the xlsx.
I think that's the most maintainable option for you.


Accessor functions in elisp I'm writing some simple emacs tools for visual studio solutions.

I've got a function sln-process-csproj-file.  This function takes the path to a project, and returns a tuple that's just a data model of the innards of the project.

Right now the return value on the last line of that function is `(,project-name ,project-path ,project-files).

I have written three getter functions to use with the list:

(defun sln-project-name (project)
  (nth 0 project))

(defun sln-project-path (project)
  (nth 1 project))

(defun sln-project-files (project)
  (nth 2 project))

Does this getter and setter boilerplate code match best practices? Is there a shorter way to write it?

Yes, it can be shortened by using defstruct. An example from the docs:

      (cl-defstruct person name age sex)
      (setq dave (make-person :name "Dave" :sex 'male))
           ⇒ [cl-struct-person "Dave" nil male]
      (setq other (copy-person dave))
           ⇒ [cl-struct-person "Dave" nil male]
      (eq dave other)
           ⇒ nil
      (eq (person-name dave) (person-name other))
           ⇒ t
      (person-p dave)
           ⇒ t
      (person-p [1 2 3 4])
           ⇒ nil
      (person-p "Bogus")
           ⇒ nil
      (person-p '[cl-struct-person counterfeit person object])
           ⇒ t

Alternatively, if you want something more heavy weight, there is a CLOS-like object system.


Simple for loop to calculate headers size based on a specific ratio How can I improve the following for loop (wannabe function) to create harmonic sizes for headers based on a specific ratio?

var base = 16;
var goldenRatio = 1.618;
var list = "";
for(var i=6; i>0; i--){
    list = "\nh" + i + " { font-size: " + base + "px; }" + list;
    base *= Math.round(base*goldenRatio);
}
console.log(list)

This is what your code produces and I'm wondering if this really what you want:

"
h1 { font-size: 1.0957612059345655e+45px; }
h2 { font-size: 2.602367950332107e+22px; }
h3 { font-size: 126822144384px; }
h4 { font-size: 279968px; }
h5 { font-size: 416px; }
h6 { font-size: 16px; }"

The numbers are huge. Looking at this page, it seems you should not have base inside the multiplication here:

base *= Math.round(base*goldenRatio);

Also, by rounding at this step, you lose precision. It would be better to round right before you put the value in the string. Like this:

var base = 16;
var list = "";
for (var i = 6; i > 0; i--) {
    list = "\nh" + i + " { font-size: " + Math.round(base) + "px; }" + list;
    base *= goldenRatio;
}

I'm also wondering if you really want the \n at the start of the resulting string.
It would seem more natural to put it at the end of each line, like this:

list = "h" + i + " { font-size: " + Math.round(base) + "px; }\n" + list;

Notice also that I added more spaces around the operators in the for.
There is no real standard for this in JavaScript,
but this is a practice I borrow from other languages where it is a standard,
for improved readability. Compare these two versions, I hope you'll agree that this is an improvement:

for(var i=6; i>0; i--){

for (var i = 6; i > 0; i--) {


Get IP info from a FreeBSD machine I'm try to get the public IP address from my FreeBSD machine and use it for the rest of my code.

Is this implementation good? Can it be optimized more? Can you see some gaps here? Something that maybe sometimes will throw an error?

GET.CPP

    char g_szPublicIP[16] = "0";
    char g_szInternalIP[16] = "0";

bool GetIPInfo()
{
    struct ifaddrs* ifaddrp = NULL;

    if (0 != getifaddrs(&ifaddrp))
    {
        return false;
    }

    for( struct ifaddrs* ifap = ifaddrp ; NULL != ifap ; ifap = ifap->ifa_next )
    {
        struct sockaddr_in * sai = (struct sockaddr_in *) ifap->ifa_addr;

        if (!ifap->ifa_netmask ||  // ignore if no netmask
                sai->sin_addr.s_addr == 0 || // ignore if address is 0.0.0.0
                sai->sin_addr.s_addr == 16777343) // ignore if address is 127.0.0.1
        {
            continue;
        }

        char * netip = inet_ntoa(sai->sin_addr);

        if (!strncmp(netip, "10.", 3))
        {
            strlcpy(g_szInternalIP, netip, sizeof(g_szInternalIP));
            fprintf(stderr, "INTERNAL_IP: %s interface %s\n", netip, ifap->ifa_name);
        }
        else if (g_szPublicIP[0] == '0')
        {
            strlcpy(g_szPublicIP, netip, sizeof(g_szPublicIP));
            fprintf(stderr, "PUBLIC_IP: %s interface %s\n", netip, ifap->ifa_name);
        }
    }

    freeifaddrs( ifaddrp );

    if (g_szPublicIP[0] != '0')
    {
        return true;
    }
    else
    {
        return false;
    }
}

    int main()
    {
        if (!GetIPInfo()) // Check is getIpInfo
        {
            fprintf(stderr, "Can not get public ip adress (1)-GetIpInfo\n");
            exit(1);
        }

        if(g_szPublicIP[0] == '0') // Check is
        {
            fprintf(stderr, "Can not get public ip address (2)-EndGetIpInfo\n");
            exit(1);
        }
    }

main() doesn't need to be indented out as such, same with the global arrays.
main() should have a void parameter since it's not taking command-line arguments.
You're using "Yoda conditions" in some places:

if (0 != getifaddrs(&ifaddrp))

NULL != ifap

and rest elsewhere in most places. Stay consistent with one of these types.
It looks like netip could be const since it's not being modified and is only used as a const parameter in strlcpy().
You can simplify this:

if (g_szPublicIP[0] != '0')
{
    return true;
}
else
{
    return false;
}

to this:

return g_szPublicIP[0] != '0';

It'll automatically return the outcome of the function call.

However, if you still prefer to see true and false, you can use a ternary:

return (g_szPublicIP[0] != '0') ? true : false;


Regex in Hive QL (RLIKE) I'm wondering how/if I can improve the regex I'm using in a query. I have a set of identifiers for certain user groups. They can be in two main format:

X123 or XY12, and
Any two letter combo

A user can belong to multiple groups, in which case different groups are separated by a pound symbol (#). Here's an example:

groups     user     age
X124       john     23
XY22#AB    mike     33
AB         peter    21
X122#XY01  francis  43

I want to count rows in which at least one group in second format appears, i.e. where a user is not exclusively a member of groups in first the format. I'm currently doing it like this:

select
  count(*)
from
  users
where
  groups not rlike '^(X[Y1-9][0-9]{2,2})(#X[Y1-9][0-9]{2,2})*$'

Is this bad performance-wise? And how should I approach fixing it?

Looks good to me.

Your specification, "at least one group in second format appears", is stated in the positive, yet your not rlike is stated in the negative. You might consider phrasing it as where groups rlike '(^|#)[A-Z][A-Z](#|$)'.

You asked about performance. These queries will certainly have to read all rows, which costs more CPU cycles than evaluating the regexes. You might consider adding derived boolean column(s) that indicate whether "format1" and "format2" groups are present. Then you could index on such a column.


Soundcloud to CSV File This program connects to Soundcloud and turns the supplied username into a CSV file with the user's like list. The code accomplishes this although it looks rather messy and was wondering what I could change to improve it.

import soundcloud
import urllib.request
import json
import requests

client = soundcloud.Client(client_id="********************************")

def get_username():
    """
    Asks user for their Soundcloud username.
    """
    username = input("Please enter your Soundcloud username: ")
    user_id = (valid_username(username))
    print(user_id)

def valid_username(username):
    """
    Checks if supplied username is valid.
    """
    global user
    try:
        user = client.get("/resolve", url="http://soundcloud.com/{}/".format(username))
        user_info(user.id)
    except requests.HTTPError:  # Runs if account cannot be found.
        print("The username you entered is invalid, please try again")
        get_username()

def user_info(user_id):
    """
    Retrieves the users information from their user ID
    and prints the number of tracks they have liked.
    """
    global number_of_user_likes
    retrieve = urllib.request.urlopen("https://api.soundcloud.com/users/{}.json?consumer_key="
                                      "********************************".format(user_id)).read()
    decode_user_info = json.loads(retrieve.decode())
    number_of_user_likes = decode_user_info['public_favorites_count']
    username = decode_user_info['username']
    print("You have liked a total of {} tracks".format(number_of_user_likes))
    save_likes(username)

def save_likes(username):
    """
    Creates a CSV file with headers and then saves the users likes to the CSV file.
    """
    csv_file = open("{}s like list.csv".format(username), 'w', encoding='UTF-8')
    csv_file.write("Track Title, Track URL\n")  # Writes headers to CSV file.
    offset_number = 0
    complete = False
    while number_of_user_likes > 0 and complete is False:
        if offset_number < number_of_user_likes:
            try:
                track_fetch = urllib.request.urlopen(
                    "http://api.soundcloud.com/users/{}/favorites.json?client_id="
                    "********************************&offset={}&limit1".format(user.id, offset_number)).read()
                track_data = json.loads(track_fetch.decode())
                if "," in track_data[0]["title"]:
                    track_title = track_data[0]["title"].replace(",",
                                                                 "")  # Removes commas as causes issues with .csv files
                else:
                    track_title = track_data[0]["title"]
                csv_file.write("{},{}\n".format(track_title, track_data[0]["permalink_url"]))
                offset_number += 1
                print("{} of {} ({}%)".format(offset_number, number_of_user_likes,
                                              round(float(100 / number_of_user_likes * offset_number), 2)))
            except IndexError:
                print("There is an issue with Soundcloud, please try again")
            except requests.HTTPError:
                print("There is an issue with Soundcloud, please try again")
            except requests.ConnectionError:
                print("Check your internet connection")
        else:
            complete = True
            finished()

def finished():
    """
    Runs after the users like list has finished being saved.
    """
    print("Finished")

get_username()

Use of functions

Functions can return values.  You should do that instead of passing back results indirectly via global variables.

In get_username(), user_id = (valid_username(username)) is nonsense, since the valid_username() function never returns anything.

Worse, you are misusing functions as if they were goto labels.  get_username() and valid_username() are mutually recursive, which is inappropriate.  Furthermore, get_username() triggers all of the activity in the program, which is much more than getting the username as the function name would suggest.

Rearranging everything…

def prompt_username():
    return input("Please enter your Soundcloud username: ")

def get_account(username):
    try:
        return client.get("/resolve", url="http://soundcloud.com/{}/".format(username))
    except requests.HTTPError:
        raise ValueError("Invalid username")

def prompt_account():
    while True:
        try:
            return get_account(prompt_username())
        except ValueError:
            print("The username you entered is invalid.  Please try again")

def get_favorites(account):
    req = urllib.request.urlopen("https://api.soundcloud.com/users/{}.json?consumer_key={}",
                                 account.id, consumer_key)
    …
    return decoded_user_info['username']

def save_favorites(account, favorites):
    …

Now you can write this, which does convey what the program does, unlike your get_username() "function" which was really just a goto label:

account = prompt_account()
save_favorites(account, get_favorites(account))


Change text and styling of a form control when a slider value changes Having a hard time to achieve what I'm looking for. I was thinking of using arrays but don't know where to start. Code below is what I want to shorten to get rid of multiple if statement using jQuery.

$("input#communication").on("slide", function(slideEvt) {
    if(slideEvt.value == 1) {
        $('#slider-val1').css('color', '#D0011B');
        $('.slider-label').not('#slider-val1').css('color', '#ccc');
        $('.slider-handle').css({
            'border': '5px solid #fff',
            'box-shadow': '0 0 0 2px #D0011B'
         })
        $("#desc").text('Amir is a terrible communicator.');
    }

    if(slideEvt.value == 2) {
        $('#slider-val2').css('color', '#D0011B');
        $('.slider-label').not('#slider-val2').css('color', '#ccc');
        $("#desc").text('Amir struggles, needs a lot of help to improve communication skills.');
    }

    if(slideEvt.value == 3) {
        $('.slider-handle').css({
            'border': '5px solid #fff',
            'box-shadow': '0 0 0 2px #D0011B'
        })
        $('.slider-handle').css('background', '#D0011B');
        $('.slider-selection').css('background', '#D0011B');
        $('#slider-val3').css('color', '#D0011B');
        $('.slider-label').not('#slider-val3').css('color', '#ccc');
        $("#desc").text('Amir needs some help to improve communication skills.');
    }

    if(slideEvt.value == 4) {
        $('.slider-handle').css('background', '#F47621');
        $('.slider-selection').css('background', '#F47621');
        $('#slider-val4').css('color', '#F47621');
        $('.slider-handle').css({
            'border': '5px solid #fff',
            'box-shadow': '0 0 0 2px #F47621'
        })
        $('.slider-label').not('#slider-val4').css('color', '#ccc');
        $("#desc").text('Amir has below average communication skills.');
    }

    if(slideEvt.value == 5) {
        $('#slider-val5').css('color', '#F47621');
        $('.slider-label').not('#slider-val5').css('color', '#ccc');
        $("#desc").text('Amir has adequate communications skills.');
    }
});

The code above use to change the $('#desc') text and CSS every time the slider is slide. Now, I'm looking for a good way on how to shorten thisif else statements.

You are duplicating a lot of code here. You said you wanted an array, so make an array containing all the values that change and then use the slideEvt.value to recall the values from the array at the correct index..

Something like this maybe.. no if() statements required (at least not for the slideEvt.value):

$("input#communication").on("slide", function(slideEvt) {
    var slideEvtVals = [
      {color: '#D0011B', css: {'border': '5px solid #fff', 'box-shadow': '0 0 0 2px #D0011B'}, text: 'Amir is a terrible communicator.'}
      {color: '#D0011B', text: 'Amir struggles, needs a lot of help to improve communication skills.'}
      {color: '#D0011B', css: {'border': '5px solid #fff', 'box-shadow': '0 0 0 2px #D0011B'}, text: 'Amir needs some help to improve communication skills.', handleBG: '#D0011B', selBg: '#D0011B'}
      {color: '#F47621', css: {'border': '5px solid #fff', 'box-shadow': '0 0 0 2px #F47621'}, text: 'Amir has below average communication skills.', handleBG: '#F47621', selBg: '#F47621'}
      {color: '#F47621', text: 'Amir has adequate communications skills.'}
    ];

    var index = slideEvt.value-1;
    $('#slider-val'+slideEvt.value).css('color', slideEvtVals[index].color);
    $('.slider-label').not('#slider-val'+slideEvt.value).css('color', '#ccc');
    if(slideEvtVals[index].css) $('.slider-handle').css(slideEvtVals[index].css);
    $("#desc").text(slideEvtVals[index].text);
    $("#desc").text(slideEvtVals[index].text);
    if(slideEvtVals[index].handleBG) $('.slider-handle').css('background', slideEvtVals[index].handleBG);
    if(slideEvtVals[index].selBg) $('.slider-selection').css('background', slideEvtVals[index].selBg);
});