texts:
I'll be teaching Computer Architecture at the undergraduate level this fall and want to make sure that my example Verilog code follows best practices. I welcome any suggestions, however minor, for improving this code, which runs at EDA Playground.
Our textbook is Computer Organization and Design by Hennessy and Patterson. It doesn't say much about Verilog, and I will only be taking a small piece of code from an appendix, so there is no style to be consistent with.
Testbench
module test;
  reg   a;
  reg   b;
  reg   c_in;
  wire  sum;
  wire  c_out;

  ADDER adder(a, b, c_in, sum, c_out);

  initial begin
    // Dump waves
    $dumpfile("dump.vcd");
    $dumpvars(1);

    for (int i = 0; i < 8; i++) begin
      {a, b, c_in} = i;
      display;
    end
  end

  task display;
    #1;
    $display("%b + %b + %b = %b%b", a, b, c_in, c_out, sum);
  endtask

endmodule

Design
module ADDER (a, b, c_in, sum, c_out);
  input     a;
  input     b;
  input     c_in;
  output    sum;
  output    c_out;

  assign c_out = (a & b) | (a & c_in) | (b & c_in);
  assign sum = a ^ b ^ c_in;
endmodule


texts:
I just wrote this and don't like how bulky it is, also given the fact I will have to add at least another if statement.

I was going to switch it to a case statement but wanted to check if there were even better ways to reduce the clutter.

string emailLetterPath = Server.MapPath("~/emails/rejected.htm");

if (jobApplicantAndJob.Jobs.Title == "Store Sales Manager" || jobApplicantAndJob.Jobs.Title == "Sales Representative")
{
     emailLetterPath = Server.MapPath("~/emails/TC1RejectedP3.htm");
}

if (jobApplicantAndJob.Jobs.Title == "Outside Sales Professional")
{
     emailLetterPath = Server.MapPath("~/emails/TC2RejectedP3.htm");
}

The default option should be the rejected.htm.


texts: Implementing a new event in an old mootools version

texts:
I'm emulating a little bit the .on() from jQuery in an old Mootools version. One of the project requirements is that Mootools can't (shouldn't) be upgraded (using version 1.2.x).

Basically I'm checking the element itself and its two closest ancestors (like .parents() in jQuery).

My working code is:

Element.implement({
            addLiveEvent: function(event, selector, fn){
                this.addEvent(event, function(e){
                    var t = $(e.target);
                    if (!t.match(selector)) {
                        t = $(e.target.parentNode);
                        if(!t.match(selector)) {
                            t = $(e.target.parentNode.parentNode);
                            if(!t.match(selector)) {return false;}
                        }
                    }
                        fn.apply(t, [e]);
                }.bindWithEvent(this, selector, fn));
            }
        });

I know those if() and the way I'm setting the variable t are not a good practice, however I'm not sure how to improve it.


texts: Load title from database based on member country

texts:
As tim suggested, some changes to the database was necessary. I have posed an improved version of this question at Get title from database based on member country.

I have the following database:

Each member may have multiple countries (1:n) mapped in table country2memb. It's even possible that one member gets the same country multiple times (for example, Bernd got US twice).
Further, each member may have  multiple titles (1:n) mapped in table title2memb. Each entry idRank has a name which can be found in title.
I want to get the first N members that have at least once the country "US" in table country2memb and I want to display all their titles.
Here is working code, using two JOINS and two where statements for N=2:
<?php

$db= new mysqli("localhost","root","","example");

$sql      ="SELECT DISTINCT m.name, m.id FROM member m
INNER JOIN country2memb c ON m.id = c.idMember AND c.country='US' LIMIT 2";

$result   = $db->query($sql);

while($zeile = $result->fetch_assoc()){
  $id = $zeile['id'];
  echo $zeile['name'].": ";

  $sub_sql = "SELECT t.name FROM title t INNER JOIN title2memb tm ON
  t.id = tm.idRank AND tm.idMember='$id'";
  $sub_result   = $db->query($sub_sql);
  while($rank = $sub_result->fetch_assoc())
  {
    echo $rank['name']." ";
  }

  echo "<br>";
}

?>

And as a result I get (I had to use the DISTINCT keyword, otherwise I would get Bernd twice):

Bernd: Bee
Tom: Bear Dog

Is it really necessary to have 2 nested while clauses here?


texts:
I am trying to encrypt/decrypt file using source code directly. The issue is how to properly do it after reading the file.

int crypto_aead_encrypt(
    unsigned char *c, unsigned long long *clen,
    const unsigned char *m, unsigned long long mlen,
    const unsigned char *ad, unsigned long long adlen,
    const unsigned char *nsec,
    const unsigned char *npub,
    const unsigned char *k
)

Working code: (plaintext is char *)

for (start = 0; start < fileLength; start += 32)
    {
        int end = (start + 32);
        end = end > fileLength ? fileLength : end;

        strncpy(msg, plaintext + start, end - start);

        // encrypt
        crypto_aead_encrypt(ct, &clen, msg, mlen, ad, adlen, NULL, nonce, key);

        // decryption

        crypto_aead_decrypt(msg2, &mlen2, NULL, ct, clen, ad, adlen, nonce, key);
}

This is the function, and the max limit of the message m is 32 bits, which would make encrypting/decrypt very long for large files (ex. 1GB). Is there a way to perform the encrypting as fast as if it were from the library. Neglecting the code above, ex. how does OpenSSL do it when -in is provided?

The way I have it is to read the file, save it to an char * and then take 32 bits and enc each one. So I am wondering if there is a proper more correct way to do it.

Edit: reference implementation like ascon or photon-beetle


texts:
I created a tool to examine Python 3 source code. It measures the density of program. More info in docstring (to not reinvent the wheel).

What could be done to increase its usability? Any edge cases that I didn't think of?

#!/usr/bin/env python3

'''
Module counts how dense is Python source code in
terms of lexical entities per LoC.
'''

import ast

def traverse(node, line_nos):
    '''
    go through the AST and count lines
    '''
    children = list(ast.iter_child_nodes(node))

    try:
        current_line = node.lineno
    except AttributeError:
        current_line = 0

    count = 1
    line_nos.update([current_line])

    if len(children) == 0:
        return 1

    for child in ast.iter_child_nodes(node):
        count += traverse(child, line_nos)

    return count

def count_code_entities(source):
    '''
    parse the source&count
    '''
    line_nos = set()
    tree = ast.parse(source)

    # len - 1 to compensate for default value 0
    # which cannot hold any code
    return traverse(tree, line_nos), len(line_nos) - 1

def main():
    '''
    parsin&stuff
    '''
    from argparse import ArgumentParser, FileType
    parser = ArgumentParser()
    parser.add_argument('infile',
                        help='source file to analyze',
                        type=FileType(),
                        default='-',
                        nargs='?',)

    args = parser.parse_args()

    with args.infile as file:
        source = file.read()
        name = file.name

    count, number = count_code_entities(source)
    print(name, ': ', round(count/number, 4), 'entities/line of code')

if __name__ == '__main__':
    main()


texts: Simple code for calculating damage increase

texts:
In my little game project, I have the following piece of code, in the static class DamageHelper, that takes a Spell, and returns it's damage in the Entity:

public static float DamageIncrease(SpellData attack, Entity caster)
{
    //Elemental damage is more increased by wisdom attribute
    //Impact damage is more increased by dominance attribute
    //summon level is increased by control attribute

    float bonus = 0f;
    switch (attack.element)
    {
        case Element.Fire:
        case Element.Earth:
        case Element.Water:
        case Element.Wind:
            bonus = caster.wisdom * 0.3f + caster.dominance * 0.1f + caster.control * 0.1f;
            break;
        case Element.Impact:
            bonus = caster.wisdom * 0.1f + caster.dominance * 0.3f + caster.control * 0.1f;
            break;
        default:
            bonus = caster.wisdom * 0.1f + caster.dominance * 0.1f + caster.control * 0.3f;
            break;
    }

    return attack.damage + bonus;
}

The function above is called by the this RealDamage function, that may also be improved:

public static float RealDamage(SpellData attack, Entity target, Entity caster)
    {
        float max_variation = attack.damage_variation / 2f;
        float min_variation = max_variation - attack.damage_variation;
        float resist_percent = 0f;
        float dmg = DamageIncrease(attack, caster) + Random.Range(min_variation, max_variation);
        switch (attack.element)
        {
            case (Element.Fire):
                resist_percent = target.GetFireResistance();
                break;
            case (Element.Earth):
                resist_percent = target.GetEarthResistance();
                break;
            case (Element.Water):
                resist_percent = target.GetWaterResistance();
                break;
            case (Element.Wind):
                resist_percent = target.GetWindResistance();
                break;
            case (Element.Impact):
                resist_percent = target.GetPhysicalResistance();
                break;
        }

        dmg -= (dmg * resist_percent / 100f);

        if (dmg < 1f)
            dmg = 0f;

        return dmg;
    }

and this one is called when player casts a spell:

float damage = DamageHelper.RealDamage(data, e, spellCaster);
dmg.GetComponent<DamageText>().MakeTooltip(data.element, damage, e.transform.position);
e.TakeDamage(damage);

It's pretty simple, but I would like to know if there are any ways it can be improved. Also, I will probably add more formulas, since I have to get the bonus from the Entity equipment. In this case, where should I put these?


texts: Check whether an array can be the result of merging two smaller arrays, maintaining order

texts:
I'm prepping for a tech interview coming up and trying to have a better understanding of what I should look out for in writing code. Also, feel free to correct the terminology that I use as I want to be able to talk about my code clearly and succinctly.

One of the specifications for the tech interview process is that I use idiomatic JavaScript, according to the recruiter. I'm not familiar with that term and would appreciate any feedback on how to best write to that standard. Is there a specific standard that I should adhere to? Is that related to proper naming conventions?

Is there a better way for me to optimize time and space in my code?

When I assign values to variables within loops, are there rules that I should be aware of for when I shouldn't? For example, the current element being iterated over assigned to currentH1 variable, in my mind, makes it more readable in understanding what's happening as opposed to half1[h1Index], and I reuse it more than once. Plus, I believe this might make it more idiomatic but I'm not sure? Am I losing out on space complexity in any way? Or is there something that I may not be aware of by checking current against undefined instead of checking the current index against the size of the array?

When I assign values to variables outside of loops but within the function, are there space complexities that I should pay attention to or does garbage collection take care of this? Is this \$O(1)\$ space complexity as I'm just keeping track of the indices? Feel free to breakdown space complexity as I truly do want to have a more solid understanding of memory management.

I believe I've accounted for the edge cases that I can think of, but are there more that I should be aware of?

I placed the if condition for checking lengths at the top even before the index definitions because I figured that if they aren't even the same size, why bother with doing anything else. Is that weird?

function isMergedArray(half1, half2, mergedArray) {
  if ((half1.length + half2.length) != mergedArray.length ) {
    return false;
  }

  let h1Index = half1.length - 1;
  let h2Index = half2.length - 1;
  let maIndex = mergedArray.length - 1;

  while (maIndex >= 0) {
    const currentH1 = half1[h1Index];
    const currentH2 = half2[h2Index];
    const currentMa = mergedArray[maIndex];

    if (currentH1 != undefined && currentH1 === currentMa) {
      h1Index--;
    } else if (currentH2 != undefined && currentH2 === currentMa) {
      h2Index--;
    } else {
      return false;
    }

    maIndex--;
  }

  return true;
}


texts: Writing a particular column of a two-dimension array to a worksheet

texts:
I had some great feedback on my code previously here and I was hoping that I could get some further help with writing a column of the array to the worksheet.

I have an example here where I write one column of my array to the worksheet with a loop, but I'm wondering if there wouldn't be a more efficient way to do this:

Option Explicit
Option Base 1

Public Sub arrayMatch()

    Dim firstArray As Variant
    With ThisWorkbook.Worksheets(1)
        firstArray = .Range("A1", .Range("A1").End(xlDown).End(xlToRight))
    End With
    ReDim Preserve firstArray(UBound(firstArray, 1), UBound(firstArray, 2) + 1)

    Dim secondArray As Variant
    With ThisWorkbook.Worksheets(2)
        secondArray = .Range("A1", .Range("A1").End(xlDown).End(xlToRight))
    End With

    Dim rowFirstArray As Long
    Dim rowSecondArray As Long
    For rowFirstArray = 1 To UBound(firstArray,1)
        For rowSecondArray = 1 To UBound(secondArray,1)
            If firstArray(rowFirstArray, 3) = secondArray(rowSecondArray, 1) Then
                firstArray(rowFirstArray, 4) = secondArray(rowSecondArray, 2)
                Exit For
            End If
        Next rowSecondArray
    Next rowFirstArray
    Erase secondArray

    For rowFirstArray = 1 To UBound(firstArray, 1)
        ThisWorkbook.Worksheets(1).Cells(rowFirstArray, 4).Value = firstArray(rowFirstArray, 4)
    Next rowFirstArray
    Erase firstArray

End Sub


texts: Predicting words based on swiping a keyboard

texts:
I thought this question was particularly interesting DailyProgrammer 284: Wandering Fingers so thought I'd have a pop at it myself. See the other question for the nitty gritty but the brief problem statement is:

  You'll be given a string of characters representing the letters the user has dragged their finger over.

  For example, if the user wants "rest", the string of input characters might be "resdft" or "resert".

  Input

  Given the following input strings, find all possible output words 5 characters or longer.

  qwertyuytresdftyuioknn
  gijakjthoijerjidsdfnokg

  Output

  Your program should find all possible words (5+ characters) that can be derived from the strings supplied.

  Use http://norvig.com/ngrams/enable1.txt as your search dictionary.

  The order of the output words doesn't matter.

  queen question
  gaeing garring gathering gating geeing gieing going goring

I've made the assumption that this is the English alphabet (i.e. [a-z]) which is pretty normal for a qwerty keyboard.

I created a simple lookup class:

public class AutocompleteCache
{
    private readonly IList<string>[] cache = new IList<string>[26*26];

    public AutocompleteCache(IEnumerable<string> wordList)
    {
        if (wordList == null)
        {
            throw new ArgumentNullException(nameof(wordList));
        }
        foreach (var word in wordList.Where(w => w.Length >= 5))
        {
            var index = CalculateIndex(word);
            var cachedWords = cache[index];
            if (cachedWords == null)
            {
                cache[index] = new List<string>();
            }
            cache[index].Add(word);
        }
    }

    private static int CalculateIndex(string word)
    {
        Debug.Assert(!string.IsNullOrEmpty(word));
        return (word[0] - 97)*26 + (word[word.Length - 1] - 97);
    }

    public IEnumerable<string> SuggestWords(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return Enumerable.Empty<string>();
        }
        var candidates = (cache[CalculateIndex(input)] ?? Enumerable.Empty<string>());
        return candidates.Where(candidate => CheckWordIsValidForInput(candidate, input));
    }

    private bool CheckWordIsValidForInput(string word, string input)
    {
        int currentPosition = 0;
        foreach (var c in word)
        {
            currentPosition = input.IndexOf(c, currentPosition);
            if (currentPosition == -1)
            {
                return false;
            }
        }
        return true;
    }
}

The responsibility of this class is to take a dictionary of words and sort it into an array of lists of words. The index of the array is determined by a simple calculation of the first and last letters of the word (CalculateIndex). Which gives us an O(1) lookup for the list of candidate words. This is the same complexity as using a dictionary would have but has smaller constant terms than using the dictionary. The overall algorithm is  O(n*m) with O(n) startup cost where n is the number of words and m is the length of the input string. The memory requirement is O(k^2) where k is the alphabet length (hard coded to 26 here).

I benchmarked this against the OP's solution and Jonbot's dictionary and found that for input 1 over 10000 iterations it's approximately twice as fast as Jobbot's and about 200 times faster than OPs solution. For words with a larger list of candidates, i.e. more common first and last letters, it ends up being only very slightly faster ~5% that the dictionary approach but still an order of magnitude faster than the OP.

Usage of the code:

 var words = File.ReadAllLines(@"C:\some\path\to\dictionary.txt");
 var autoCompleteCache = new AutocompleteCache(words);
 var results = autoCompleteCache.SuggestWords("quen");
 Console.WriteLine(string.Join(", ", results)); // queen

Looking for any and all comments.


texts: Classes to help transform "How hard is it to …?" questions into replies like "It's really hard to …"

texts:
I've written a Twitter bot, @answering_yelp, which responds to another Twitter bot, @hard_to_yelp. They scrape yelp reviews for sentences which start "How hard is it to..." and my bot answer with some version of how hard it is.

I recently refactored the code to handle changes to the source text as a list of command classes, instead of one ever-expanding method, or collection of methods, in my Generator class.

You can see the code in context on GitHub.

I'm wondering if I should have implemented these classes as singletons, or if there's some reason to leave the singleton declaration out.

Here's some snippets:

generator.rb (much smaller since this refactor)

class Generator

  TRANSFORMS = [
    Transforms::Substitutions,
    Transforms::Answer,
    Transforms::Question,
    Transforms::Recipient
  ]

  def initialize(source, options, recipient='hard_to_yelp')
    @source = source
    @transform_arguments = {
      options: options,
      recipient: recipient
    }
  end

  def run
    result = @source.dup
    TRANSFORMS.each { |transform| result = transform.run(result, @transform_arguments) }
    result = run until result.length <= 140
    result
  end

end

Just one of my transforms, Question, which adds a question mark if there's a questioning word present (or removes one if there isn't).

module Transforms
  class Question
    include Singleton

    QUESTION_WORDS = %w{why where which who}

    def self.run(source, arguments={})
      if is_question?(source)
        has_punctuation?(source) ? source.gsub('.', '?') : source + '?'
      else
        source.gsub('?', '.')
      end
    end

    def self.is_question?(source)
      src = source.downcase
      QUESTION_WORDS.any? { |q| src.index(q) }
    end

    private_class_method :is_question?

    def self.has_punctuation?(source)
      source.index('.') || source.index('?')
    end

    private_class_method :has_punctuation?

  end
end

Singleton pros:

The only public interface is the run method. Some other interface (such as the new method) is removed.
If I choose to keep the environment open (say, with spring), there'll be fewer objects initialised, marginally more performant.

Singleton cons:

It's probably not needed, if I remove the include, it still works.
People don't like singletons.

To singleton, or not to singleton. That is the question.


texts: Analyze terraform template files to return infrastructure cost

texts:
I am trying to write a program I am calling "terraform cashier." Terraform is a tool released by hashicorp to allow you to codify your infrastructure. I thought it would be useful to know how much your infrastructure would cost you before you deployed it, and have implemented a prototype of that for AWS. I also had to write a pricing data ingestion tool and API to power this particular tool, but those seem to be working fine, so I'd like to keep the review to the cli tool itself.

The repo can be found here.

I do a lot of type casting in the processTerraformFile function. How can I avoid that? Am I processing the terraform files correctly? A particular ugly segment of the function is below. The main goal of the function is to import the data in the terraform templates so that it can be processed inside of cashier. I'm just identifying the resources and counting them.

arrayOfResources, success := decodedOutput["resource"].([]map[string]interface{})

if success == true {
    for _, resource := range arrayOfResources {
        for key := range resource {
            switch key {
            case "aws_instance":
                resourceKeys, resourceKeysSuccess := resource[key].([]map[string]interface{})
                if resourceKeysSuccess == true {
                    for resourceKey := range resourceKeys[0] {
                        instanceType, instanceTypeSuccess := resourceKeys[0][resourceKey].([]map[string]interface{})[0]["instance_type"].(string)
                        if instanceTypeSuccess == true {
                            masterResourceMap = countResource(masterResourceMap, key, instanceType)
                        }
                    }
                }
            default:
                fmt.Println("resource type not recognized: ", key)
            }
        }
    }
}

I wrote some basic tests as well, but decided to not test the main() function. Is this standard? It started to feel strange when I was making API calls in my test.


texts: Imitate UITableView reordering interaction

texts:
I have a UIScrollView full of vertically stacked subviews which I want the user to rearrange as they desire. I've implemented a UILongPressGestureRecognizer on my UIScrollView to successfully move the items around.

The more difficult part is when the user brings their finger to the edges of the scrolling area, the UIScrollView needs to scroll, while the gesture recognizer holds onto the floating reordering view. You get this behaviour for free in UITableView when you implement reordering. You can see an example of this when you edit your Safari bookmarks.

My implementation produces the same result, but I have a concern about it. Let me explain.

With each update of the UILongPressGestureRecognizer I check the touch point to see if it is within 20 points of the visual boundaries of my UIScrollView.
If we are within this boundary, I move the content offset by one pixel.
To continue this process as long as the user's finger is within bounds, I repeat the method call.

- (void)handleReorderGestureRecognizerChange:(id)sender
{
    if (!self.reorderGestureRecognizerActive) return;

    // Scroll the scroll view
    BOOL scheduleRecursion = NO;
    if (sender == self.reorderGestureRecognizer && self.scrollViewIsAutomaticallyScrolling)
    {

    }
    else
    {
        // Determine the bounds of the scroll view
        const CGPoint superviewTouchPoint = [self.reorderGestureRecognizer locationInView:self.view];
        const CGPoint currentContentOffset = self.scrollView.contentOffset;
        CGPoint newContentOffset = currentContentOffset;

        // Determine if we are at the bottom
        const CGFloat scrollingBottomArea = (self.scrollView.bottom - 20);
        if (superviewTouchPoint.y > scrollingBottomArea)
        {
            const CGFloat maximumYContentOffset = self.scrollView.contentSize.height - self.scrollView.height;
            newContentOffset = CGPointMake(self.scrollView.contentOffset.x, fmin((self.scrollView.contentOffset.y + SMCompatibilitySinglePixelSize()), maximumYContentOffset));
        }

        // Determine if we are at the top
        if (superviewTouchPoint.y < 20)
        {
            newContentOffset = CGPointMake(self.scrollView.contentOffset.x, fmax((self.scrollView.contentOffset.y - SMCompatibilitySinglePixelSize()), -self.scrollView.contentInset.top));
        }

        // Schedule a change
        if (!CGPointEqualToPoint(currentContentOffset, newContentOffset))
        {
            self.scrollViewIsAutomaticallyScrolling = YES;
            self.scrollView.contentOffset = newContentOffset;

            scheduleRecursion = YES;
        }
        else
        {
            self.scrollViewIsAutomaticallyScrolling = NO;
        }
    }
    ...
    if (scheduleRecursion)
    {
        SM_run_block_after_delay(0.0005, ^{ // <- this hooks through to a dispatch_after call
            [self handleReorderGestureRecognizerChange:self];
        });
    }
}

As I said, this works as expected, I am just very uncomfortable with the idea of continually scheduling this method from itself.

It is however the only way I can think of to make UIScrollView scroll continuously on its own.

As a reviewer would you say this is safe and efficient?


texts: Finding strings inside of other strings in order in C

texts:
A question on Stack Overflow recently intrigued me to the point of me implementing the functionality in C. Can you critique this algorithm and tell me what is good and bad about it?

This program will tell you if a string is inside of another string.

For example:

"elf" would be inside "self"
"hit" would be inside "chemistry"
"tim" would not be inside "chemistry"
"try" would be inside "chemistry"

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

/*
 * const char* const read only
 * const char* is read/write
 */
int find_str_in_str(const char* const base, const char* const sub)
{
        int base_len = strlen(base);
        int sub_len  = strlen(sub);
        char *tmp_sub = NULL;

        /* allocate enough mem for the max string length */
        if(base_len > sub_len) {
                tmp_sub = malloc(base_len + 1);
        }
        else {
                tmp_sub = malloc(sub_len + 1);
        }

        if(NULL == tmp_sub) {
                fprintf(stderr, "Runtime error (malloc)\n");
                exit(1);
        }

        int i = 0;
        int j = 0;

        for(; i < sub_len; i++) {
                for(; j < base_len; j++) {
                        if(base[j] == sub[i]) {
                                tmp_sub[i] = base[j];
                                /* the first occurance was found */
                                break;
                        }
                }
        }

        tmp_sub[i++] = '\0';

        if(0 == strcmp(sub, tmp_sub)) {
                free(tmp_sub);
                return 1;
        } else {
                free(tmp_sub);
                return 0;
        }
}

int main(int argc, char **argv)
{
        if(argc < 3) {
                fprintf(stderr, "Usage: %s %s %s\n", argv[0], "base", "derived");
                return EXIT_FAILURE;
        }

        fprintf(stdout, "Base :    %s\n", argv[0]);
        fprintf(stdout, "Sub  :    %s\n", argv[1]);

        if(1 == find_str_in_str(argv[1], argv[2])) {
                fprintf(stdout, "Result :    true\n");
        } else {
                fprintf(stdout, "Result :    false\n");
        }

        return EXIT_SUCCESS;
}


texts: C++ performance: Linear regression in other way

texts:
Here is the code that can be used for calculation of mathematical function, like ax^2 + bx + c.
It is fast enough if you choose small length, otherwise if programmer don't know the small range, that code can be really slow. I've made it specially on C++ to be more fast.
#include <iostream>
#include <vector>

using namespace std;

template<class var>
var Module(var x){
    if (x >= 0)
        return x;
    else
        return x*-1;
}

class Linear {
public:
    float resA, resB, resC;
    float err;

    float Predict(float a, float b, float c, float x) {
        return ((a * (x*x)) + (b*x) + c);
    }

    float Predict(float x) {
        return ((resA * (x * x)) + (resB * x) + resC);
    }

    float ErrorAv(float a, float b, float c, vector<float> input, vector<float> output) {
        float error = Module(Predict(a, b, c, input[0]) - output[0]);
        for (int i = 1; i < input.size(); i++)
            error = (Module(Predict(a, b, c, input[i]) - output[i]) + error)/2;
        return error;
    }

    void LinearRegr(vector<float> input, vector<float> output, float maximum, float minimum = 0, float step = 1) {
        if (step == 0)
            step++;
        float a, b, c;

        float lastError = INFINITY;
        for (a = minimum; a <= maximum; a += step)
            for (b = minimum; b <= maximum; b += step)
                for (c = minimum; c <= maximum; c += step) {
                    float error = ErrorAv(a, b, c, input, output);
                    if (error < lastError) {
                        lastError = error;
                        resA = a;
                        resB = b;
                        resC = c;
                        err = lastError;

                        if (!lastError)
                            return;
                    }
                }

    }
};

#include <ctime>
int main(){
    vector<float> input; //Input example.
    vector<float> output; //Output example.

    float a = 10.5, b = -7, c = 5.5; //Variables as search values.

    //Fill dataset:
    for (int i = 0; i < 100; i++) {
        input.push_back(i);
        output.push_back((a * (i * i)) + (b * i) + c);
    }

    clock_t begin = clock(); //Start clock while searching a, b, c values
    Linear linear;
    linear.LinearRegr(input, output, 15, -10, 0.5); //Start searching.
    cout << "Time: ~" << double(clock() - begin) / CLOCKS_PER_SEC << " seconds." << endl;

    cout << linear.resA << "*x^2 + " << linear.resB << "x + " << linear.resC << endl; //Enter results.
}

As can see, Linear.LinearRegr function can get from 3 to 5 parameters.
I dont need make the code super prettier(for me its already pretty), just want to work it faster.
How to optimize and make it faster?


texts: Clean up after shell script that is run via k8s pod on a gpu node for health check

texts:
Team,
I have a working script but when we upgraded some drivers on the GPU system it’s starting to cause zombie process and system is lowing down as script runs periodically as a crib job.

so I am trying to see is there a way I can have a graceful clean up after the Scripts run what is the best procedure to clean up after yourself when Scripts is done running? What wrong am I doing or what better could it be?

gpu-health-check.sh: |
     #!/bin/bash
     # Do nothing if nvidia-smi is found. This is not a GPU node.
     if ! [ -x "$(command -v nvidia-smi)" ]; then
       echo "nvidia-smi not found. Ignoring"
       exit 0
     fi
     # Check if there is any retired page. The query is copied from https://docs.nvidia.com/deploy/dynamic-page-retirement/index.html.
     bad_gpus=$(nvidia-smi --query-retired-pages=gpu_uuid,retired_pages.address,retired_pages.cause --format=csv,noheader | cut -d, -f1| sort | uniq)
     if [ -z "${bad_gpus}" ]; then
       echo "No Single/Double Bit ECC Error found"
       exit 0
     fi
     for bad_gpu in "{$bad_gpus}"; do
       # Exit 1 if there is a pending page blacklist as we need to reboot the node to actually add the page to the blacklist.
       nvidia-smi -i $bad_gpu -q -d  PAGE_RETIREMENT | grep Pending| grep Yes > /dev/null 2>&1
       if [ $? -eq 0 ]; then
         echo "Found pending blacklist on ${bad_gpu}"
         exit 1
       fi
       echo "No pending blacklist on ${bad_gpu}"
     done
     exit 0

On gpu system I see

741:19286 ?        Z      0:00 [gpu-health-chec] <defunct>
757:30022 ?        Z      0:00 [gpu-health-chec] <defunct>
761:31930 ?        Z      0:00 [gpu-health-chec] <defunct>
762:31931 ?        Z      0:00 [gpu-health-chec] <defunct>
794:37947 ?        S      0:00 /bin/bash ./config/gpu-health-check.sh
795:37948 ?        S      0:00 /bin/bash ./config/gpu-health-check.sh
796:37955 ?        S      0:00 /bin/bash ./config/gpu-health-check.sh
803:37962 ?        S      0:00 /bin/bash ./config/gpu-health-check.sh
816:50066 ?        Z      0:00 [gpu-health-chec] <defunct>
817:50067 ?        Z      0:00 [gpu-health-chec] <defunct>

All above are just piling up. How to avoid coz system is becoming irresponsible after hours.


texts: Dynamically mess images inside a container

texts:
Well, i'm starting a function to 'mess' with a image gallery, i made an example

i wanna know if the way i'm doing is realy the BEST way, the function work perfect, but i fill that can be better, something more dynamic, like never flow over the edge, and mess with the number of images that user places inside the gallery, now i set as index 0 to 5.

Is there any easy way to improve this little function, make the code faster/smaller then that?

Any tips, be my guest.

jQuery

$("#ran").click(function () {
    mess(1, $(".holder img"));
});

function mess(type, gallery) {
    var getNumImg = gallery.length,
        winWidht = $("#galeria").width(),
        winheight = $("#galeria").height(),
        imgHeight = $("#content-wrapper img").height(),
        ftBottom = winheight - ($(".stats").height() + imgHeight + 150);

    $(".holder").width(winWidht / 2);

    gallery.each(function (index) {
        var randonLeft, randonRight, randonTop, randonTransform, maxIndex;
        var leftFt, topFt, transFt;
        var sign = "- ";
        var signRes = sign.charAt(Math.floor(Math.random() * sign.length));

        if (type == 1) {
            if (index == 0) {
                maxIndex = getNumImg;
                transFt = {
                    "from": 1,
                    "to": 30
                }
                topFt = {
                    "from": 1,
                    "to": ftBottom
                }
            } else if (index == 1) {
                leftFt = {
                    "from": 30,
                    "to": 40
                }
                transFt = {
                    "from": 1,
                    "to": 30
                }
                topFt = {
                    "from": 1,
                    "to": ftBottom
                }
            } else if (index == 2) {
                leftFt = {
                    "from": -30,
                    "to": -40
                }
                transFt = {
                    "from": 1,
                    "to": 30
                }
                topFt = {
                    "from": 1,
                    "to": ftBottom
                }
            } else if (index == 3) {
                leftFt = {
                    "from": -30,
                    "to": -40
                }
                transFt = {
                    "from": 1,
                    "to": 30
                }
                topFt = {
                    "from": 1,
                    "to": ftBottom
                }
            } else if (index == 4) {
                transFt = {
                    "from": 1,
                    "to": 30
                }
                topFt = {
                    "from": 1,
                    "to": ftBottom
                }
            } else if (index == 5) {
                leftFt = {
                    "from": 40,
                    "to": 50
                }
                transFt = {
                    "from": 1,
                    "to": 30
                }
                topFt = {
                    "from": 1,
                    "to": ftBottom
                }
            }
        }

        if (typeof leftFt != "undefined") {
            randonLeft = Math.floor(Math.random() * leftFt.to) + leftFt.from;
        }
        if (typeof transFt != "undefined") {
            randonTransform = Math.floor(Math.random() * transFt.to) + transFt.from;
        }
        if (typeof topFt != "undefined") {
            randonTop = Math.floor(Math.random() * topFt.to) + topFt.from;
        }

        // make it happen
        $(this).css({
            zIndex: maxIndex,
            left: randonLeft,
            top: randonTop,
            transform: "rotate(" + signRes + randonTransform + "deg)"
        });
    });
}


texts:
I've noticed that there are several ways of sending data through a TCP stream. I want to do it the fastest way in terms of latency.

One method I became aware of is with a binary writer:

using (MemoryStream ms = PrintWindow(process))
{
    writer.Write((int)ms.Length);
    writer.Write(ms.GetBuffer(), 0, (int)ms.Length);
}

And to receive it:

Image.FromStream(new MemoryStream(reader.ReadBytes(reader.ReadInt32())));

It writes the size for reference, then takes the data.

For the other method, which is a bit sensitive, it seems that it can easily fail if the image changes for some reason:

using (MemoryStream ms = PrintWindow(process))
{
    tcp.GetStream().Write(ms.GetBuffer(), 0, tcp.SendBufferSize);
}

And to receive it:

byte[] b = new byte[tt1.ReceiveBufferSize];
tt1.GetStream().Read(b, 0, tt1.ReceiveBufferSize);
Image.FromStream(new MemoryStream(b));

I've found this with trial and error.  But, as I've said, it's very sensitive and can cause an error if the image changes in a certain way.  I'm not absolutely sure why, though.

Which of these is the fastest?  In my view, writing with just the stream should be faster than with some special writer.

The error I get when using the second method seems to occur when the data is very low.  For example: a black or near-black picture. If anyone knows how to solve this, please let me know.

It seems that I need to have the TCP Send and Receive buffer at least as big as the largest file for it to work, so I've increased it by x128.  I'm not sure if that's a good idea or not, but from my understanding, the only thing it does is allocate more RAM.  Then again, I think it's probably because I set the byte size to the buffer size.


texts: Axiomatic proofs of natural addition properties, in Idris

texts:
I'm a seasoned programmer in a variety of languages (including Haskell and some ML dialects), but i'm a complete dilettante when it comes to formal logic. I've very briefly looked at Coq, and now i'm trying to dabble in theorem proving with Idris.

In particular, before trying to use the interactive elaborator, I'd like to understand how to create simple proofs, because I had a hard time following the elaborator section of the tutorial. So, I've written the following program, that typechecks successfully:

total
project : a = b -> S a = S b
project Refl = Refl

total
sym : a = b -> b = a
sym Refl = Refl

total
transitive : a = b -> b = c -> a = c
transitive Refl Refl = Refl

total
plus_assoc : (a: Nat) -> (b: Nat) -> (c: Nat) -> a+(b+c) = (a+b)+c
plus_assoc Z     b c = Refl
plus_assoc (S a) b c = project (plus_assoc a b c)

total
plus_succ_commute : (n: Nat) -> (m: Nat) -> S n + m = n + S m
plus_succ_commute Z     m = Refl
plus_succ_commute (S n) m = project (plus_succ_commute n m)

total
plus_commutes : (n: Nat) -> (m: Nat) -> n + m = m + n
plus_commutes Z     Z     = Refl
plus_commutes Z     (S m) = project (plus_commutes Z m)
plus_commutes (S n) m     = transitive (project (plus_commutes n m)) (plus_succ_commute m n)

I'd appreciate advice on how to make things cleaner, and in particular:

At first, I tried to write a direct proof for plus_commutes that would not involve plus_succ_commute, but alas, to no avail.
In the second clause of plus_assoc, I tried to get rid of my definition of project by writing

plus_assoc (S a) b c = let Refl = plus_assoc a b c in Refl

Which seems to me as just substituting the definition of project into the original clause, but fails with a type error:

Type mismatch between
    plus (plus a b) c = plus (plus a b) c (Type of Refl)
and
    a + (b + c) = a + b + c (Expected type)

Specifically:
    Type mismatch between
        plus (plus a b) c
    and
        plus a (plus b c)

Can anyone offer insight as to why inlining this definition breaks the proof ? perhaps I ought to pass some implicits to constraint the type of the subexpression ?


texts: Improving LINQ expression with inner method call and switch statement

texts:
I have the following class which returns an expression that then returns data. It seems a tad over complicated and I'm pretty sure LINQ has something to offer that makes my life much easier. But I simply cannot get it.

/// <summary>Provides methods and properties to query location details from a database.</summary>
internal sealed class LocationDatabaseDetailsRequest : DatabaseDetailsRequest<LocationContext, LocationDataContract, Guid>
{
    /// <inheritdoc />
    public override Func<LocationContext, LocationDataContract> Resource
    {
        get
        {
            return
                c =>
                c.Locations.Select(
                    l =>
                    new LocationDataContract
                    {
                        Id = l.Id,
                        Coordinates = l.Coordinates,
                        Description = l.Description,
                        Name = l.Name,
                        Type = l.Type,
                        Details = this.GetDetails(l.Type, c)
                    }).SingleOrDefault(i => i.Id == this.Identifier);
        }
    }

    private LocationDetailsDataContract GetDetails(string detailsType, LocationContext locationContext)
    {
        switch (detailsType)
        {
            case "City":
                return locationContext.Set<CityDetailsDataContract>().SingleOrDefault(i => i.Id == this.Identifier);
            case "Planet":
                return locationContext.Set<PlanetDetailsDataContract>().SingleOrDefault(i => i.Id == this.Identifier);
            case "StarSystem":
                return locationContext.Set<StarSystemDetailsDataContract>().SingleOrDefault(i => i.Id == this.Identifier);
            case "Sector":
                return locationContext.Set<SectorDetailsDataContract>().SingleOrDefault(i => i.Id == this.Identifier);
            default:
                return null;
        }
    }
}

My problem is the method call. I know which sets the data context has, but they are fluid, meaning it is certain that new sets will get added.

Can I write this query shorter and well... better?


texts: C function to capitalize first word in a sentence, handles arbitrary spaces

texts:
The code below capitalized the first letter of every word in a sentence. It handles an arbitrary number of spaces in any part of string. It works. Can it be optimized further?

void capitalize_string(char *s) {
  while(*s) {
    while (*s && *s == ' ')
      s++;
    *s = toupper(*s);
    s++;
    while (*s && *s != ' ')
      s++;
  }
}


texts:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
  see that the 6th prime is 13.

  What is the 10 001st prime number?

How can I optimize this code?

#include <iostream>

bool is_prime(int num)
{
    for (int i = 2; i <= num/2; ++i)
    {
        if (num % i == 0)
        {
            return false;
        }
    }
    return true;
}

int main()
{
    int count = 2;
    for (int i = 5; ; i = i+2)
    {
        if (is_prime(i))
        {
            count++;
        }
        if (count == 10001)
        {
            std::cout << i;
            return 0;
        }
    }
}


texts: Is this a thread safe way to control access to a reusable resource? Is there a better way?

texts:
public static class ThreadStatic<T> where T : new()
{
    [ThreadStatic]
    private static T instance;

    public static T Instance
    {
        get { return instance ?? (instance = new T()); }
    }
}

Used like this:

var probability = ThreadStatic<Random>.Instance.NextDouble();

Can this be broken? (Like, am I missing a volatile somewhere?)
Is there an existing pattern for this?  Is there a better way to do this?
What would be an elegant way to allow for constructor parameters to be specified?
Would this be better suited to an IOC container?


texts:
I'm fairly proficient in C and Python, but want to learn some skills for administrating my new Linux machine. I wrote this simple address book app to teach myself shell scripting. This is the first script I've written longer than a couple of lines.

The address book is a plain text file stored in $HOME/.sab-db. Entries are separated by newlines and the three fields (first name, surname, email) are separated by colons, like the fields in /etc/passwd.

The application is divided into four scripts that have a single task each. This is inspired by how Git is organized. Is this a good way to isolate independent code in bash?

How should I handle shared code between scripts? I've use two different approaches below: I created a standalone script that the others call for determining the database name, and I copy-pasted the die function. I've heard of script sourcing, but I've never seen that used for creating bash "libraries".

sab-find-db

#!/bin/bash

DB_NAME=".sab-db"

if [ -n "$SAB_DB_DIR" ]; then
    echo "$SAB_DB_DIR/$DB_NAME"
else
    echo "$HOME/$DB_NAME"
fi

sab-search

#!/bin/bash

function die {
    echo "$1" >&2
    exit 1
}

if [ $# -eq 1 ]; then
    # Fields can't include : since it's the delimiter
    if [ $(echo "$1" | grep ":" | wc -l) -gt 0 ]; then
        exit 0
    else
        file=$(mktemp)
        grep -i "$1" $(./sab-find-db) >"$file" 2>/dev/null
    fi
elif [ $# -eq 0 ]; then
    file=$(./sab-find-db)
else
    die "usage: $0 [<first name> | <surname> | <email>]"
fi

cat "$file"

while read line; do
    echo "First name: $(echo "$line" | cut -d: -f1 -)"
    echo "Surname:    $(echo "$line" | cut -d: -f2 -)"
    echo "Email:      $(echo "$line" | cut -d: -f3 -)"
    echo
done <"$file"

if [ $# -eq 1 ]; then
    rm "$file"
fi

sab-add

#!/bin/bash

function die {
    echo "$1" >&2
    exit 1
}

if [ $# -eq 3 ]; then
    entry="$1:$2:$3"
elif [ $# -eq 0 ]; then
    echo -n "First name: "
    read first_name
    echo -n "Surname: "
    read surname
    echo -n "Email: "
    read email
    entry="$first_name:$surname:$email"
else
    die "usage: $0\n [<first name> <surname> <email>]"
fi

if [ $(echo "$entry" | grep -o ":" | wc -l) -gt 2 ]; then
    die "Fields can't include colon"
# Check if any : is next to another : or start or end of line
elif [ $(echo "$entry" | grep "\(^:\)\|\(::\)\|\(:$\)" | wc -l) -gt 0 ]; then
    die "No fields can be left empty"
elif [ $(grep -i "^$entry\$" $(./sab-find-db) 2>/dev/null | wc -l) -gt 0 ]; then
    die "This entry already exists. It was not added again."
else
    echo "$entry" >>$(./sab-find-db)
fi

sab-remove

#!/bin/bash

function die {
    echo "$1" >&2
    exit 1
}

if [ $(grep -i "\<$1\>" $(./sab-find-db) 2>/dev/null | wc -l) -eq 0 ]; then
    die "No match found"
fi

file=$(mktemp)

if [ ! $(grep -vi "\<$1\>" $(./sab-find-db) >"$file" 2>/dev/null) ]; then
    mv "$file" $(./sab-find-db)
else
    rm "$file"
fi


texts: Infinite scroll pagination with a Wookmark layout

texts:
/* Infinite Scroll Pagination with a Wookmark layout
 *
 * Requires: jQuery, Wookmark
 */

var myApp = myApp || {};

;(function(myApp,$){
  var WookmarkPagination = function(elem, options){
    this.elem = elem;
    this.$elem = $(elem);
    this.options = options;
  };

  WookmarkPagination.prototype = {
    defaults: {
      url: '',
      page: 2,
      per_page: 5,
      template: '',
      scroll: true,
      item: ".item",
      items: ".items",
      loader_image: ''
    },

    fetchReady: {
      status: true
    },

    /**
     * Initiate app. Bind the scroll event and onScroll function to the document.
     *
     * @return this
     */
    init: function(){
      var _this = this;
      _this.config = $.extend({}, _this.defaults, _this.options);
      var loader = '

';

      // Set loader
      $(loader).appendTo("body").hide();

      // Build wookmark layout
      wookmark_handler = this.$elem.find(_this.config.item);
      wookmark_handler.wookmark({
        container: _this.$elem,
        offset: 15,
        itemWidth: 160,
        autoResize: true
      });

      if(_this.config.scroll){
        $(document).bind('scroll', function(){
          _this.onScroll();
        });
      }
      return _this;
    },

    /**
     * Rebuild Wookmark layout
     *
     * @return void
     */
    refreshLayout: function(){
      var _this = this;
      var opt = _this.config;
      //console.log(wookmark_handler);

      // Rebuild wookmark positions
      if(wookmark_handler) wookmark_handler.wookmarkClear();
      wookmark_handler = _this.$elem.find(_this.config.item);

      // Initialize Wookmark to build layout container
      wookmark_handler.wookmark({
        container: _this.$elem,
        offset: 15,
        itemWidth: 160,
        autoResize: true
      });
    },

    /**
     * Fetches the JSON from the server. On success rebuilds Wookmark positioning.
     *
     * @return the JSON object
     */
    fetch: function(){
      var _this = this;
      var opt = _this.config;

      // If no other getJSON is being processed continue
      if(_this.fetchReady.status){
        // Block other requests
        _this.fetchReady.status = false;

        // Show loader
        $("#wookmark-pagination-loader").fadeIn();

        // Fetch Data
        return $.getJSON(opt.url,{
          page: opt.page,
          per_page: opt.per_page
        })
        .success(function(data){
          // Each data item is wrapped in a template and appended to the page.
          $.each(data, function(i, item){
            _this.$elem.find(_this.config.items).append(Mustache.to_html(opt.template, item.item));
          });

          // Set next page number for next request.
          opt.page += 1;

          _this.refreshLayout();

        })
        // TODO: setup error catching and show a user there was a problem with the request
        //.error(function(data, response){})
        .complete(function(data){
          // Allow other getJSON requests
          _this.fetchReady.status = true;

          // Hide loader
          $("#wookmark-pagination-loader").fadeOut();
        });
      }
    },

    /**
     * Checks if the scroll position has reached the bottom, then runs the fetch function
     *
     * @return void
     */
    onScroll: function() {
      // Check if we're within 100 pixels of the bottom edge of the broser window.
      var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
      if(closeToBottom) {
        this.fetch();
      }
    }
  };

  WookmarkPagination.defaults = WookmarkPagination.prototype.defaults;

  $.fn.wookmark_pagination = function(options) {
    return this.each(function() {
      new WookmarkPagination(this, options).init();
    });
  };

  myApp.WookmarkPagination = WookmarkPagination;
})(myApp,jQuery);


texts: Improve performance while Traversing List

texts:
I was trying to write a Java program to compare previous records while traversing. It returns true if element exists previously, else false.

e.g.

if elements are {"Raj","Jas","Kam","Jas"} then return true (since Jas element available previously)
if elements are {"Raj","Jas","Kam","Tas"} then return false

I have written the below code, but its complexity is n*n, which is not good.  How could I write clean code to improve the performance?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CompareList {
    private List<String> listNames;
    private List<String> listTempName = new ArrayList<>();

    public CompareList(String[] vListArray) {
        listNames = Arrays.asList(vListArray);
    }
    public CompareList(List<String> vListName) {
        listNames = vListName;
    }
    public boolean isPreviousNameExist() {
        String tempName = null;
        for (int i = 0; i < listNames.size(); i++) {
            tempName = listNames.get(i);
            if (listTempName.contains(tempName)) {
                return true;
            } else {
                listTempName.add(tempName);
            }

        }
        return false;
    }
    public static void main(String[] args) {
        String[] nameArray = {"A", "B", "C", "D", "E", "F"};
        CompareList compareList = new CompareList(nameArray);
        System.out.println("==>" + compareList.isPreviousNameExist());
    }
}

UPDATED

I have updated the code and tried using a recursive way, same way how we sort using MergeSort and find its performance better for a large number of records, compared to HashSet. I believe its complexity is O(log n).

public class NameComparator {

    private String[] listNames;

    private String[] listTempNames;

    private boolean compareFlag = false;

    private int size;
    public boolean isNameAlreadyExist(String[] vListNames) {
        this.listNames = vListNames;
        size = vListNames.length;
        this.listTempNames = new String[size];
        checkAndSort(0, size - 1);
        return compareFlag;
    }
    private void checkAndSort(int low, int high) {

        //Use the merge sort
        }
    }
    ..............................
}


texts:
I just want an indication as to whether or not I'm on the right track regarding PHP OOP, at least on a basic level.  Positive criticism welcome.

P.S. Excuse the visuals of the code.  This is how I usually remember code.

<html>
<?php

//Blueprint

class Human{

    // properties of human
    private $gender;
    private $name;
    private $age;
    private $talk;

    public function __construct($gender, $name, $age, $talk){
        $this->gender   = $gender;
        $this->name     = $name;
        $this->age      = $age;
        $this->talk     = $talk;
    }

    public function getGender(){
        return $this->gender;
    }

    public function getName(){
        return $this->name;
    }

    public function getAge(){
        return $this->age;
    }

    public function getTalk(){
        return $this->talk;
    }
}

class female extends Human{

    //properties of female
    private $bum;
    private $feet;

    public function __construct($gender, $name, $age, $talk, $bum, $feet){
        parent::__construct($gender, $name, $age, $talk);

        $this->bum  = $bum;
        $this->feet = $feet;
    }

    public function  getBumSize(){
        return $this->bum;
    }

    public function getFeetSize(){
        return $this->feet;
    }
}

class male extends Human{

    //properties of male
    private $facialHair;
    private $adamsApple;

    public function __construct($gender, $name, $age, $talk, $facialHair, $adamsApple){
        parent::__construct($gender, $name, $age, $talk);

        $this->beard    = $facialHair;
        $this->throat   = $adamsApple;
    }

    public function getBeard(){
        return $this->beard;
    }

    public function getThroat(){
        return $this->throat;
    }
}

//instantiate objects
$malePerson     = new male('male', 'John Doe', '32', 'clear', 'beard', 'adams apple in my throat');
$femalePerson   = new female('female', 'Jane Doe', '28', 'loud', 'big and round', 'small');

echo "Hi, My name is {$malePerson->getName()}, {$malePerson->getAge()} years of age, I talk {$malePerson->getTalk()}
        so i guess that makes me {$malePerson->getGender()} a.k.a man....I also have
        a {$malePerson->getThroat()} and a {$malePerson->getBeard()} which is very very long .lol";
echo "<br>";
echo "Hi, My name is {$femalePerson->getName()}, {$femalePerson->getAge()} years of age, I talk {$malePerson->getTalk()} so i
        guess that makes me {$femalePerson->getGender()} a.k.a mamalicious....I also have
         {$femalePerson->getFeetSize()} feet and a {$femalePerson->getBumSize()} bum.lol";
?>
</html>


texts: Calling tries to lazy load in every properties getter

texts:
I've inherited a class which has a bunch of properties defined as:

public int ID
{
    get { return m_nOID; }
    set { m_nOID = value; }
}

public int ConxnDetail
{
    get { LoadDetails(); return m_nConxnDetail; }
    set { m_nConxnDetail = value; }
}

public bool ConxnConstraints
{
    get { LoadDetails(); return m_bConxnConstraints; }
    set { m_bConxnConstraints = value; }
}

public bool IsShowCables
{
    get { LoadDetails(); return m_bIsShowCables; }
    set { m_bIsShowCables = value; }
}

public int DefaultQueue
{
    get { LoadDetails(); return m_nDefaultQueue; }
    set { m_nDefaultQueue = value; }
}

private User LoadDetails()
{
    if (!IsLoaded && !IsNew)
    {
        Logger.InfoFormat("Loading user details. UserID: [{0}]", m_nOID);
        User user = RemoteActivator.Create<RemoteUser>().GetUserById(m_nOID);
        if (user != null)
        {
            CopyDetails(user);
            MarkLoaded();
        }
        else
            ClearDetails();
    }
    return this;
}

I would absolutely love to clean up the conventions here a bit and use only automatic getters/setters. Is this possible to do? If not, any other suggestions on reducing the boilerplate needed?


texts: Best structure for a Person in PHP classes (and databse)

texts:
I am (in the process of) creating a system to store People and their details - names, date of birth (dob), addresses, phone numbers, etc. - and I'm curious how it is best achieved. Below is an an example of some of the SQL code with test data (the PHP classes match the structure in the db):

CREATE TABLE IF NOT EXISTS `person` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(16) DEFAULT NULL,
  `forename` varchar(50) DEFAULT NULL,
  `middlenames` varchar(50) DEFAULT NULL,
  `surname` varchar(50) DEFAULT NULL,
  `display` varchar(100) NOT NULL,
  `dob` datetime DEFAULT NULL,
  `dod` datetime DEFAULT NULL,
  `numViews` int(4) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

INSERT INTO `person` (`id`, `title`, `forename`, `middlenames`, `surname`, `display`, `dob`, `dod`, `views`) VALUES
(1, 'Miss', 'Julie', 'Nicola Louise', 'Smith', 'Mum', '1958-09-21 00:00:00', NULL, 1),
(2, 'Mr', 'David', NULL, 'Jones', 'Dave', '1932-06-19 00:00:00', NULL, 0);

CREATE TABLE IF NOT EXISTS `email` (
  `id` int(4) unsigned NOT NULL AUTO_INCREMENT,
  `contactId` int(10) unsigned DEFAULT NULL,
  `address` varchar(250) DEFAULT NULL,
  `type` enum('Personal','Work') DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

INSERT INTO `email` (`id`, `contactId`, `address`, `type`) VALUES
(1, 1, 'j.smith@example.com', 'Personal');

CREATE TABLE IF NOT EXISTS `address` (
  `id` int(4) unsigned NOT NULL AUTO_INCREMENT,
  `line1` varchar(50) NOT NULL,
  `line2` varchar(50) DEFAULT NULL,
  `city` varchar(30) DEFAULT NULL,
  `county` varchar(25) DEFAULT NULL,
  `postcode` varchar(8) DEFAULT NULL,
  `type` enum('Home','Office','Holiday','Other') DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

INSERT INTO `address` (`id`, `line1`, `line2`, `city`, `county`, `postcode`, `type`) VALUES
(1, '32 Test Road', NULL, 'Some City', NULL, 'PO1 2ST', 'Home'),
(2, '6 High Street', 'New Road', 'Chatham', NULL, 'TN6 8BL', 'Home');

CREATE TABLE IF NOT EXISTS `personaddress` (
  `contactId` int(10) unsigned NOT NULL,
  `addressId` int(4) unsigned NOT NULL,
  PRIMARY KEY (`contactId`,`addressId`),
  KEY `addressId` (`addressId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `personaddress` (`contactId`, `addressId`) VALUES
(1, 1),
(2, 2);

I did move the dob & dod fields into another Personal table, as I realised that at times - such as showing email addresses for a Person - that it wasn't necessary to load the dob & dod fields. However, when I did this and when I then wanted to get People with upcoming birthdays, to display the person's name I either had to load a Person object at the same time or add the display field to the Personal class and join the tables in the SQL - which I really didn't want to do (loose coupling). So I ended up moving the fields back to Person.

So my question is what is the best way of implementing this structure?

Note that in a class I currently have standard getter/setter methods, then additional methods (such as getFullName, getFullLegalName, etc. for Person) and finally methods for db interaction – load, save, etc. I've also been informed that really I should put these other methods into different classes. So my second question (which I suppose is tied to the first really) is should I also have separate classes for different sets of methods?


texts: Mapping from multiple sources to destination using JMapper

texts:
I am using JMapper to map from multiple sources to a destination class. Could you review it and let me know if the code looks OK to you? Please suggest any changes that I can make to improve it.

Interface to Map sources to destination object:

public interface ObjectMapper<D> {

    public D getDestination(Object... sources);

}

Class that implements this interface to perform the desired mapping using JMapper:

import org.apache.commons.lang.WordUtils;
import com.googlecode.jmapper.JMapper;

public class JMapperImpl<S1, S2> implements ObjectMapper<DestinationClazz> {

    private static ObjectMapper<DestinationClazz> INSTANCE;
    private static final String CONVERSION_END = "Conversion.xml";

    private Class<S1> source1;
    private Class<S2> source2;

    private final JMapper<DestinationClazz, S1> mapper1;
    private final JMapper<DestinationClazz, S2> mapper2;

    private JMapperImpl(Class<DestinationClazz> destination, Class<S1> source1, Class<S2> source2) {
        final String mappingFile = getMappingFile(destination);
        mapper1 = new JMapper<DestinationClazz, S1>(destination, source1, mappingFile);
        mapper2 = new JMapper<DestinationClazz, S2>(destination, source2, mappingFile);

        this.source1 = source1;
        this.source2 = source2;
    }

    /**
     * @param destination
     * @return uncapitalizes the first letter of destination class name.
     */
    private String getMappingFile(Class<DestinationClazz> destination) {
        return WordUtils.uncapitalize(destination.getSimpleName())+CONVERSION_END;
    }

    public static <S1, S2> ObjectMapper<DestinationClazz> getJMapperInstance(Class<DestinationClazz> destination, Class<S1> source1, Class<S2> source2) {
        if(INSTANCE == null) {
            INSTANCE = new JMapperImpl<S1, S2>(destination, source1, source2);
        }
        return INSTANCE;
    }

    /**
     * Returns new instance of destination object with its properties mapped from source objects
     */
    @Override
    public DestinationClazz getDestination(Object... sources) {
        DestinationClazz destination;
        try {
            destination = DestinationClazz.class.newInstance();
            for(Object source : sources) {
                Class<? extends Object> sourceClass = source.getClass();
                if(sourceClass == source1) {
                    destination = mapper1.getDestination(destination, (S1)source);
                }
                else if(sourceClass == source2) {
                    destination = mapper2.getDestination(destination, (S2)source);
                }
            }
        } catch (InstantiationException e) {
            throw new CustomException("Couldn't instantiate DestinationClazz class:"+e.getMessage());
        } catch (IllegalAccessException e) {
            throw new CustomException("Couldn't access DestinationClazz class:"+e.getMessage());
        } catch (Exception e) {
            throw new CustomException("Exception while mapping source objects to DestinationClazz object:"+e.getMessage());
        }
        return destination;
    }
}


texts:
I've been teaching myself basic haskell this week in order to be able to better read literature about functional programming (about 80% of which in haskell by my completely off-the-cuff statistic). Just as a check to make sure I got the basic concepts, here is how I answered Project Euler 1.

divisible :: Integral a => a -> a -> Bool
divisible x y = mod y x == 0

-- do any of the predicates match a value
any' :: [a -> Bool] -> a -> Bool
any' predicates match = any ($ match) predicates

euler1 :: Integral a => [a] -> a
euler1 xs = sum . filter (any' [divisible 3, divisible 5]) xs

euler1' = euler1 [1..999]

I opted to describe how the answer is defined (as seems to be the way FP works) as opposed to find a faster solution, as this was an exercise in idiomatic FP and haskell.

Since this is supposed to be a practice in idiomatic haskell, point free seems to be the way to go:

-- with the same type definitions
divisible = ((==) 0 .) . flip mod
any' = flip (any . flip id)
euler1 = sum . filter $ any' [divisible 3, divisible 5]

The main purpose of this review is this: which definition of each of these functions is the most idiomatic haskell? Along those lines, this is not supposed to be reinventing-the-wheel, and if a Prelude or stdlib solution to divisible or any' exists, they should be replaced with the stdlib version.

I admit that tools were used in the process of creating the pointfree version. With divisible I think I fully understand the composition (f . . g === f ( g ( arg, arg ) )), but I'd be fecetious in saying I fully understood the pointfree formulation of any'. That may effect the best solution for me, but I'm interested mostly in idiomatic, readable (to more veteran haskellers) code.


texts:
I'm learning string algorithms and I wanted to optimize the basic suffix algorithm which I implemented.
suffix.go
package main

import (
  "fmt"
)

func main(){
  str := "Hello"
  arr := []string{}
  for i:=len(str)-1; i >=0 ; i--{
    var s string
    s = s+str[i:]
    fmt.Println(s)
    arr = append(arr, s)
  }
}

The problem with the above code is, every time I'm creating a new string. I'm trying to avoid it but was not able to do.


texts: Fast import of numbers stored in a CSV file

texts:
I would like to efficiently import real numbers stored in CSV format into an array.  Is there a way to modify my code to make it faster?  Also, is there a way to scan the file and compute the number of rows and columns rather than having to provide these directly?

double * getcsv(string fname, int m, int n){
    double *a;
    a = (double *)malloc(n * m * sizeof(double));

    ifstream fs(fname.c_str());
    char buf[100];

    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            if (j < (n-1) ){
                fs.getline(buf,100,',');}
            else{
                fs.getline(buf,100);}
            stringstream data(buf);
            data>>a[(i*n)+j];

         }
     }

     return(a);
}


texts: Versatile React component that maps style attributes

texts:
I'm creating a versatile component with styled-components that essentially just maps style attributes. I feel my type declarations seem inefficient in getting access to props.

Is it appropriate to use the props interface for each of these styles the way I'm doing it? Thoughts?

import styled, { css } from 'styled-components';
import { darken } from 'polished';

import { elevation as boxShadow, color } from '../../StyleBase';
import { mapStyle } from '../../StyleBase';

export interface BoxProps {
    fill?: boolean;
    background?: string;
    padding?:
        | number
        | [number, number]
        | [number, number, number]
        | [number, number, number, number];
    margin?:
        | number
        | [number, number]
        | [number, number, number]
        | [number, number, number, number];
    radius?: number;
    elevation?: number;
    border?: boolean;
}

const padding = ({ padding }: BoxProps) => mapStyle('padding', padding);

const margin = ({ margin }: BoxProps) => mapStyle('margin', margin);

const radius = ({ radius }: BoxProps) => mapStyle('border-radius', radius);

const background = ({ background }: BoxProps) =>
    mapStyle('background', background);

const elevation = ({ elevation }: BoxProps) =>
    elevation && mapStyle('box-shadow', boxShadow[elevation]);

const fill = ({ fill }: BoxProps) =>
    fill &&
    css`
        flex: 1 1 0%;
    `;

const border = ({ border }: BoxProps) =>
    border &&
    css`
        border: 1px solid ${darken(0.07, color.GRAY_LIGHT)};
    `;

export const Box = styled.div`
  ${fill}
  ${padding}
  ${margin}
  ${radius}
  ${background}
  ${elevation}
  ${border}
`;
```


texts: Golang implementation of Pascal's triangle

texts:
How can I improve my code and make it more idiomatic?

package pascal

func NextRow(prevRow []int) []int {
    x := make([]int, len(prevRow)+1, len(prevRow)+1)
    x[0], x[len(prevRow)] = 1, 1
    for i := 0; i < len(prevRow)-1; i++ {
        x[i+1] = prevRow[i] + prevRow[i+1]
    }
    return x
}

func Triangle(x int) [][]int {
    y := [][]int{}
    for i := 0; i < x; i++ {
        if i == 0 {
            y = append(y, []int{1})
        } else {
            y = append(y, NextRow(y[i-1]))
        }
    }
    return y
}


texts: Returning an IEnumerable using Linq-to-SQL which is then bound to a GridView

texts:
This function works, but it's really really slow and the generated SQL is gargantuan and horrible to look at.  It's also very expensive to run when it shouldn't be.

public static IEnumerable<TrackingComputer> TrackingBoardPCsgroup(string groupName)
{
    var pingresult = from p in db.GetTable<tblTBHealthPing>()
                     group p by p.ComputerAsset into g
                     select g.OrderByDescending(t => t.HealthPingTime).FirstOrDefault();

    var healthresult = from p in db.GetTable<tblTBHealthHeartbeat>()
                       group p by p.ComputerAsset into g
                       select g.OrderByDescending(t => t.HealthHeartbeatTime).FirstOrDefault();

    var query = (from t in TrackingBoardPCs()
                 where t.TrackingGroup == groupName
                 select new TrackingComputer
                 {
                     ComputerName = t.ComputerAsset,
                     IPAddress = t.ComputerIP,
                     Location = t.Location,
                     Pingable = (from p in pingresult where p.ComputerAsset == t.ComputerAsset select p.HealthPingResult).FirstOrDefault() ?? false,
                     PingTime = (from p in pingresult where p.ComputerAsset == t.ComputerAsset select p.HealthPingTime).FirstOrDefault() ?? DateTime.Now.AddDays(-100),
                     Username = (from p in healthresult where p.ComputerAsset == t.ComputerAsset select p.HealthCurrentUser).FirstOrDefault(),
                     CurrentWindow = (from p in healthresult where p.ComputerAsset == t.ComputerAsset select p.HealthCurrentWindow).FirstOrDefault(),
                     Uptime = (from p in healthresult where p.ComputerAsset == t.ComputerAsset select p.HealthUptime).FirstOrDefault()
                 }).OrderBy(t => t.Pingable);
    return query;
}

TrackingBoardPCs function:

public static IQueryable<tblTrackingBoardPC> TrackingBoardPCs()
    {

            var query = (from tbpcs in db.GetTable<tblTrackingBoardPC>()
                         select tbpcs);

        return query;

    }


texts: Check if dictionary keys are declared, if not leave them as true

texts:
I've tried with:

dictionary.TryGetValue("MoreDetails", out bool MoreDetails);

but if the key is not present it defaults to false, and I need it to default to true. Else I have this working implementation:

Dictionary<string, bool> CheckNullsSectionsVisibility(Dictionary<string, bool> dictionary)
{
    bool Summary = true;
    bool Backlog = true;
    bool MoreDetails = true;

    if (dictionary != null)
    {
        Summary = dictionary.ContainsKey("Summary") ? dictionary["Summary"] : true;
        Backlog = dictionary.ContainsKey("Backlog") ? dictionary["Backlog"] : true;
        MoreDetails = dictionary.ContainsKey("MoreDetails") ? dictionary["MoreDetails"] : true;
    };

    return new Dictionary<string, bool> {
        { "Summary", Summary},
        { "Backlog", Backlog},
        { "MoreDetails", MoreDetails}
    };
}

Is there a better approach? I don't like to repeat the true assignment, by the way.


texts: strlen and strcmp implementation in x86 FASM assembly

texts:
I wrote my own implementation of strlen and strcmp from C in x86 FASM and I would like to know is there anything that should be changed or improved.

strlen needs string in eax and is returning length of that string into ebx.

strlen:
    mov ebx,0
    strlen_loop:
        cmp byte [eax+ebx],0
        je strlen_end
        inc ebx
        jmp strlen_loop
    strlen_end:
        inc ebx
        ret

strcmp needs two strings (one in eax, other in ebx) and returns into ecx 0 if strings are equal or 1/-1 if they are not.

strcmp:
    mov ecx,0
    strcmp_loop:
        mov byte dl,[eax+ecx]
        mov byte dh,[ebx+ecx]
        inc ecx
        cmp dl,0
        je strcmp_end_0
        cmp byte dl,dh
        je strcmp_loop
        jl strcmp_end_1
        jg strcmp_end_2
    strcmp_end_0:
        cmp dh,0
        jne strcmp_end_1
        xor ecx,ecx
        ret
    strcmp_end_1:
        mov ecx,1
        ret
    strcmp_end_2:
        mov ecx,-1
        ret


texts:
I'm trying to develop some templates for common HTML + CSS tasks I've been dealing with. One of which is a general search results list either from client- or server-side.

So far I'm using the following reusable code which seems to be working fine without any noticeable bug:

[Dummy Title] Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis accumsan felis. Maecenas vel libero mi. Suspendisse potenti. Sed tempus ex eu diam imperdiet mattis ac ut orci. Sed non lectus libero. Suspendisse vitae nunc a quam mattis congue id eget tortor. Vivamus id arcu eros. Duis eu risus semper, dapibus quam in, tristique magna. Duis semper tempus dolor eget elementum. Duis arcu ipsum, suscipit a egestas quis, lobortis sit amet purus.

                        dummy notes 1
                        &bull; dummy notes 2
                        &bull; dummy notes 3

                        dummy notes 4
                        &bull; dummy notes 5
                        &bull; dummy notes 6

Some main characteristics of this code are:

the text content has a maximum of 5 lines (title + notes) independently of the amount of text content
independently of the number of title lines, the notes are always immediately bellow (no variable gap)
the maximum number of title lines automatically adjust according to the number of notes lines included or removed

Interested in:

Is it possible to simplified it? There is a nest of
,  and flexbox that seems to me overly complicated for such a simple task ...
Any standard nomenclature or other best practices?
Any ideas to improve its design and appearance (without JS)?


texts:
I'm trying to solve a graph traversal problem I found, and was wondering how I could improve my implementation. Currently it seems a little convoluted and long.

The problem is as follows:
I have a matrix of size (rows x cols). This matrix has some cells that are empty (designated by a 0) and some cells that are blocked off (designated by a 1). Given a length, I would like to find a consecutive set of empty cells (ie, a path) of size length.

For this specific code instance, I actually hardcoded the matrix, as well as the length. My approach was:

to loop through the matrix;
at each position try to find a path, if that position was empty and not yet visited;
if so, then find all adjacent positions that fit the same condition (ie, empty and not visited);
if adjacent positions exist, continue finding further adjacent positions until my path is complete in size;
if a path is not possible, then print "impossible".

My code is as follows:

def positionInGraph(pos):
    return ((pos[0] >= 0) and (pos[1] >= 0)) and ((pos[0] < rows) and (pos[1] < cols))

def positionNotVisited(pos):
    return not(pos in visited)

def positionIsEmpty(pos):
    return (graph[pos[0]][pos[1]]==0)

def getAdjacent(posx, posy):
    adjQueue = [(posx-1,posy), (posx, posy+1), (posx+1, posy), (posx, posy-1)]
    for i in adjQueue:
        if (positionInGraph(i) and positionNotVisited(i) and positionIsEmpty(i)):
            yield i

def getOnePath(pos):
    counter = 0
    pathList = []
    processQueue = []
    if (not(positionIsEmpty(pos)) or (pos in visited)):
        return (pathList, counter)
    else:
        processQueue.append(pos)
    while (processQueue and (counter < length)):
        currentPos = processQueue.pop()
        visited.add(currentPos)
        pathList.append(currentPos)
        counter = counter + 1
        adjQueue = getAdjacent(currentPos[0],currentPos[1])
        if (not(adjQueue) and counter < length):
            pathList.pop(currentPos)
            counter -= 1
        for i in adjQueue:
            processQueue.append(i)

    print pathList
    return (pathList, counter)

def findFinalPath():
    #5 4 8
    # oxoo
    # xoxo
    # ooxo
    # xooo
    # oxox

    for i in xrange(0,rows):
        for j in xrange(0,cols):
            path = getOnePath((i,j))
            if path[1] == length:
                return path[0]

    return "impossible"

visited = set()
graph = [[0,1,0,0],[1,0,1,0],[0,0,1,0],[1,0,0,0],[0,1,0,1]]

rows = 5
cols = 4
length = 8

findFinalPath()


texts:
I know of BlockingCollection in .net, but this is rather for my understanding of the pattern. Is this implementation correct ?

Consumer

class Consumer
{
    readonly Queue<int> _q;

    public Consumer(Queue<int> q)
    {
        this._q = q;
    }

    public void Consume()
    {
        for (int i = 0; i < 10; i++)
        {
            while (_q.Count == 0)
            {
            }

            Console.WriteLine("consuming " + _q.Dequeue());
        }

    }
}

Producer

class Producer
    {
        readonly Queue<int> _q;
        readonly int _maxSize;

        public Producer(Queue<int> q, int maxSize)
        {
            this._q = q;
            this._maxSize = maxSize;
        }

        public void Produce()
        {
            for (int i = 0; i < 10; i++)
            {
                while (_q.Count == _maxSize)
                {
                }

                Console.WriteLine("producing " + (i + 1));
                _q.Enqueue(i + 1);
            }
        }
    }

Client

class Program
    {
        static void Main(string[] args)
        {
            Queue<int> q = new Queue<int>();
            var prod = new Producer(q, 10);
            var consumer = new Consumer(q);

            var producerThread = new Thread(new ThreadStart(prod.Produce));
            producerThread.Start();

            var consumerThread = new Thread(new ThreadStart(consumer.Consume));
            consumerThread.Start();
        }
    }

The way I see it, this handles the race condition in Inadequate implementation by introducing while instead of if

The program runs fine on my machine, so is this correct or am i missing something? why the need for synchronization?


texts: Math game with 'hard' and easy questions

texts:
In my competition, I was to create a game that asked at least 5 easy questions, and up to ten hard questions, summing fifteen questions. Please review my code, especially how I formatted it with the class. ALL criticism is appreciated.

#SkillsUSA Computer Programming Problem Number One - Math Challenge

import random
import time

class Math_game(object):

    def __init__(self):

        print("Welcome to the Official Math Game of SkillsUSA!\nYou will have at least five relatively simple questions,\nand up to ten difficult ones.\nGood luck!")
        time.sleep(5)
        x = 3
        while x != 0:
            print("Starting in ",x,"...")
            time.sleep(1)
            x -= 1

        #Above we can see a cheesy intro with the time countdown.

        self.tried = 0
        self.correct = 0
        self.easyQuestionsAsked = 0
        self.numCorrect = -1

        #The __init__ method is simply the initiating object. When an object of the class is made, this method/function is automatically called.
        #By automatically declaring all of these objects, we can start keeping track of the number of questions attempted, correct, etc.

    def prob(self, maximum, operators):

        self.maximum = maximum
        self.operators = operators
        self.num_a, self.num_b = [random.randint(1,self.maximum),random.randint(1,self.maximum)]

        #In the above line, we are able to declare two variable values in one, efficient line.

        operators = ['+','-','*']

        self.operator = operators[random.randint(0,int(self.operators))]

        #The operators parameter of the "prob" method is used to access the list of operators, If only two operators are available to use, a random number
        #chooses between + or -. Otherwise, it will choose between + or - or *.

        if self.maximum < 50:

            if self.num_a <= self.num_b:
                self.num_a = random.randint(1,self.maximum)

        #If it is an easy problem and we are not allowed to use negatives, and the first number is smaller than the second, just default to 25.

        if self.operator== '+':
            self.answer = self.num_a + self.num_b
        elif self.operator == '-':
            self.answer = self.num_a - self.num_b
        else:
            self.num_a, self.num_b = random.randint(-12,12), random.randint(-12,12)
            # If we are using the multiplication operator, set the numbers to max out at 12, or be as low as -12.
            self.answer = self.num_a * self.num_b

        #Above, we use the parameter, userself.answer, and see if the self.answer is correct. Below, we the returned value is whether the user correctly self.answered the question.

        return self.num_a, self.operator, self.num_b

    def isCorrect(self, userInput):

        self.userInput = userInput
        #Simply returning whether the user answer was correct or not.
        return self.userInput == self.answer

game = Math_game()
#Make an object of the  Math_game class.
while game.tried <= 15:
    if game.easyQuestionsAsked <= 5:
        game.prob(25,1)
        game.easyQuestionsAsked += 1
        #While we have not asked 15 questions yet, and while there have been less than 5 easy questions asked, ask another easy question.
    else:
        game.prob(50,2)
    userAnswer = int(input("Problem:  {0} {1} {2}  :  ".format(game.num_a, game.operator, game.num_b)))
    #If we do not HAVE to ask an easy question, feel free to ask a hard one.

    if game.isCorrect(userAnswer):
        game.numCorrect += 1
        print("Right!")
    else:
        print("Wrong!")
    game.tried += 1
    #Accumalting questions asked.

if game.numCorrect > 11:
    print("Great job! ({0}/15)".format(game.numCorrect))
else:
    print("Try again for a better score! ({0}/15)".format(game.numCorrect))
print("This window will automatically close in ten seconds.")

time.sleep(10)
quit()


texts:
I am doubtful about the security of my PHP code. I am new to programming, but want to learn how to secure things, protect my databases from SQL injection, and other best practices. I'd like to know if my databases are safe from attacks with this code.

public function __construct( $data = array() ) {
               if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
              if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}

I would appreciate any suggestions to existing scripts if mine is insufficient.
If somebody wants to inspect the entire code of this class, here it is:

<?php

class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";

public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}

public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}

public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";

$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();

$valid = $stmt->fetchColumn();

if( $valid ) {
$success = true;
}

$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}

public function register() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";

$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
return "Registration Successful
 Login Now";
}catch( PDOException $e ) {
return $e->getMessage();
}
}

}

?>


texts:
This code works as intended, however, I am sure that there is a way to condense the xmldataLoad method. If someone could maybe explain a better approach than what I have done with the method, I would be extremely grateful.
Essentially, what I am saying is I am rather new to using LINQ and don't fully understand the various ways of using it, and I am quite sure there are many people in the same boat as I am.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Xml.Serialization;
//using XMLControlLibrary;

namespace EJCTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        private void xmlDataLoad()
        {
            string xmlPath = @"C:\Users\Jesse\Source\Repos\AsyncSpeechSynth\EJCTest\XMLControlLibrary\newDictionary.xml";
            XDocument xdoc = XDocument.Load(xmlPath);

            var eng = from wordList in xdoc.Root.Elements("Word")
                      select wordList.Element("English").Value;
            engList.ItemsSource = eng.ToList();

            var rom = from wordList in xdoc.Root.Elements("Word")
                      select wordList.Element("Romaji").Value;
            romList.ItemsSource = rom.ToList();

            var jpn = from wordList in xdoc.Root.Elements("Word")
                      select wordList.Element("Japanese").Value;
            jpnList.ItemsSource = jpn.ToList();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            xmlDataLoad();
        }

        public class WordList
        {
            string english;
            string romaji;
            string japanese;

            public string English
            {
                get { return english; }
                set { english = value; }
            }

            public string Romaji
            {
                get { return romaji; }
                set { romaji = value; }
            }

            public string Japanese
            {
                get { return japanese; }
                set { japanese = value; }
            }
        }
    }
}


texts: Setting locale based on preferences with fallbacks

texts:
Consider the following code. Are the multiple assignments to the loc variable a code smell? If so, how can I refactor this?

def set_locale
  begin
    loc = user_signed_in? ? user_locale : browser_locale
    loc = browser_locale if loc.nil?
    loc = param_locale if loc.nil?
    loc = I18n.available_locales.include?(loc.to_sym) ? loc.to_sym : I18n.default_locale
  rescue
    loc = I18n.default_locale
  ensure
    cookies.permanent[:my_locale] = loc
  end
  I18n.locale = loc
end


texts: How to take the some elements of a list of random numbers and sort them?

texts:
I want to create a file consisting take rows of distinct numbers in ascending order. They are randomly taken from the first total integer. The file will be used to make an excerpt as discussed here.

I realize that my naming convention for identifiers below is not good but please ignore it for the sake of simplicity.

using System;
using System.IO;
using System.Linq;

namespace Karls.Students.Excerpting
{
    class Program
    {
        static void Main(string[] args)
        {
            int total = int.Parse(args[0]);
            int take = int.Parse(args[1]);
            int seeder = int.Parse(args[2]);
            string filename = args[3];

            int[] array = Enumerable.Range(1, total).ToArray();

            Random random = new Random(seeder);
            for (int i = total - 1; i > 0; i--)
            {
                int j = random.Next(i+1);
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }

            File.WriteAllLines(filename, array.Take(take).OrderBy(x => x).Select(x => x.ToString()));
        }
    }
}

With best practice in mind, is there anything "bad" in my code?


texts: please check my user session login system and tell me what can be done to make it better

texts:
There can be some errors in the script, if u find them thanks, but the main thing is to get useful suggestions about how can I do this better and secure.

ini_set('session.use_only_cookies', true);
session_start();
//Create a random salt value
$salt = 'Hjkhkjh9089&j98098';
$tokenstr = (str) date('W') . $salt;
//Create a md5 hash to be used for token.
$token = md5($tokenstr);

///checking if already logged in
if ($_REQUEST['token'] == $token AND $_SESSION['user_ip']=$_SERVER['REMOTE_ADDR'] ) {
   ...grant user with some data
}

//user login block
if (($_POST['login']!="") OR ($_COOKIE["username"]!='' AND $_COOKIE["password"]!='') AND $_SESSION['user']=='')
{

    if ($_SESSION['temp_ban']==1)
    {

    $p='login_error';
    }
        else
        {
        $ip=$_SERVER['REMOTE_ADDR'];
        $result2=  mysql_query("SELECT * FROM banned_ip_list WHERE banned_ip='$ip'") or die("unable to connect to msql server: " . msql_error()) ;
        $row2 = mysql_fetch_array($result2);
            if (!$row2=="")
            {
            $_SESSION['temp_ban']=1;
            $p='login_error';
            }
                else
                {
                    if ($_COOKIE["username"]!='' AND $_COOKIE["password"]!='')
                    {
                    $login_username=security2($_COOKIE["username"]);
                    $login_password=security2($_COOKIE["password"]);
                    $remember_me='on';
                    }
                    else
                    {
                    $login_username=security2($_POST['username']);
                    $login_password=security2($_POST['password']);
                    $remember_me=security2($_POST['remember_me']);
                    }
                    $result = mysql_query("SELECT * FROM users WHERE    username='$login_username' AND password=SHA1('$login_password')") or die("unable to connect to msql server: " . msql_error()) ;

                    $row = mysql_fetch_array($result);
                        if ($row!="")
                        {
                            if($remember_me!='')
                            {
                            $expire=time()+60*60*24*7;
                            setcookie("username", $login_username , $expire);
                            setcookie("password", $login_password , $expire);
                            }

                        $_SESSION['user_ip']=$_SERVER['REMOTE_ADDR'];
$_SESSION['user_id']=$row['id'];
$_SESSION['user']=$row['username'];
$_SESSION['ch_insert_temp_key']=1;
$_SESSION['token'] = $token;
output_add_rewrite_var('token', $token);

$_POST['login']='';
unset($_SESSION['try_error']);
                        }
                            else
                            {
                                if (!$_SESSION['try_error'] AND !$_SESSION['temp_ban'])
                                {
                                $_SESSION['try_error']=11;
                                }
                                if ($_SESSION['try_error']-1==1)
                                {
                                $_SESSION['temp_ban']=1;
                                $ip=$_SERVER['REMOTE_ADDR'];
                                $banned_time=date('Y-m-d H:i:s');

                                $result3 = mysql_query("INSERT INTO banned_ip_list (banned_ip,banned_time) VALUES ('$ip','$banned_time')") or die("unable to connect to msql server: " . msql_error()) ;
                                /////////////log
                                $event_type_id=10;
                                $additional_info='';
                                $event_object='';

                                include $log_entry;
                                //////////////////
                                }
                                else {$_SESSION['try_error']--;}
                            $p='login_error';
                            }

                }
        }

}


texts: Better way to assert correct return values in Groovy

texts:
I have written a function that returns me the duplicates of a list:

static List<SomeClass> findDuplicateElements(List<SomeClass> myObjects) {
    List<SomeClass> duplicates = myObjects
    .groupBy { it.someAttribute }
    .findAll { it.value.size() > 1 }
    .collect { it.value }
    .flatten()

    assert duplicates.size() != 1
    duplicates
}

The list cannot have the size 1 because if no duplicates are found it must be empty else if there are duplicates it must me at least 2 elements.

Without that check I would do it this way without having to create any new variables:

static List<SomeClass> findDuplicateElements(List<SomeClass> myObjects) {
    myObjects
    .groupBy { it.someAttribute }
    .findAll { it.value.size() > 1 }
    .collect { it.value }
    .flatten()
}

When using assert, is there any way to avoid saving the result in the duplicates variable and returning it at the end?


texts:
This script documents every website visited and writes the text content of each webpage to its own individual file. It seems to work as intended. Is there anything I could do to improve it?

#!/bin/bash

#####################
##### Functions #####
#####################

chrome() {

    osascript -e \
    'tell application "Google_Chrome" to tell active tab of window 1 to execute javascript "document.body.innerText"' 2>&1

}

set_variables() {

    ds="$(date +%Y_%m_%d)"
    url="$(osascript -e 'tell app "Google_Chrome" to tell the active tab of window 1 to get the url as text' 2>&1 | grep -v '78:82: execution error')"
    title="$(osascript -e 'tell application "Google_Chrome" to tell active tab of window 1 to get the title as text' 2>&1 | grep -v '84:88: execution error')"
    site="$(echo "$url" | awk -F '/' '{OFS="/"} { print $3 }')"
    page="$(echo "${site%.*}" | sed 's/www.//g')"
    name="$(echo "$url" | awk -F '/' '{OFS="/"} { print $4 }')"
    if [[ "$name" = '' ]]; then
        name="$page"
    fi
    dir="$HOME/Logfiles/$page/$ds"
    if [ ! -d "${dir}" ]; then
        mkdir -p "${dir}"
    fi
    doc="$name.txt"
    tmp="${doc}_temporary.txt"
    file="${dir}/${doc}"
    if [[ $url = '' ]]; then
        echo -e "\nAll browser windows have closed\nNow exiting\n" && exit
    fi
    echo

}

##################
##### Script #####
##################

while true
do
    set_variables
    echo -e "$ds\n----------\n$site\n$title\n" | tee -a "$file"
    while true
    do
        current_url="$(osascript -e 'tell app "Google_Chrome" to tell the active tab of window 1 to get the url as text' 2>&1 | grep -v '78:82: execution error')"

        if [[ "$current_url" != "$url" ]]; then
            awk '!seen[$0]++' "$file" >> "$tmp"
            cat "$tmp" > "$file"
            rm "$tmp"
            break 1
        # example regex for specific websites
        elif [[ "$current_url" = https://example.com/*/ ]]; then
            regex='[[:alnum:]]'
        else
            regex='[\p{L}]'
        fi

        chrome | while read -r lines
        do
            echo "$lines" | grep -E $regex
        done
    done | awk '!seen[$0]++ { print; fflush() }' | tee -a "$file"
done


texts: Remove and move elements in a WebBrowser Control page

texts:
I'm making some changes to a page on a WebBrowser Control. There is some indications in the code. I just want to make sure that I don't have any unnecessary lines of code.

namespace AL4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.Document.GetElementById("gpu_notice").Style = "display:none"; // hide gpu_notice element
            webBrowser1.Document.GetElementById("header").OuterHtml = ""; // delete header element
            webBrowser1.Document.GetElementById("ads").OuterHtml = ""; // delete ads element
            webBrowser1.Document.GetElementById("the_game").Style += "position: absolute; top: 0px; right: 0px;"; // align the_game element to the center of the webbrowser
        }
    }
}