texts:
I started following Harvard's CS50 (Introduction to Computer Science) on edX, and as part of their Hacker edition set 1 was the following assignment:

I am supposed to write a program (in C), that takes as input a long long int from the user and proceeds to check whether the entered number is a valid credit card number. For the purposes of this assignment, I am only interested in Visa, American Express and MasterCard number formats. The validation is done with Luhn's algorithm.

/* This program checks whether an entered number is a valid
 * credit card number (only American Express, Visa and
 * MasterCard formats are supported).
 */

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

int main(void)
{
    long long int credit_card;
    int digits = 0;
    string bank = "";

    printf("Number: ");
    credit_card = GetLongLong();

    // calculate number of digits
    for (long long int temporary = credit_card; temporary > 0;
                    temporary /= 10, digits++);

    // check if number length corresponds to valid format
    switch (digits)
    {
        case 13:
            if ( (credit_card / (long long int) pow(10, digits - 1) ) == 4)
            {
                bank = "VISA";
                break;
            }

        case 15:
            if ( ( (credit_card / (long long int) pow(10, digits - 2)) == 34 ) ||
                   (credit_card / (long long int) pow(10, digits - 2)) == 37)
            {
                bank = "AMEX";
                break;
            }

        case 16:
            if ( ( (credit_card / (long long int) pow(10, digits - 2)) >= 51) &&
                   (credit_card / (long long int) pow(10, digits - 2)) <= 55)
            {
                bank = "MASTERCARD";
                break;

            }
            else if ( (credit_card / (long long int) pow(10, digits - 1) ) == 4)
            {
                bank = "VISA";
                break;
            }
        // sets bank to invalid if it doesn't satisfy any of the standards.
        default:
            bank = "INVALID";
    }

    if (strcmp(bank, "INVALID") != 0)
    {
        // used for summing up the digits of the credit card number.
        int odd_sum = 0, even_sum = 0, total = 0;

        // looping through all the digits, decreasing credit_card on every iteration
        for (int i = 1; i <= digits; i++, credit_card /= 10)
        {
            // gets the last digit of credit_card
            int digit = credit_card % 10;

            // performs the necessary tasks on every other digit, starting from the next-to-last one.
            if (i % 2 == 0)
            {
                int prod_dig_sum = 0;

                digit *= 2;
                prod_dig_sum += (digit % 10) + (digit / 10);
                even_sum += prod_dig_sum;
            }

            else
            {
                odd_sum += digit;
            }
        }

        total = odd_sum + even_sum;

        if (total % 10 == 0)
        {
            printf("%s\n", bank);
            return 0;
        }

        else
        {
            printf("INVALID\n");
            return 0;
        }
    }

    printf("INVALID\n");
    return 0;
}

Notes:

The cs50.h library is custom-made by the Harvard staff
the function GetLongLong() is part of that library, and I currently don't know all the details of how this function works
This assignment is fairly early in the course, so we are only supposed to use the most basic tools of C. Basically, only conditions and loops.
I focused mainly on code readability, sometimes on expense of exactness

Having said all that, I am wondering if there is maybe a more elegant way to do all the checking involved in my program. The way it is now, I think I may have over-complicated the process a bit.


texts:
I have to implement a method in which i'm passing two arguments as Mobile number and second one is Message to be sent.

I'm using clickatell for the first time and its successfully sending the messages but is it the right approach of coding for it.

Its the test code what i have posted can i implement this in my production code.

I have cleared the Key out and replaced with stars.

As its a paid service should i go for clickatell or is there any others options to send sms i can try out.

Please review the code.

public class Sms {

    public final String APIKEY = "*************************";
    //private String mobile;

    public void sms_generation(String mobile, String Message) {

        System.out.println("\n\nSTARTING WITH TESTING REST:");

        // Create New object (Assign auth straight away.):
        ClickatellRest click = new ClickatellRest(APIKEY);

        // We cannot test for auth, so lets start with balance:
        System.out.println("TESTING GET BALANCE");
        try {
            double response = click.getBalance();
            System.out.println(response);
        } catch (UnknownHostException e) {
            System.out.println("Host could not be found");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        // Assuming the auth was successful, lets send one message, to one
        // recipient:
        System.out.println("\nTESTING SEND SINGLE MESSAGE");
        try {
            ClickatellRest.Message response = click.sendMessage(mobile, Message);
            System.out.println(response);
            if (response.error != null) {
                System.out.println(response.error);
            } else {

                ClickatellRest.Message msg = click
                        .getMessageStatus(response.message_id);
                System.out.println("ID:" + msg.message_id);
                System.out.println("Status:" + msg.status);
                System.out.println("Status Description:" + msg.statusString);
                System.out.println("Charge:" + msg.charge);
                System.out.println("\nTESTING STOP MESSAGE");
                ClickatellRest.Message msgStatus = click
                        .stopMessage(response.message_id);
                System.out.println("ID:" + msgStatus.message_id);
                System.out.println("Status:" + msgStatus.status);
                System.out.println("Status Description:"
                        + msgStatus.statusString);
            }
        } catch (UnknownHostException e) {
            System.out.println("Host could not be found");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

}


texts:
I was attempting to do some contribution to the underscore-contrib library, and I ended up writing a function that will parse a JavaScript path to later on expose through an API if the path exists or to get the value.

However, a reasonable concern around it is the complexity. (Discussion in the repository, if you're interested.)

I did review other approaches to the problem, but most of them seem to leave valid complex property names behind, or some even are tied to actually retrieving the value at that point.

Can this be made simpler?

// Will take a path like 'element[0][1].subElement["Hey!.What?"]["[hey]"]'
// and return ["element", "0", "1", "subElement", "Hey!.What?", "[hey]"]
function parseJavaScriptPathIntoKeyNames(javascriptPath) {
  var parts = [];
  var terminatorExpected = null;
  var insideIndexer = false;
  var currentPart = "";

  function flushCurrentPart() {
    if (currentPart.length > 0) {
      parts.push(currentPart);
      currentPart = "";
    }
  }

  for (var i = 0; i < javascriptPath.length; i++) {
    var currentChar = javascriptPath[i];
    switch (currentChar) {
    case "[":
      if (!terminatorExpected) {
        flushCurrentPart();

        terminatorExpected = ']';
        insideIndexer = true;
      } else {
        currentPart += currentChar;
      }
      break;
    case "]":
      if (terminatorExpected === "]") {
        flushCurrentPart();

        terminatorExpected = null;
        insideIndexer = false;
      } else {
        currentPart += currentChar;
      }
      break;
    case ".":
      if (!terminatorExpected) {
        flushCurrentPart();
      } else {
        currentPart += currentChar;
      }
      break;
    case "\'":
      if (!terminatorExpected || terminatorExpected === "]") {
        terminatorExpected = "\'";
      } else if (terminatorExpected === "\'" && insideIndexer) {
        terminatorExpected = ']';
      } else if (terminatorExpected === "\'" && !insideIndexer) {
        flushCurrentPart();

        terminatorExpected = null;
      } else {
        currentPart += currentChar;
      }
      break;
    case "\"":
      if (!terminatorExpected || terminatorExpected === "]") {
        terminatorExpected = "\"";
      } else if (terminatorExpected === "\"" && insideIndexer) {
        terminatorExpected = ']';
      } else if (terminatorExpected === "\"" && !insideIndexer) {
        flushCurrentPart();

        terminatorExpected = null;
      } else {
        currentPart += currentChar;
      }
      break;
    default:
      currentPart += currentChar;
    } // switch (currentChar)
  } // for

  flushCurrentPart();

  return parts;
}


texts:
I was solving problem 18  and 67 on Project Euler and came up with an algorithm that actually goes through almost all the possibilities to find the answer in O(n) time. However, ProjecEuler claims that a Brute force solution will take too long.
Many have implemented this problem using trees, dp and what not.

Is my approach not a Brute force?

n = []
for i in range(100):
    n.append(map(int,raw_input().split()))
newresult = [int(59)]
n.pop(0)
for i in range(99):
    x = n.pop(0)
    result = list(newresult)
    newresult =[]
    t = len(x)
    for j in range(t):
        if(j==0):
            newresult.append(result[0]+x.pop(0))
        elif(j==t-1):
            newresult.append(result[0]+x.pop(0))
        else:
            newresult.append(max((result.pop(0)+x[0]),result[0]+x.pop(0)))
print max(newresult)

UPDATE:
here's a idea how my algorithm works (taking max when needed)


texts:
I made a value comparison "programming language" similar to a previous one I made, except this one is based solely on value comparisons.

# Basic value comparison
from operator import *

# Main compare class
class Compare(object):
    def __init__(self):
        self.OpError = "OpError: Invalid operator or brace.\n"
        self.IntError = "IntError: Invalid integers.\n"
        self.StrError = "StrError: Invalid strings.\n"
        self.LstError = "LstError: Invalid list.\n"
        self.BoolError = "BoolError: Invalid boolean.\n"
        self.st_brace = "["
        self.end_brace = "]"
        self.OPERATORS = {
            ">=": ge,
            "<=": le,
            "==": eq,
            "!=": ne,
            ">": gt,
            "<": lt}

    # Compare two integers
    def compareint(self, command):
        if command[1] == self.st_brace and command[3] in self.OPERATORS and command[5] == self.end_brace:
            try:
                print self.OPERATORS[command[3]](
                    int(command[2]), int(command[4]))
            except ValueError:
                print self.IntError
        if command[3] not in self.OPERATORS:
            print self.OpError

    # Compare two strings
    def comparestr(self, command):
        if command[1] == self.st_brace and command[3] in self.OPERATORS and command[5] == self.end_brace:
            try:
                print self.OPERATORS[command[3]](
                    eval(command[2]), eval(command[4]))
            except SyntaxError:
                print self.StrError
        if command[3] not in self.OPERATORS:
            print self.OpError

    # Compare two lists
    def comparelst(self, command):
        if command[1] == self.st_brace and command[3] in self.OPERATORS and command[5] == self.end_brace:
            try:
                print self.OPERATORS[command[3]](
                    eval(command[2]), eval(command[4]))
            except SyntaxError:
                print self.LstError
        if command[3] not in self.OPERATORS:
            print self.OpError

    # Compare two booleans
    def comparebool(self, command):
        if command[1] == self.st_brace and command[3] in self.OPERATORS and command[5] == self.end_brace:
            try:
                print self.OPERATORS[command[3]](
                    eval(command[2]), eval(command[4]))
            except NameError:
                print self.BoolError
        if command[3] not in self.OPERATORS:
            print self.OpError

# Dict containing commands
COMMANDS = {
    "cmpbool": Compare().comparebool,
    "cmplst": Compare().comparelst,
    "cmpint": Compare().compareint,
    "cmpstr": Compare().comparestr,
}

# Read the inputted commands
def read_command(prompt):
    command = raw_input(prompt)
    split_cmd = command.split(" ")
    if split_cmd[0] in COMMANDS:
        COMMANDS[split_cmd[0]](split_cmd)
    if split_cmd[0] not in COMMANDS:
        print "CmdError: Invalid command.\n"

# Run the program
if __name__ == "__main__":
    while True: read_command(">}}>")

Here's how you use it.

>}}>cmpbool [ True == True ]
True
>}}>cmplst [ [""] == [""] ]
True
>}}>cmpint [ 2 == 2 ]
True
>}}>cmpstr [ "Hello" == "Hello" ]
True

What can be improved? How can I shorten the code? Any general improvements are welcome. Just don't change the syntax.


texts: Is there any better way of defining respective data structures to read the sensor data into from driver/application file?

texts:
So I have been wondering about the standard way of structuring your files/code when it comes to reading data from the driver file.
So what I now have is a buffer that's supposed to store the data that we, as user, requested from the driver file. Since we can't pass arrays to the function (decays to a pointer), what I do is have a struct member variable pRxBuff point to rxBuffer array which is located in main instead of defining inside a function because once the function returns, the array is no longer valid, and inside the Read() function, I populate rxBuffer by dereferencing the data at specific index.

typedef struct {
    I2C_TypeDef *pI2Cx;
    I2C_Config_t I2C_Config;
    I2C_State I2C_State;
    uint8_t *txBuffer;
    uint8_t *pRxBuffer;
    uint8_t rxStartIndex;
    uint8_t rxBufferSize;
    uint8_t txBufferLength;
    uint8_t rxBufferLength;
} I2C_Handle_t;

void ProcessData (uint8_t *rxBuffer) {
    uint8_t startIndex = 0;
    uint16_t temp;

    // process data
    uint8_t upperByte = rxBuffer[startIndex] & 0x1F; // mask out the 3 bits
    uint8_t signBit = upperByte & 0x10;

    if (signBit)
    {
        upperByte = upperByte & 0xF;    // clear out the sign bit
        temp = 256 - (upperByte << 4 | rxBuffer[startIndex+1] >> 4);
    }
    else
    {
        temp = upperByte << 4 | rxBuffer[startIndex+1] >> 4;
    }
}

// sensor.c
void ReadData(I2C_Handle_t *I2C_handle)
{
    // start I2C transaction
    while (HAL_I2C_StartInterrupt(I2C_TX_BUSY) != I2C_READY);

    I2C_handle->I2C_State = I2C_INIT;

    // read the data from the sensor
    for (int i = 0; i < I2C_handle->rxBufferSize/2; i++)
    {
        I2C_handle->I2C_State = I2C_INIT;
        while (HAL_I2C_StartInterrupt(I2C_RX_BUSY) != I2C_READY);
    }

    // at this point, I have `rxBuffer` populated with raw data
    // now I need to convert this raw data into human-readable

    for (int i = 0; i < I2C_handle->rxBufferSize; i+=2)
    {
        ProcessData(I2C_handle->pRxBuffer, i); // currently not storing processed data anywhere
    }
}

// main.c
const int bytesToRead = 6;
static uint8_t rxBuffer[bytesToRead];
I2C_Handle_t i2c;

void I2C_Initilization()
{
    i2c.pI2Cx = I2C1;
    i2c.I2C_Config.I2C_AckControl = I2C_ACK_ENABLE;
    i2c.I2C_Config.I2C_SCLSpeed = I2C_SCL_SPEED_SM;
    i2c.I2C_Config.I2C_DeviceAddress = MCP9808_ADDR;
    i2c.I2C_Config.I2C_FMDutyCycle = I2C_FM_DUTY_2;
    I2C_Init(&i2c);
}

uint16_t read_temp(uint8_t interrupt)
{
    uint16_t temperature;

    i2c.txBuffer = txBuffer;
    i2c.txBufferLength = txSize;
    i2c.pRxBuffer = rxBuffer;
    i2c.rxStartIndex = 0;
    i2c.rxBufferLength = BYTES_PER_TRANSACTION;
    i2c.rxBufferSize = bytesToRead;

    if (interrupt == SET)
    {
        temperature = read_temp_interrupt(&i2c);
    }
    else
    {
        read_temp_polling(&i2c, bytesToRead);
    }
    return temperature;
}

int main(void) {
    I2C_Initilization();
    read_temp(SET);
}

Issues with this:

though I have been able to populate the rxBuffer which I can access
in the main, is this still the right way to do it?
what if rxBuffer is of different size than what the processed data
would need. For e.g: 2 raw bytes represent one processed decimal
value. How do I avoid creating two different buffers each for storing
raw and processed data?
With this approach, I had to create a separate member variable
rxStartIndex to keep track of the index where the data is to be
written.


texts: Switching font and background color on button click

texts:
I am currently building a web app where I need to randomly switch the font and color of a title (inside the #content div) and the background of the page every time a button is clicked.

I wrote the following code that works perfectly, but I'm wondering if it could be optimized (or at least written in a more elegant way).

// Switch font randomly
var font = ["lobster", "shadows", "oswald", "josefin", "gloria", "pacifico"];
var color = ["blue", "purple", "yellow", "red", "orange", "green"];
var background = ["bg-blue", "bg-purple", "bg-yellow", "bg-red", "bg-orange", "bg-green"];

$("#try-me").click(function() {
    $("#content")
        .hide()
        .removeClass()
        .addClass(font[Math.floor(Math.random()*font.length)]) // Font
        .addClass(color[Math.floor(Math.random()*color.length)]) // Color
        .fadeIn(600);

    $("html")
        .removeClass()
        .addClass(background[Math.floor(Math.random()*background.length)]); // Background
});


texts:
Is there anything wrong with the following implementation of an in-memory top-ten bought products tracker?

public class Main {

    private static List<Integer> topTenItems = Collections.synchronizedList(new ArrayList<Integer>(Collections.nCopies(10, 0)));
    private static List<Integer> topTenScores = Collections.synchronizedList(new ArrayList<Integer>(Collections.nCopies(10, 0)));
    private static ConcurrentMap<Integer,Integer> itemsScores;

    public static void main(String[] args)
    {
        itemsScores = new ConcurrentHashMap<Integer,Integer>();

        for (int i = 0; i < 1000000; i++)
        {
            Integer boughtItem = new Integer((int)(Math.random() * 100) + 1);
            bought(boughtItem);
        }

        assert isSorted(topTenItems);
        assert isSorted(topTenScores);

        System.out.println("items: " + getTopTen());
        System.out.println("scores:" + topTenScores);

    }

    public static boolean isSorted(List<Integer> l)
    {
     for (int i = 1; i < l.size(); i++)
     {
         if (l.get(i - 1) < l.get(i))
             return false;
     }
     return true;
    }

    public static void bought(Integer itemId)
    {
        Integer oldScore = itemsScores.get(itemId);
        Integer newScore;
        if (oldScore == null)
            newScore = 1;
        else
            newScore = oldScore + 1;

        itemsScores.put(itemId,newScore);
        doTopTen(itemId,newScore);
    }

    private static void doTopTen(Integer itemId, Integer newScore)
    {
        if (topTenItems.contains(itemId))
        { // we have this already; up the score, check the position
            int itemIndex = topTenItems.indexOf(itemId);
            if (itemIndex > 0)
            { // not top already
                if (topTenScores.get(itemIndex - 1) < newScore)
                {
                    // move to one position above
                    Integer tempProd = topTenItems.get(itemIndex - 1);
                    Integer tempScore = topTenScores.get(itemIndex - 1);
                    topTenItems.set(itemIndex - 1, itemId);
                    topTenScores.set(itemIndex - 1, newScore);
                    topTenItems.set(itemIndex, tempProd);
                    topTenScores.set(itemIndex, tempScore);
                }
                else
                { // just update the score
                    topTenScores.set(itemIndex, newScore);
                }
            }
            else
            {
                topTenScores.set(0,newScore);
            }
        }
        else
        {
            for (int i = 0; i < 10; i++)
            {
                // left to right
                if (topTenScores.get(i) <= newScore)
                {
                    topTenItems.add(i, itemId);
                    topTenScores.add(i, newScore);
                    topTenItems.remove(10);
                    topTenScores.remove(10);
                    break;
                }
            }
        }

    }

    public static List<Integer> getTopTen()
    {
        return topTenItems;
    }
}


texts: Calculating area of different figures on a case by case basis

texts:
My program looks for the area of the figures, depending on the value of the variable а.

area -> triangle

area -> triangle2

area -> square

area -> rhombus
I want to get constructive criticism about the structure of the code and what can be redone. The program is written in the Python programming language.

while True:
    class S():
        print("Для выхода нажмите Enter")
        a = int(input("1. Площадь прямоугольного тр. \n2. Площадь равнобедренного тр. \n3. Площадь квадрата \n4. Площадь ромба  "))
        if a == 1:
            print("Это нахождение площади прямоугольного треугольника")
            a1 = float(input("Введите первый катет  "))
            b1 = float(input("Введите второй катет  "))
            class Triangle1():
                    def  __init__(self, a1, b1):
                        self.a = a1
                        self.b = b1
                    def area(self):
                        return (self.a * self.b) / 2
            Striangle1 = Triangle1(a1,b1)
            print("Площадь равна = ",Striangle1.area())
        elif a == 2:
            print("Это нахождение площади равнобедренного треугольника")
            a2 = float(input("Введите основание  "))
            b2 = float(input("Введите высоту  "))
            class Triangle2():
                    def  __init__(self, a2, b2):
                        self.a2 = a2
                        self.b2 = b2
                    def area(self):
                        return (self.a2/2)*self.b2
            Striangle2 = Triangle2(a2,b2)
            print("Площадь равна = ",Striangle2.area())
        if a == 3:
            print("Это нахождение площади квадрата  ")
            a3 = float(input("Введите сторону  "))
            class Hexagon():
                def __init__(self, a3):
                    self.a3 = a3
                def area(self):
                    return self.a3**2
            Shexagon = Hexagon(a3)
            print("Площадь равна = ",Shexagon.area())
        elif a == 4:
            print("Это нахождение площади ромба")
            a4 = float(input("Введите 1 диагональ  "))
            b4 = float(input("Введите 2 диагональ  "))
            class Romb():
                def  __init__(self, a4, b4):
                    self.a4 = a4
                    self.b4 = b4
                def area(self):
                    return (self.a4*self.b4)/2
            Sromb = Romb(a4,b4)
            print("Площадь равна = ",Sromb.area())

Drive link to the code


texts:
I made this game called Jumpol, about you trying to jump over as many obstacles and collect as many coins as possible. The coins can be used to change your ball and revive yourself so you get another shot on the track.

I've released this game on the iOS and Android apps stores and some users are reporting that the jumping is laggy and feels slow.

I tested the game on my 4 year old Android and it ran fine, plus I tested it on a few iOS devices and it also works fine. Is there any ways to make this code run smoother?

Links to game (If you want to test)

Android Link

iOS Link

float speed = 12;                // Speed of player.
float thrust = 34;              // Jump force.
float gravity = -6.18f;         // Gravity force.

bool isGrounded = false;        // If on ground or not.

private void Awake () {

    Instance = this;

}

private void Start () {

    rb = GetComponent<Rigidbody> ();

}

private void Update () {

    if (Application.platform == RuntimePlatform.WindowsEditor) DesktopControls ();

    if (Application.platform == RuntimePlatform.IPhonePlayer ||
        Application.platform == RuntimePlatform.Android) MobileControls ();

}

private void FixedUpdate () {

    if (GameManager.Instance.started) {

        Gravity ();
        Move ();
    }

}

private void OnCollisionEnter (Collision collision) {

    if (collision.gameObject.tag == "Obstacle") {

        gameObject.SetActive (false);

    }

    if (collision.gameObject.tag == "Ground") {
        isGrounded = true;
    }

}

private void OnCollisionExit (Collision collision) {

    if (collision.gameObject.tag == "Ground") {
        isGrounded = false;
    }

}

private void OnTriggerEnter (Collider other) {

    if (other.gameObject.tag == "Collectable") {

        other.gameObject.SetActive (false);

    }

}

/// <summary>
/// Controls for mobile devices.
/// </summary>
private void MobileControls () {

    for (int i = 0; i < Input.touchCount; ++i)
        if (Input.touchCount > 0 && Input.GetTouch (i).phase == TouchPhase.Began) Jump ();

}

/// <summary>
/// Controls for desktops.
/// </summary>
private void DesktopControls () {

    if (Input.GetMouseButtonDown (0)) Jump ();

}

/// <summary>
/// Makes player jump.
/// </summary>
private void Jump () {

    if (isGrounded) {
        rb.velocity += new Vector3 (0, thrust, 0);
    }

}

/// <summary>
/// Adds gravity.
/// </summary>
private void Gravity () {

    rb.velocity += new Vector3 (0, gravity, 0);

}

/// <summary>
/// Moves player.
/// </summary>
private void Move () {

    rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, speed);

}


texts: Generic message in Elm for simple model updates

texts:
In the Elm examples I have seen for form handling, they attach each input element with an update handler that sends out a very specific message to update the model according to the new input state.

So you end up with a lot of message definition in your Msg union type.

Alternatives I have seen for "dynamic" or complex forms use generic handlers that can work with Dict of data, keyed by form input id, at the expense of some type-safety.

I was thinking I can have (at least for simple handlers that only update the model in straightforward ways and do not need to send Commands to the runtime engine) a middle-ground with a generic SimpleModelUpdate message that takes a mutator function as its payload to describe what it is actually supposed to do.

Something like

 type Msg =  ....
   | SimpleModelUpdate (Model -> Model)

 update model msg = ...
   case SimpleModelUpdate mutation ->
     (mutation model, Cmd.none)

 Html.button
  [onClick = SimpleModelUpdate (\m -> {m | counter = counter + 1})]
  [text "Increase"]

That seems to work. And I like it because I do not have to spread the code for trivial updates all over the place (I can reserve dedicated message types for the really "important" stuff).

Is this bad design? Are there other issues that I am not seeing?


texts: A single function for implementing Newton forward and backward polynomial interpolation

texts:
On various websites, I've come across a lot of realizations of Newton polynomial interpolation that use separate functions for forward and backward interpolation, respectively. Such solutions seem ugly to me because the functions look pretty much the same.

For a single Newton interpolation function, I treat the backward interpolation case as forward interpolation with the data points written in reverse order. Usually the data points come already sorted in ascending order by x values, so the reverse order means simply going through the data points from right to left over an interval.

With all these in mind, my Newton interpolation function in C is:

/*
Error codes:
-2 - malloc() error
-1 - range check error
 0 - no error (success)
*/

// The necessary typedefs

typedef struct {
    int points;
    double *xList, *yList;
} DataTable;

typedef struct {
    double *coeff;
    int degree;
    double *xList;
} NewtonPoly;

// I've excluded the code for checking if the data table is filled properly.

int getNewtonPoly(DataTable *table, int nodes, NewtonPoly *poly)
{
    int n = abs(nodes);
    int points = table->points;
    if (n > points || n == 0)
        return -1;

    double *result = (double *)malloc(n * sizeof(double));
    if (result == NULL)
        return -2;
    double *tmp = (double *)malloc(n * sizeof(double));
    if (tmp == NULL)
        return -2;
    double *xList = (double *)malloc(n * sizeof(double));
    if (xList == NULL)
        return -2;

    if (nodes > 0)
        for (int i = 0; i < n; ++i) {
            xList[i] = table->xList[i];
            tmp[i] = table->yList[i];
        }
    else
        for (int i = points - 1, j = 0; i >= points - n; --i, ++j) {
            xList[j] = table->xList[i];
            tmp[j] = table->yList[i];
        }

    result[0] = tmp[0];
    for (int i = 1; i < n; ++i) {
        for (int j = 0; j <= n - i - 1; ++j)
            tmp[j] = (tmp[j + 1] - tmp[j]) / (xList[j + i] - xList[j]);
        result[i] = tmp[0];
    }

    poly->degree = n - 1;
    poly->coeff = result;
    poly->xList = xList;
    free(tmp);
    return 0;
}

Are there some better approaches to this problem?


texts:
I'm working on modernizing legacy ASP.NET WebForms site which heavily relies on doing AJAX request for client-side rendering. Without the use of vue-cli compiling .vue file with ease is not possible (or it is?).
So what I'm trying to do is to replicate single-file components and folder structure as much as possible. Result in a folder structure like this (irrelevant files are omitted).
├── Scripts
|   ├── app.js
|   └── components
|       ├── CustomCard.js
|       └── CustomButton.js
├── Default.aspx
└── ...

And in order to replicate the single-file components the content inside will look like this.
Default.aspx
<%@ Page Title="Vue" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Vue._Default" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI.WebControls" Assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>

<%-- This will be in the head tag speficied in Site.Master --%>
<asp:Content ID="HeadContent" ContentPlaceHolderID="PageHeadContent" runat="server">

</asp:Content>

<%-- This will be in the body tag speficied in Site.Master --%>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

        <custom-card></custom-card>

</asp:Content>

Scripts/app.js
import CustomCard from './components/CustomCard.js'

var app = new Vue({
    el: '#app',
    components: { CustomCard },
})

Scripts/components/CustomCard.js
import CustomButton from './CustomButton.js'

export default {
    name: 'custom-card',
    components: { CustomButton },
    data: function () {
        return {
            cardText: 'This is card body',
        }
    },
    template: `

{{ cardText }}

            <custom-button></custom-button>

`
}

Scripts/components/CustomButton.js
export default {
    name: 'custom-button',
    data: function () {
        return {
            buttonText: 'I am child button!',
        }
    },
    template: `<button class="btn btn-success">{{ buttonText }}</button>`
}

I wanted to know can the structure be improved or is there a downside or limitations of doing this? Thanks.


texts: Determine if .deb package is installed using Bash

texts:
I was able to use dpkg-query to determine if a package is installed on Ubuntu, but it's a bit of a mess because the name used to install the package doesn't always align with what it's installed as. For instance, gnutls-dev is installed under libgnutls-dev...

Any suggestions on how I could clean this up a bit?

function isInstalled() {
    if dpkg-query -W -f'${Status}' "$1" 2>/dev/null | grep -q "ok installed" || dpkg-query -W -f'${Status}' "lib$1" 2>/dev/null | grep -q "ok installed"; then
        echo 1;
    fi

    echo 0
}


texts:
I am working on writing a discrete random variable generator function in excel vba. I've pulled this off a number of ways but here is the one I like the most.

Imagine in excel we have the following in cells A1:B3

red     5
blue    7
yellow  3

The following code is modeled as follows. Imagine drawing a line going from 0 to 15 (where 15 is 5 + 7 + 3). The line is red from [0,5) and blue from [5,12) and yellow from [12,15). And you pick a uniformly distributed random number, x, from 0 to 15. And wherever on the line x falls, that is the color that wins.

Here is the function:

Function discrete(r1 As Range, r2 As Range)

  'shrink column ranges to contiguous cells
  Set r1 = Range(r1(1), r1(1).End(xlDown))
  Set r2 = Range(r2(1), r2(1).End(xlDown))

  'convert ranges to arrays
  Dim arr1, arr2 As Variant
  arr1 = r1.Value
  arr2 = r2.Value

  Dim n As Long
  n = Application.Sum(arr2) 'sum total of 2nd array

  Dim x As Double
  x = n * Rnd() 'generate a random number 0 <= x < n

  Dim min, max As Double
  min = 0
  max = 0

  Dim i As Long
  For i = LBound(arr1, 1) To UBound(arr1, 1) 'where on the line x falls
      max = max + arr2(i, 1)
      If x >= min And x < max Then
          discrete = arr1(i, 1)
      End If
      min = min + arr2(i, 1)
  Next i

End Function

I'm looking for some critique of my code and approach.

Assuming I'm not picking from 1000 values (column a), is it reasonable that I convert the ranges to arrays? Is this a time saving step? Or should I just work with the ranges? What I mean is, does this step pay for itself computationally given that I may always be working with only a few rows of data? Or might it be worth it solely on that basis that I may indeed supply this function with large ranges?
Even if you supply a full column, ie. discrete(range("a:a"), range("b:b")), the range inside the function is reset to only those cells that are contiguous starting from the first cells of the supplied ranges. Is that a reasonable approach?
The algorithm itself relies on a for loop and 2 simple variables (min, max). I this a lightweight enough approach? Or are there some generally accepted practices I'm not aware of?


texts: Logging a user in and creating a session

texts:
I have a bunch of functions that return promises and need to chain them together. However, it's currently difficult to read and I would expect it to be even harder to maintain.

I have a function that performs the following actions:

Logs off any inactive users.
Verifies a user's credentials.
Creates a session and logs the user in.

Is there a better way?

generateToken: function (email, password) {
    return new Promise((resolve, reject) => {
        //Kill inactive sessions first
        module.exports.destroyInactive()
        .then(() => {
            //Verify that the password matches the user
            users.checkPassword(email, password, sharedSecret)
            .then((user) => {
                //Check if there is another user already signed in, if there is then we can't
                //produce another token until they are signed out.
                signedon.getByEmailAddressThisProcess(email)
                .then((result) => {
                    let rows = result[0];

                    if (rows.length > 0)
                        return reject('A user with email: ' + email + ' is already logged in.');

                    //Get the current XPROCESS.
                    xprocess.getByProcessId(process.pid)
                    .then((xproc) => {
                        //Create a brand new session object
                        let session = generateSession(user);

                        //Save the session in the signed on table.
                        signedon.signin(session, xproc.pid)
                        .then(() => {
                            resolve(parseSessionToToken(session));
                        },
                        reject);
                    },
                    reject);
                },
                reject);
            },
            reject);
        },
        reject);
    });
},


texts: openMP implementation of loop until predicate met

texts:
I want to implement in openMP a loop that terminates when a certain condition holds. In serial code the function body would simply be

for(; begin < end; ++begin)
    if(pred(begin))
        return true;
return false;

The openMP version may differ in two respects: (1) concurrent function calls to pred() are not truncated and (2) the order of calls to pred() may be anything. However, it must not be assumed that calls to pred() are all equally expensive.

/// loop until pred(i) returns true;
/// \return  whether loop was terminated
template<typename index, typename predicate>
bool loop_until(index begin, index end, predicate const&pred)
{
    const index chunk_size = std::max(index(1), index((begin-end)/(8*omp_get_num_threads())));
    std::atomic<bool>  stop{false};
    std::atomic<index> next_chunk{begin};
#   pragma omp parallel
    {
        for(index beg_chunk = next_chunk.fetch_add(chunk_size);
            beg_chunk < end && !stop;
            beg_chunk = next_chunk.fetch_add(chunk_size))
            for(index end_chunk = std::min(beg_chunk+chunk_size,end);
                beg_chunk < end_chunk && !stop;
                ++beg_chunk)
                if(pred(beg_chunk))
                    stop = true;
    }
    return stop;
}

I'm a bit rusty on openMP hence my questions:

Is the code correct?
Is there a more openMPish or better way to code this?


texts:
Here I have two DataTables:

dtTotalDateRangeExcludeSundays
dtAbsentsLeavesHolidaysWorks

Each has 10k+ values, and I need to delete matched rows.

foreach (DataRow rw in dtTotalDateRangeExcludeSundays.Select())
 {
    DateTime dateFromRange=Convert.ToDateTime(rw[0].ToString());
    string strPrnt = dateFromRange.ToShortDateString();
    foreach (DataRow row in dtAbsentsLeavesHolidaysWorks.Select())
    {
      DateTime getDate = Convert.ToDateTime(row[0].ToString());
      string strchild = getDate.ToShortDateString();
       if (strPrnt == strchild)
       {
          rw.Delete();
        }
       }
 }

I want to know if any better alternative suggestion, because the foreach loop takes time when bulk data is there.  I am not good with Linq, so I want to know if any Linq tricks work.


texts:
What I'm doing:

Searching in current directory for a set of files.
Filtering the set.
Searching through the filtered set of files for a specific line sequence.
Write to an output file that line along with the line that directly preceded it and the file in which it is found.

There's no actual purpose to this besides practice, so I'm just reading dummy data. This is my first C++ program and it's especially challenging since it uses the rogue-wave library rather than much of the standard ones (this runs on an embedded device).

The program:

#include <windows.h>
#include <fstream.h>
#include <rw/collstr.h>
#include <rw/sortvec.h>
#include <rw/rstream.h>
#include <rw/regexp.h>

RWSortedVector retrieveFiles();
void searchAndLogFile(RWCollectableString filename, ofstream &outputCSV);

int main()
{
    RWSortedVector fileVecor = retrieveFiles();
    RWCollectableString* file;
    RWSortedVectorIterator next(fileVecor);
    ofstream outputCSV("temp_output.csv");
    while (file = (RWCollectableString*) next()) {
        searchAndLogFile(*(file), outputCSV);
    }
    fileVecor.clearAndDestroy();
    outputCSV.close();

    return 0;
}

void searchAndLogFile(RWCollectableString filename, ofstream &outputCSV)
{
    RWCString line;
    RWCString previousLine;
    ifstream file(filename);
    RWCRegexp re("<TEST>\\.+</TEST>");
    while(line.readLine(file))
    {
        RWCString result = line(re);
        if (result.length() > 0)
        { // if matching line is found
            outputCSV << filename << "," << line << "," << previousLine << endl;
        }
        previousLine = line;
    }
}

// Produces a list of relevant file names
RWSortedVector retrieveFiles()
{
    RWSortedVector fileVector;
    system("dir *.cr | sort > temp.txt");

    RWCString line;
    ifstream file("temp.txt");
    // Regular expression to ensure we only retrieve desired files
    RWCRegexp re("test[0-9]+\\.cr");
    while(line.readLine(file))
    {
        RWCString result = line(re);
        if (result.length() > 0)
        { // if file name matches
            fileVector.insert(new RWCollectableString(result));
        }
    }

    file.close();
    system("del temp.txt");
    return fileVector;
}

Notes:

To my knowledge, there's no way to get files in the directory with my constraints. Employing the directory system command with an output file is an effective work-around.

Concerns:

Direct access to pointers and references is a novel concept and if there's anywhere that its use would benefit.
Any error handling I should be doing.


texts: Animated scrolling to a place in the same webpage

texts:
I'm just beginning web design, and I've come up with this code to scroll to a place in the same page.

I don't know if this can or should be improved much longer, so I'm asking for any tips that can make this code better.

I know it's messy, but I will clean it later.  I just want to know if there's a better method.

$(document).ready(function(){
$('#Tecnologia').click(function(){
$(".ConHome").css('transition','all 0.4s ease');
$(".ConHome").css('transform','translateY(-50em)');
$("#BlankSpaceMenu").css('transition','all 0.4s ease');
$('#BlankSpaceMenu').css('transform','translateY(-50em)');
$(".ConTech").css('transition','all 0.4s ease');
$(".ConTech").css('transform','translateY(-50em)');
$(".TopHeader").css('transition','all 0.4s ease');
$(".TopHeader").css('border-bottom-color','rgba(0,0,255,1)');
})})
#BlankSpaceMenu{
position:relative;
height:7em;
width:100%;
background-color:rgba(0,0,255,1);
z-index:9;
}
.Container{
position:relative;
color:rgba(255,255,255,1);
}
.TopHeader{
 position:fixed;
background-color:rgba(255,153,0,1);
color:rgba(255,255,255,1);
height:7em;
width:100%;
z-index:10000;
border-bottom:rgba(0,0,0,1) dashed 10px;
}
.ConHome{
position: relative;
background-color: rgba(0,0,0,1);
color: rgba(255,255,255,1);
height: 50em;
width: 100%;
z-index:10;
}
.ConTech{
position: relative;
background-color:rgba(0,0,255,1);
color:rgba(255,255,255,1);
height: 50em;
width: 100%;
z-index:8;
}

Tecnologia

....

...


texts:
public class InfoSerializer : IInfoSerializer
{
    private static readonly ILogger _logger = LoggerFactory.Instance.GetCurrentClassLogger();

    public string Serialize(BackgroundJobInfo info)
    {
        var stringBuilder = new StringBuilder();

        using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
        {
            var writer = new XmlTextWriter(stringWriter);
            new DataContractSerializer(typeof(BackgroundJobInfo)).WriteObject(writer, info);
        }

        return stringBuilder.ToString();
    }

    public BackgroundJobInfo Deserialize(string info)
    {
        var dataContractSerializer = new DataContractSerializer(typeof(BackgroundJobInfo));
        using (var xmlTextReader = new XmlTextReader(info, XmlNodeType.Document, new XmlParserContext(null, null, null, XmlSpace.None)))
        {
            try
            {
                var result = (BackgroundJobInfo)dataContractSerializer.ReadObject(xmlTextReader);

                return result;
            }
            catch (Exception e)
            {
                // hopefully, will never happen
                _logger.ErrorException(e, "Error when deserializing a BackgroundJobInfo object from string <{0}>", info);
                return null;
            }
        }
    }
}

Is it good serializer? Maybe I can improve it or I miss something?


texts: Random distributions in Go with inheritance

texts:
I am currently discovering Golang, and I try to implement some random variable generation functions similar to R functions.

To avoid code repetition, I'd like to use inheritance, which is quite complex with Go at first sight.

Each variable implements a x.R() method, which generate a random value following x distribution.

I'd like to implement x.Rn(n int), which simply returns an array of n random values. It is therefore the same for any random variable, as it simply calls x.R() n times.

So far, my implementation is as following:

// Continuouser Implements a continous law
type Continuouser interface{
    R() float64
    D(value float64) float64
    P(value float64) float64
}
// Continuous A Continuous law
type Continuous struct{
    Continuouser
}
// Rn Generate n draws of a continuous random variable
func (c Continuous) Rn(n int) (res []float64){
    if (n < 0){
        panic(errors.New("n must be positive"))
    }
    res = make([]float64,n)
    for i := 0; i < n; i++{
        res[i] = c.R()
    }
    return
}

And here is how I implement a law :

// NewBern Generate a new variable following a Bern(p) law
func NewBern(p float64) (x *Bern){
    x = &Bern{Discrete{},p,1.-p}
    // Discrete.discreter self reference X
    x.Discrete = Discrete{x}
    return
}

// R Generate a random value following the same Bernouilli distribution as x
func (x Bern) R() int64 {
    var u = NewStdUnif()
    // maybe there is a more idomatic way link int(u.R()<p)
    if u.R() < x.p {
        return 1
    }
    return  0
}

So, x does embed an anonymous continuous struct, which in turn embeds a reference to x, that implements the method R().

You can have access to the full repo here on GitHub.

It does work and avoid code redundancy, but is that the idiomatic Golang way?


texts:
I have the following code, which is working (?), but I guess I can do it simpler and more elegantly. I need to invoke a method when everything is completed (channelsVideos array is filled). The console.log function at the end runs and display the array. The objects are in it, but it is displayed as Array[0] in the console. All I want is to be sure that all the data is donwloaded before creatign the UI elements.

menuItemsAndTabs: [],
categoriesAndChannels: [],
channelsVideos: [],

...
...
...

getChannelsAndVideos: function() {
    $.each(MyApp.menuItemsAndTabs[1].menuItem.tabs, function(index, value) {
        var _id = value._id;
        var ajaxGetChannels = $.getJSON(MyApp.CONSTANTS.URLS.API + "/api/assets/" + _id, function(response) {

    }).done(function(response) {
        $.each(response.channels, function(ind, val) {
            MyApp.categoriesAndChannels.push({
                channel: {
                    categoryName: value.label,
                    channelName: val.channelId,
                    channelId: val._id
                }

            });
            var ajaxGetVideos = $.getJSON(MyApp.CONSTANTS.URLS.API + "/videos/channel/" + val.channelId, function(response) {

            }).done(function(response) {
                $.each(response.videos, function(ind, val) {
                    MyApp.channelsVideos.push({
                        channelName: val.channelId,
                        videos: {
                            title: val.title
                        }
                    });
                });
            });
        });

        });
    });

console.log(MyApp.channelsVideos);

},


texts:
Problem:

Censor Unwanted words.

Solution:

Note: I am beginner and self learning programming by reading the book "Programming: Principles and Practises" by Bjarne Stroustrup and this a "try this" exercise from chapter 4.

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> words;

    std::cout << "Enter a list of words.\n";
    std::string temp;

    while(std::cin>>temp){
        words.push_back(temp);
        }

    for(auto w : words){
        if(w=="idiot"||w=="nonsense"||w=="hyper"){
            std::cout<<"BlEEP"<<" ";
        }
        else std::cout<<w<<" ";
    }
}

Sample Test run.


texts: AES-256-CBC encrypt and decrypt files in Python

texts:
I wrote a simple algorithm to encrypt and decrypt files in Python using aes-256-cbc.

from Crypto import Random
from Crypto.Cipher import AES
import base64

def pad(s):
    return s + b"\0" * (AES.block_size - len(s) % AES.block_size)

def encrypt(message, key, key_size=256):
    message = pad(message)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return iv + cipher.encrypt(message)

def decrypt(ciphertext, key):
    iv = ciphertext[:AES.block_size]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plaintext = cipher.decrypt(ciphertext[AES.block_size:])
    return plaintext.rstrip(b"\0")

def encrypt_file(file_name, key):
    with open(file_name, 'rb') as fo:
        plaintext = fo.read()
    plaintext = base64.b64encode(plaintext)
    print(plaintext)
    enc = encrypt(plaintext, key)
    with open("file.txt" + ".enc", 'wb') as fo:
        fo.write(enc)

def decrypt_file(file_name, key):
    with open(file_name, 'rb') as fo:
        ciphertext = fo.read()
    dec = decrypt(ciphertext, key)
    dec = base64.b64decode(dec)
    with open(file_name[:-4]+ ".dec", 'wb') as fo:
        fo.write(dec)
    return dec.decode()

key = b'1234sfsfdsafasdf'

encrypt_file('file.txt', key)
decrypt_file('file.txt.enc', key)

However, I am definitely not a cryptography expert and I suppose my code may be missing something.

Is it safe to use this code for encryption of my files and what could be improved in this algorithm?

Also what do you think about This Implementation, is it secure and could be used in production?


texts: Generate String with Random Consonants and Vowels

texts:
Purpose

This problem comes from this dailyProgrammer subreddit challenge.

The task is to take an input of C / cs and V / vs and to replace Cs with random consonants and Vs with random vowels (English alphabet) while keeping the case the same. Y is not considered a vowel in this case.

Example:

CcVvv => BgAoi
ccVVV => zqUUE

Implementation

For this case, I've put all methods in the same class - in reality, I might split these methods out into different classes.

Edit: I forgot to throw an exception in generateRandomString when the isValidCharacter method is called and returns false.

public class RandomCharacterReplacer {
  public static final char C = 'C';
  public static final char V = 'V';
  public static final List<Character> CONSONANTS = new ArrayList<>(
      Arrays.asList('B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z')
  );
  public static final List<Character> VOWELS = new ArrayList<>(
      Arrays.asList(
          'A', 'E', 'I', 'O', 'U'
      )
  );

  private static boolean isValidCharacter(final char c) {
    final char upperCaseChar = Character.toUpperCase(c);
    return upperCaseChar == C || upperCaseChar == V;
  }

  public static AlphabetCharacterCase returnAlphabetCharacterCase(final char c) {
    if (!Character.isAlphabetic(c)) {
      throw new RuntimeException("character is non-alphabetic");
    }

    if (Character.isUpperCase(c)) {
      return AlphabetCharacterCase.UPPER;
    }

    if (Character.isLowerCase(c)) {
      return AlphabetCharacterCase.LOWER;
    }

    throw new RuntimeException("unexpected character case");
  }

  public static AlphabetCharacterType returnAlphabetCharacterType(final char c) {
    if (!Character.isAlphabetic(c)) {
      throw new RuntimeException("character is non-alphabetic");
    }

    final char upperCaseChar = Character.toUpperCase(c);
    if (upperCaseChar == C) {
      return AlphabetCharacterType.CONSONANT;
    }

    if (upperCaseChar == V) {
      return AlphabetCharacterType.VOWEL;
    }

    throw new RuntimeException("unexpected character type");
  }

  public static char returnRandomCharacter(final List<Character> characterList) {
    if (characterList.isEmpty()) {
      throw new IllegalArgumentException("character list must be non-empty");
    }
    final Random random = new Random();
    return characterList.get(random.nextInt(characterList.size() - 1));
  }

  public static List<Character> returnAlphabetCharacterTypeList(final AlphabetCharacterType characterType) {
    switch (characterType) {
      case CONSONANT: {
        return CONSONANTS;
      }

      case VOWEL: {
        return VOWELS;
      }

      default: {
        throw new RuntimeException("unexpected character type");
      }
    }
  }

  public static char generateRandomCharacter(final AlphabetCharacterCase alphabetCharacterCase, final AlphabetCharacterType characterType) {
    final List<Character> characters = returnAlphabetCharacterTypeList(characterType);
    switch (alphabetCharacterCase) {
      case UPPER: {
        return returnRandomCharacter(characters);
      }

      case LOWER: {
        return Character.toLowerCase(returnRandomCharacter(characters));
      }

      default: {
        throw new RuntimeException("unexpected character case");
      }
    }
  }

  public static String generateRandomString(final String input) {
    final char[] chars = input.toCharArray();
    final StringBuilder stringBuilder = new StringBuilder();
    for (final char c : chars) {
      if (isValidCharacter(c)) {
        final AlphabetCharacterCase alphabetCharacterCase = returnAlphabetCharacterCase(c);
        final AlphabetCharacterType alphabetCharacterType = returnAlphabetCharacterType(c);
        stringBuilder.append(generateRandomCharacter(alphabetCharacterCase, alphabetCharacterType));
      }
    }

    return stringBuilder.toString();
  }
}


texts:
I'm working on a logger that has a name of the module that called the logger (when I create an instance of a logger in my program, I call LoggingHandler(__name__)) to send all the messages, including info and debug, to the log file, and print the messages specified by max_level to console (so, by default, it will not print info and debug messages to console, but will still write them into file).

The problem came when I was managing levels. If I set level in basicConfig to "WARNING", then it will not print info and debug to file, even though I've set fh.setLevel(logging.DEBUG). It just won't go to levels lower than the one specified in basicConfig. Okay, I could just go ahead and specify filename in basicConfig to make it output to file, but I want a RotatingFileHandler to take care of it (because I require its rollover functionality). So, I've set level in basicConfig to "NOTSET", the lowest one possible. Things go better now except one problem. The output to console doubles. It prints

[2016-08-29 10:58:20,976] __main__: logging_handler.py[LINE:51]# WARNING   hello
[2016-08-29 10:58:20,976] __main__: logging_handler.py[LINE:51]# WARNING   hello
[2016-08-29 10:58:20,977] __main__: logging_handler.py[LINE:48]# ERROR     hola
[2016-08-29 10:58:20,977] __main__: logging_handler.py[LINE:48]# ERROR     hola
[2016-08-29 10:58:20,977] __main__: logging_handler.py[LINE:54]# INFO      info message
[2016-08-29 10:58:20,977] __main__: logging_handler.py[LINE:57]# DEBUG     debug message

So, the global logger does the output and the StreamHandler does. I need to prevent the global logger from outputting anything. So I redirect its output to a "dummy" class Devnull. Now the code works exactly as I need, but it feels like such approach is what they call "bodging". So, I'd like to know if there's a better way to write this code.

#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from os import path, makedirs

LOGS_DIR = "logs"
DEBUG_FILE_NAME = 'debug.log'
MAX_LOG_SIZE = 10*1024*1024
BACKUP_FILES_AMOUNT = 3
LOG_FORMAT = u'[%(asctime)s] %(name)s: %(filename)s[LINE:%(lineno)d]# %(levelname)-8s  %(message)s'

class Devnull(object):
    def write(self, *_, **__): pass

class LoggingHandler:
    def __init__(self, logger_name, max_level="WARNING"):
        makedirs(LOGS_DIR, exist_ok=True)

        logging.basicConfig(format=LOG_FORMAT,
                            level="NOTSET",
                            stream=Devnull(),
                            )

        self.main_logger = logging.getLogger(logger_name)

        # create file handler which logs even debug messages
        fh = RotatingFileHandler(path.join(LOGS_DIR, DEBUG_FILE_NAME),
                                 maxBytes=MAX_LOG_SIZE, backupCount=BACKUP_FILES_AMOUNT)
        fh.setLevel(logging.DEBUG)
        # create console handler with a higher log level
        ch = logging.StreamHandler()
        ch.setLevel(max_level)
        # create formatter and add it to the handlers
        fmter = logging.Formatter(LOG_FORMAT)
        fh.setFormatter(fmter)
        ch.setFormatter(fmter)
        # add the handlers to the logger
        self.main_logger.addHandler(fh)
        self.main_logger.addHandler(ch)

    def error(self, message):
        self.main_logger.error(message)

    def warning(self, message):
        self.main_logger.warning(message)

    def info(self, message):
        self.main_logger.info(message)

    def debug(self, message):
        self.main_logger.debug(message)

if __name__ == '__main__':
    # Tests
    log = LoggingHandler(__name__)
    log.warning("hello")
    log.error("hola")
    log.info("info message")
    log.debug("debug message")


texts:
I have tests for simple POJO class ProgressableItem (i.e. the one which has attributes total work and work done).

I use JUnit 3 (it's from Android application).

public class ProgressableItemTest extends AndroidTestCase {
    private ProgressableItem item;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        item = new ProgressableItem("item", "test item", 0, 100);
    }

    public void testNotEquals() {
        ProgressableItem itemWithDifferentName = copyOf(item);
        itemWithDifferentName.setName("Not the same " + item.getName());
        assertThat(itemWithDifferentName, not(item));
        ProgressableItem itemWithDifferentDescription = copyOf(item);
        itemWithDifferentName.setDescription("Not the same " + item.getDescription());
        assertThat(itemWithDifferentDescription, not(item));
        ProgressableItem itemWithDifferentProgress = copyOf(item);
        itemWithDifferentName.setProgress(item.getProgress() + 1);
        assertThat(itemWithDifferentProgress, not(item));
        ProgressableItem itemWithDifferentMax = copyOf(item);
        itemWithDifferentName.setMax(item.getMax() + 1);
        assertThat(itemWithDifferentMax, not(item));
    }

    private static ProgressableItem copyOf(ProgressableItem item) {
        return new ProgressableItem(item.getName(), item.getDescription(), item.getProgress(), item.getMax());
    }

}

public interface Handler<T> {
    void handle(T obj);
}

Then I modified it into:

public void testNotEquals() {
    for (Handler<ProgressableItem> progressableItemModifier : PROGRESSABLE_ITEM_MODIFIERS) {
        ProgressableItem differentItem = copyOf(item);
        progressableItemModifier.handle(differentItem);
        assertThat(differentItem, not(item));
    }
}

private static final Collection<? extends Handler<ProgressableItem>>
        PROGRESSABLE_ITEM_MODIFIERS = Arrays.asList(
                new Handler<ProgressableItem>() {
                    @Override
                    public void handle(ProgressableItem obj) {
                        obj.setName("Not the same " + obj.getName());
                    }
                },
                new Handler<ProgressableItem>() {
                    @Override
                    public void handle(ProgressableItem obj) {
                        obj.setDescription("Not the same " + obj.getDescription());
                    }
                },
                new Handler<ProgressableItem>() {
                    @Override
                    public void handle(ProgressableItem obj) {
                        obj.setProgress(obj.getProgress() + 1);
                    }
                },
                new Handler<ProgressableItem>() {
                    @Override
                    public void handle(ProgressableItem obj) {
                        obj.setMax(obj.getMax() + 1);
                    }
                }
);

But now I have many more lines of code.

Which of the two options is better? Should I separate the test method into 4 small methods? Is there no need to check each case?


texts: Linkedlist visualization using html5 canvas

texts:
I have written a simple linked list visualization program in JavaScript:

I am just a beginner in html5 canvas. I am pretty much satisfied with how it works, but I´d like to know if I made some things, that could have been done better.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>

var Shape=Shape || {
 x:0,
 y:0,
 w:0,
 h:0,
 t:0,
 rects:[],
 create:function(){
  var obj=Object.create(this);
  return obj;
 },
 add:function(x,y,w,h,t){
  this.x=x;
  this.y=y;
  this.w=w;
  this.h=h;
  this.t=t;
  this.rects.push({x,y,w,h,t});
 },
 draw:function(context,text){
  for (var i in this.rects) {
        oRec = this.rects[i];
        context.fillStyle = 'red'
        context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
      context.fillText(oRec.t, oRec.x,oRec.y);
        context.beginPath();
       context.moveTo(oRec.x+oRec.w/2,oRec.y+oRec.h/2);
       context.lineTo(oRec.x+100,oRec.y+12);
       context.stroke();
       context.closePath();
       if(i==this.rects.length){

       }

    }
 }

};
window.onload=function(){
   var canvas=document.getElementById("canvas");
   var ctx=canvas.getContext("2d");
   var h=canvas.width=window.innerWidth;
   var w=canvas.height=window.innerHeight;
   var node=Shape.create();
   node.add(10, 100, 25, 25,1)
   node.add(100,100, 25, 25,2)
   node.add(200,100, 25, 25,3)
   node.add(300,100, 25, 25,4)
   node.add(400,100, 25, 25,5)
   node.add(500,100, 25, 25,6)
   node.draw(ctx);

};

</script>
</body>
</html>


texts:
I am creating styles for the comment posts for a projects using BootStrap. I am wondering if this is good HTML markup and the extending of BootStrap's CSS.

Using HTML5 markup recommendations the HTML for the comment posts is as follows.

Comments

username

 That Guy

                <time class="comment-date" datetime="16-12-2014 01:05"> Dec 16, 2014</time>

                  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 reply

I tried to work off BootStrap's CSS and add my style to it.

The CSS is as follows

/*Comment List styles*/
.comment-list .row {
margin-bottom: 0px;
}
.comment-list .panel .panel-heading {
 padding: 4px 15px;
 position: absolute;
 border:none;
/*Panel-heading border radius*/
border-top-right-radius:0px;
top: 1px;
}
.comment-list .panel .panel-heading.right {
border-right-width: 0px;
/*Panel-heading border radius*/
border-top-left-radius:0px;
right: 16px;
}
.comment-list .panel .panel-heading .panel-body {
padding-top: 6px;
}
.comment-list figcaption {
/*For wrap text is thumbnail*/
word-wrap: break-word;
}
/* Portrait tablets and medium desktops */
@media (min-width: 768px) {
.comment-list .arrow:after, .comment-list .arrow:before {
content: "";
position: absolute;
width: 0;
height: 0;
border-style: solid;
border-color: transparent;
}
.comment-list .panel.arrow.left:after, .comment-list .panel.arrow.left:befor {
border-left: 0;
}
/*****Left Arrow*****/
/*Outline effect style*/
.comment-list .panel.arrow.left:before {
left: 0px;
top: 30px;
/*Use boarder color of panel*/
border-right-color: inherit;
border-width: 16px;
}
/*Background color effect*/
.comment-list .panel.arrow.left:after {
left: 1px;
top: 31px;
/*Change for different outline color*/
border-right-color: #FFFFFF;
border-width: 15px;
}
/*****Right Arrow*****/
/*Outline effect style*/
.comment-list .panel.arrow.right:before {
right: -16px;
top: 30px;
/*Use boarder color of panel*/
border-left-color: inherit;
border-width: 16px;
}
/*Background color effect*/
.comment-list .panel.arrow.right:after {
right: -14px;
top: 31px;
/*Change for different outline color*/
border-left-color: #FFFFFF;
border-width: 15px;
}
}
.comment-list .comment-post {
margin-top: 6px;
}

I have included a Bootply link to the example.

comment post example on Bootply


texts: Compute the square root of a positive integer using binary search

texts:
The requirement is to find the square root of a positive integer using binary search and the math property that square root of a number n is between 0 and n/2, and the required answer is "floored", meaning mySqrt(8) is to return 2.

Please comment on the efficiency, and if possible, the loop invariants in terms of correctness:

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int

        Loop invariant:

            The answer is always in the range [low, high] inclusive,
            except possibly:

                1) low == high == mid, and mid * mid == x and
                   any of low, high, or mid can be returned as the answer.

                2) if there is no exact answer and the floor is to be
                   returned, then low > high by 1. Since sq != x,
                   so either low or high is set inside the loop.

                   If low gets set and gets pushed up, it is pushed up too much.
                   So when low > high by 1, low - 1 is the answer and it is the same
                   as high, because low > high by 1.

                   If high gets set and gets pushed down, high can be
                   the correct answer. When low > high, it is by 1,
                   and high is the correct floor value to be returned.
                   (since there is no perfect square root and the floor is required)

            0 <= low <= answer <= high <= n//2 + 1

                where answer is floor(sqrt(x)) to be found,
                except if low > high and the loop will exit.

            Each loop iteration always makes the range smaller.

        If the range is empty at the end, low is > high by 1, and high is
            the correct floored value, and low is the ceiling value, so high is returned.
        """

        low = 0;
        high = x//2 + 1;

        while (low <= high):
            mid = low + (high - low) // 2;
            sq = mid * mid;
            if (sq == x):
                return mid;
            elif (sq > x):
                high = mid - 1;  # sq exceeds target, so mid cannot be the answer floored, but when high is set to mid - 1, then it can be the answer
            else:
                low = mid + 1;   # (here sq < x, and mid might be the answer floored, so when low is set to mid + 1, then low might be too big, while high is correct)

        return high;


texts:
I am developing an e-commerce site and am confused about this.

Customers come on the site and add some products to the cart.
Customers click on the checkout link if already logged in, then will go to the "thanks" page (this is your order number, total price, etc.).

I want to insert the total price into Order table.

<?php
session_start();
include('../includes/dbfunctions.php');
if(!isset($_SESSION["id"]))
{
header("location:order_login.php");
}
if(isset($_SESSION['id']))
{
$id=$_SESSION["id"];
$email=$_SESSION["email"];
$name=$_SESSION['name'];
$contact=$_SESSION["contact"];
$mysqli->query("insert into     orders(user_id,user_name,contact_no,email)values('$id','$name','$contact','$email')");

$result=$mysqli->query("select order_id from orders where user_id='$id'   ORDER BY order_id desc limit 1");
$obj=$result->fetch_object();
$order_id=$obj->order_id;
}
?>
<form action="#" method="post" enctype="multipart/form-data">

  <?php
        //Display of cart

        if(isset($_SESSION["products"]))
        {
            $total = 0;
            $qty=0;
            ?>

        <?php
        foreach ($_SESSION["products"] as $cart_itm)
        {
            $product_qty = $cart_itm["qty"];
            $product_code=$cart_itm["product_code"];
            $image=$cart_itm["pic"];
            $product_name=$cart_itm["name"];

            echo '';
            echo 'ucwords($product_name)';
            echo 'ucwords($product_code)';
            echo 'ucwords($product_qty)';
            $subtotal = ($cart_itm["price"]*$product_qty);
            $total = ($total + $subtotal);
            echo '$subtotal';
            $qty=($product_qty+$qty);

            $mysqli->query("insert into order_details(user_id,img,product_name,product_code,qty,sub_total,order_id)values('$id','$image','$product_name','$product_code','$product_qty','$subtotal',$order_id)");

            }
            ?>
</form>


texts:
In essence, I need to do a stable partition: All elements of the 1D np.array a that are present in b should be moved to the front of a but apart from that, the relative order of the elements in a should be preserved.

This code seems to do what I want:

from __future__ import print_function
import numpy as np

if __name__=='__main__':
    a = np.array([1, 2, 3, 4, 5], dtype=np.int32)
    b = np.array([4, 2, 6],       dtype=np.int32)
    pos = np.in1d(a, b, assume_unique=True)
    cnt = np.count_nonzero(pos)
    tmp = np.empty(a.size, dtype=np.int32)
    tmp[0:cnt] = a[pos]
    tmp[cnt: ] = a[np.invert(pos)]
    a = tmp
    print('after stable partition:', a)

Output:

after stable partition: [2 4 1 3 5]

Is there a cleaner / more efficient way of doing this in NumPy?


texts: Selecting a prize category based on two parameters

texts:
I get an object with categories, first category has 2 types. Both types are in the first and second position but sorting is not constant.

I have to return category 1 with playLevel === 2 when bonusPlus is true and category 1 with playLevel === 1 otherwise.

Here is the code:

const getFirstCategory = (bonusPlus, prizeCategories) => {
  if (bonusPlus) {
    if (prizeCategories[0].playLevel === 2) {
      return [prizeCategories[0]];
    }
    return [prizeCategories[1]];
  }
  if (prizeCategories[0].playLevel === 1) {
    return [prizeCategories[0]];
  }
  return [prizeCategories[1]];
};

How can I reduce / beautify this code?


texts:
Please tell me if this function is correct (I believe it to be), efficient, and clean.

Function to check:

::CURLcode CURL_DownloadFile( __in ::LPCSTR URL, __in ::LPCSTR Destination )
{
    ::CURL* Curl;
    ::CURLcode Return_CurlCode;
    std::FILE* File;

    if( ( Curl = ::curl_easy_init( ) ) )
    {
        File = std::fopen( Destination, "wb" );

        ::curl_easy_setopt( Curl, CURLOPT_URL, URL );
        ::curl_easy_setopt( Curl, CURLOPT_WRITEFUNCTION, WriteData );
        ::curl_easy_setopt( Curl, CURLOPT_WRITEDATA, File );

        Return_CurlCode = ::curl_easy_perform( Curl );
        std::fclose( File );
    } else { ( Return_CurlCode = CURLE_FAILED_INIT ); }

    return( Return_CurlCode );
};

Example of usage:

#include "Global.h"

::CURLcode CURL_DownloadFile( __in ::LPCSTR URL, __in ::LPCSTR Destination );

int main( void )
{
    if( CURL_DownloadFile( "http://stackoverflow.com/", "c:\\users\\xorr\\desktop\\stackoverflow.txt" ) != CURLE_OK )
        std::printf( "An error has occured...\n" );

    std::cin.get( );
    return( EXIT_SUCCESS );
    // Xorr@Hotmail.com
};

size_t WriteData( void *ptr, size_t size, size_t nmemb, std::FILE *stream ) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

::CURLcode CURL_DownloadFile( __in ::LPCSTR URL, __in ::LPCSTR Destination )
{
    ::CURL* Curl;
    ::CURLcode Return_CurlCode;
    std::FILE* File;

    if( ( Curl = ::curl_easy_init( ) ) )
    {
        File = std::fopen( Destination, "wb" );

        ::curl_easy_setopt( Curl, CURLOPT_URL, URL );
        ::curl_easy_setopt( Curl, CURLOPT_WRITEFUNCTION, WriteData );
        ::curl_easy_setopt( Curl, CURLOPT_WRITEDATA, File );

        Return_CurlCode = ::curl_easy_perform( Curl );
        std::fclose( File );
    } else { ( Return_CurlCode = CURLE_FAILED_INIT ); }

    return( Return_CurlCode );
};


texts:
Here is my objective:

Ask how many categories there are for the class (ex: Labs, Tests, Homework, Quizzes), and then ask what total percentage each make up for the class (ex: Lab are 15%, tests are 60%, so on), and then ask how many items there are under each category (ex: 7 labs, 3 tests, so on), and then ask for the max points of each items in each category, and finally ask what I got on each one.

I could make a pretty simple one for each class, but I wanted to be able to have one program that does it for any class that I can continue to use through my years at university. I'm not advanced by any means, which is why I want to take on this side project. I was hoping some of you could help me out in finishing it up.

Also, I don't know how to make arrays as big as the user wants, so I just put large enough numbers so that I won't ever need more. Probably not good practice, not sure.

int main()
{
    string categories[10];
    int percent[10];
    int totalPoints[50];
    int totalItems[50];
    int a = 0;

    cout << "How many grade categoies do you have: ";
    cin >> a;

    for(int i = 1; i <= a; i++)
    {
        cout << "Enter the category title: ";
        cin >> categories[i];
    }
    for(int i = 1; i <= a; i++)
    {
        cout << "Enter the total percentage for " << categories[i] << ": ";
        cin >> percent[i];
    }
    for(int i = 1; i <= a; i++)
    {
        cout << "How many items are there for " << categories[i] << ": ";
        cin >> totalItems[i];
    }

    return 0;
}


texts: Is this an ugly/incorrect usage of subscriptions?

texts:
Little backstory: I'm trying to write code that will read messages from INetworkConnection that the INetworkConnection publishes and then send those up to the NetworkController which should do some processing and then send that off to an injected IObserver<IMessage> (which is a single observer because there's a global listener interested in network messages).

In other words, I'm trying to read messages, transform them, and then push them off to some listener. The reason why the controller is not subscribable is because there is only meant to be one listener (which will then distribute messages as necessary).

Now, right now I haven't added the transformation, so all the network controller does is that it pipes the messages from every connection into the injected subscriber like so:

    private readonly IDisposable _networkConnectionStreamSubscription;
    private readonly IObserver<INetworkMessage> _networkMessageStream;

    public NetworkController(IObservable<INetworkConnection> networkConnectionStream,
        IObserver<INetworkMessage> networkMessageStream)
    {
        _networkConnectionStreamSubscription = networkConnectionStream.Subscribe(
            x => LinkWith(x),
            () => Close());
        _networkMessageStream = networkMessageStream;
    }

    /// <summary>
    /// Link the Controller with the given Connection, allowing the network
    /// controller to start listening for network messages.
    /// </summary>
    /// <param name="networkConnection"></param>
    public void LinkWith(INetworkConnection networkConnection)
    {
        // Subscribe to the network message, and pipe the messages that have been parsed
        // out through our network message stream.
        // TODO: Do something with the subscription disposable
        networkConnection.Subscribe(
            x => _networkMessageStream.OnNext(x),
            exception => _NetworkMessageError(networkConnection, exception),
            () => _NetworkConnectionClosed(networkConnection)
        );
    }

My question is, simply speaking, am I

going the wrong way by thinking of Rx as streams of T and
is this considered an anti pattern/bad approach to what I am trying to do?


texts:
I have tried to remove the duplicate elements from the array using c language, here I am using 3 for loops to remove the duplicate elements.
How can this optimize the code?
Are there any other simple methods to remove the duplicate elements?
Please help.
#include <stdio.h>

#define MAX_SIZE 100 // Maximum size of the array

int main()
{

 int arr[MAX_SIZE];
 int size;
 int i, j, k;

printf("Enter size of the array : ");
scanf("%d", &size);

printf("Enter elements in array : ");
for(i=0; i<size; i++)
{
    scanf("%d", &arr[i]);
}

for(i=0; i<size; i++)
{
    for(j=i+1; j<size; j++)
    {

        if(arr[i] == arr[j])
        {

            for(k=j; k<size; k++)
            {
                arr[k] = arr[k + 1];
            }

            size--;

            j--;
        }
    }
}

printf("\nArray elements after deleting duplicates : ");
for(i=0; i<size; i++)
 {
    printf("%d\t", arr[i]);
 }

return 0;
 }


texts:
Given a list of numbers, e.g.:

25626 25757 24367 24267 16 100 2 7277

Output a delta encoding for the sequence. In a delta encoding, the first
element is reproduced as is. Each subsequent element is represented as the
numeric difference from the element before it. E.g. for the sequence above,
the delta encoding would be:

25626 131 -1390 -100 -24251 84 -98 7275

However, if a difference value does not fit in a single signed byte,
i.e. -127 <= x <= 127, then, instead of the difference, we would like
to use an escape token, printing it.

This will denote that the value following the escape token is a full
four-byte difference value, rather than a one-byte different value.

For this exercise, we'll declare -128 as the escape token.

Following the same example above, the final result would be:

25626 -128 131 -128 -1390 -100 -128 -24251 84 -98 -128 7275

function getDelta(arr) {
  let diffs = [];
  for (let i = 1, N = arr.length -1; i <= N; ++i) {
    diffs.push(arr[i] - arr[i - 1]);
  }
  return diffs;
}

function encode(arr) {
  if (arr.length === 0) {
    return arr;
  }
  let encoding = [];
  let deltas = getDelta(arr);

  for (let delta of deltas) {
    if (127 < delta || delta < -127) {
      encoding.push(-128);
    }
    encoding.push(delta);
  }
  encoding.unshift(arr[0]);
  return encoding;
}

console.log(encode('25626'.split(' ')).join(' '));
console.log(encode('25626 25757 24367 24267 16 100 2 7277'.split(' ')).join(' '));


texts:
So I made this calculator the other day as a small project. I just wanted to know if I remembered the fundamentals. It works fine from the looks of it, but I know there are always ways to improve.

    package Main;
    import java.util.*;
    public class calc {
@SuppressWarnings("resource")
private static void circle() {
    // TODO Auto-generated method stub
    double a_c = 0; //a_c = area of circle

    System.out.println("Please enter the radius of the circle.");

    Scanner read_r = new Scanner(System.in); // This is the scanner that scan user input.

    double r = read_r.nextDouble(); // This is the radius the user enters.

    a_c = Math.PI * r *r ; //a_c stands for area of circle followed by equation.

    System.out.print("The area of the circle equals: ");

    System.out.println(a_c);// the system is printing the result; the value of a_c

    main(null);
}
@SuppressWarnings("resource")
private static void square() {
    // TODO Auto-generated method stub

    double a_s = 0; // a_s = area of square initial value

    System.out.println("Please enter the value of the length of one side of the square.");

    Scanner read_s = new Scanner(System.in); // This is the scanner that scan user input.

    double s = read_s.nextDouble(); // This is the side length the user enters.

    a_s = s*s; //equation for square area = s^2

    System.out.print("The area of the square equals: ");

    System.out.println(a_s);

    main(null);
}
@SuppressWarnings("resource")
private static void triangle() {
    // TODO Auto-generated method stub
    double a_t = 0; //a_t = area of triangle initial value

    System.out.println("Please enter the height of your triangle.");

    Scanner read_h = new Scanner(System.in); // This is the scanner that will read height.

    int h = read_h.nextInt(); // This is the height the user enters.

    System.out.println("Please enter the value for the base of your triangle");

    Scanner read_b = new Scanner(System.in); // This is the scanner that reads base

    Double b = read_b.nextDouble(); // This is the base the user enters

    a_t = .5*b*h;

    System.out.print("The area of the traingle equals: ");

    System.out.println(a_t);

    main(null);
}
@SuppressWarnings("resource")
private static void rectangle() {
    // TODO Auto-generated method stub
    double a_r = 0;// a_r = area of rectangle initial value

    System.out.println("Please enter the width of your rectangle.");

    Scanner read_w = new Scanner(System.in); // This is the scanner that scan user input.

    double w = read_w.nextInt(); // This is the width value the user enters.

    System.out.println("Please enter a value for the height of your triangle.");

    Scanner read_h = new Scanner(System.in);

    double h = read_h.nextDouble();

    a_r = h*w;

    System.out.print("The area of the rectangle equals: ");

    System.out.println(a_r);

    main(null);
}
private static void quit(){
    System.out.println("Quiting....");

    System.exit(0);

}
@SuppressWarnings("resource")
public static void main(String [] args1){

    System.out.println("What would you like to do? Type the number of your desired function.");

    System.out.println("1. Area of a Circle");

    System.out.println("2. Area of a Square");

    System.out.println("3. Area of a Triangle");

    System.out.println("4. Area of a Rectangle");

    System.out.println("5. Quit");

    Scanner readc = new Scanner(System.in);

    int c = readc.nextInt(); //This is the choice method 1-4

switch (c){
case 1:
    circle();
    break;
case 2:
    square();
    break;
case 3:
    triangle();
case 4:
    rectangle();
case 5:
    quit();
    break;
default:
    System.out.println("I'm sorry, you didn't select a function.");
    System.out.println("Please choose again");
    main(null);
    }
 }

}


texts:
This is within a base class of a library, where several other classes inherit this one.

This seems like the simplest way of just getting some data, for now without timeout/errorhandling. This is supposed to get some data that will most ofthe time be converted to a small JSONObject.

Do you think I should put everything inside the try and use val? Any other suggestions? I'm basically just learning networking with android, only did it in C#.NET before.

protected fun sendGetRequest(url: URL): String {
    var urlConnection: HttpsURLConnection? = null
    var reader: InputStreamReader? = null
    var responseData = ""
    try {
        urlConnection = url.openConnection() as HttpsURLConnection

        reader = InputStreamReader(urlConnection.inputStream)
        responseData = reader.readText()
    }catch (e: Exception){
        this.messageHandler.handleMessage(e.message!!)
    }finally {
        reader?.close()
        urlConnection?.disconnect()
    }
    return responseData
}


texts: Find the largest exponent x such that p^x evenly divides n

texts:
Write a method getExponent(n, p) that returns the largest exponent
  x such that px evenly divides n. If p ≤ 1 the method should return -1.

  getExponent(162, 3) returns 4 because 162 = 21∙ 34, therefore the value of x here is 4.
  if n is 27 and p is 3, return 3 because 33 divides 27 evenly but 34 does not.
  if n is 28 and p is 3, return 0 because 30 divides 28 evenly but 31 does not.
  if n is 280 and p is 7, return 1 because 71 divides 280 evenly but 72 does not.
  if n is -250 and p is 5, return 3 because 53 divides -250 evenly but 54 does not.`
  if n is 18 and p is 1, return -1 because if p <= 1 the function returns -1.
  if n is 128 and p is 4, return 3 because 43 divides 128 evenly but 44 does not.

I wrote following code to test that result

public class Exponent {

public static void main(String args[]) {
    int n = 27;
    int p = 3;
    System.out.println("result is: " + getExponent(n, p));
}

public static int getExponent(int n, int p) {
    int count = 0;
    if (p <= 1) {
        count = -1;
    } else {
        boolean status = true;
        while (status) {
            if (n % p == 0) {
                count++;
                n = n / p;
            } else {
                status = false;
                break;
            }
        }
    }

    return count;
}
}

I checked whether n is divisible by p or not. If divisible, then increment count and return count. Is this the right way to do that?


texts:
I would love a second opinion / another pair of eyes on this.

db.customers.mapReduce(
    function() {
        Array.prototype.getUnique = function() {
            var u = {}, a = [];
            for (var i = 0, l = this.length; i < l; ++i) {
                if (u.hasOwnProperty(this[i])) {
                    continue;
                }
                a.push(this[i]);
                u[this[i]] = 1;
            }
            return a;
        }
        var customer = this;
        this.tags.getUnique().forEach(function(tag) {
            if (customer.status) {
                emit(customer.shop, {
                    "kind": "unique_customers_submitted",
                    "tag": tag.tag,
                });
            } else {
                emit(customer.shop, {
                    "kind": "unique_customers_withheld",
                    "tag": tag.tag,
                });
            }
            emit(customer.shop, {
                "kind": "unique_customers_total",
                "tag": tag.tag,
            });
        })
        this.tags.forEach(function(tag) {
            if (customer.status) {
                emit(customer.shop, {
                    "kind": "total_customers_submitted",
                    "tag": tag.tag,
                });
            } else {
                emit(customer.shop, {
                    "kind": "total_customers_withheld",
                    "tag": tag.tag,
                });
            }
            emit(customer.shop, {
                "kind": "total_customers",
                "tag": tag.tag,
            });
        });
    },
    function(key, sets) {
        var forms = {};
        sets.forEach(function(set) {
            if (typeof forms[set.tag] == "undefined") forms[set.tag] = {};
            if (typeof forms[set.tag][set.kind] == "undefined") forms[set.tag][set.kind] = 0;
            forms[set.tag][set.kind] += 1;
        });
        return forms;
    }, {
        out: "form_numbers",
    },
    function(err, results) {
        console.log(err);
        //console.log(results);
        results.find().toArray(function(err, numbers) {
            console.log(err);
            console.log(JSON.stringify(numbers));
            db.server.close();
        });
    }
);


texts:
I'm re-writing my Module of standard methods. These 3 are used to retrieve Workbooks as Workbook Objects. The standard I'm aiming for here is "Third-party Library/Add-in". So:

Do these functions adhere to the principle of least surprise?
Have I missed any potential error cases?

As always, general feedback is also welcome.

Public Function GetWorkbook(ByVal strFileName As String, Optional ByVal strFilePath As Variant) As Workbook

        If Not (IsMissing(strFilePath) Or strFilePath.TypeName = "String") Then
            PrintErrorMessage "File Path was not supplied as a string", stopExecution:=True
        End If

    Dim wbIsOpen As Boolean

        wbIsOpen = IsWorkbookOpen(strFileName)
        If wbIsOpen Then
            Set GetWorkbook = Workbooks(strFileName)
        Else
            If Not IsMissing(strFilePath) Then
                Set GetWorkbook = OpenWorkbook(strFilePath & strFileName)
            Else
                PrintErrorMessage "Workbook (" & strFileName & ") is not open, and no filepath was supplied", stopExecution:=True
            End If
        End If

End Function

Public Function IsWorkbookOpen(ByVal strTargetName As String) As Boolean

    Dim wbTest As Workbook

        On Error Resume Next
            Set wbTest = Workbooks(strTargetName)
            IsWorkbookOpen = (wbTest.Name = strTargetName)
        On Error GoTo 0

End Function

Public Function OpenWorkbook(ByVal strFileName As String, strFilePath As String) As Workbook

    Dim strFullFilename As String
        strFullFilename = strFilePath & strFileName

    Dim wbOpenedSuccessfully As Boolean

        On Error Resume Next
            Set OpenWorkbook = Workbooks.Open(strFullFilename)
            wbOpenedSuccessfully = IsWorkbookOpen(strFileName)
        On Error GoTo 0

        If Not wbOpenedSuccessfully Then
            PrintErrorMessage "Failed to open workbook """ * strFullFilename & """", stopExecution:=True
        End If

End Function


texts:
Is there a more efficient algorithm to generate random numbers in C++?

(This code is working on Dev-C++, but I'm not sure if it works on a Borland compiler.)

/*
  Author: Arpit Agrawal
  Email: arpitagrawal294@gmail.com
  Description: Dice Roll Algorithm.
  Project Name: e-Roll.

*/

#include<iostream.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#include <stdio.h>
#include <Windows.h>

void call();
void one();
void two();
void three();
void four();
void five();
void six();
void call();
int main()
{

    //gotoxy(30,15);
    cout<<"\n\n\n\n\t\tAuthor: Arpit Agrawal\n\t\tEmail: arpitagrawal294@gmail.com\n\t\tDescription: Dice Roll Algorithm.\n\t\tProject Name: e-Roll.\n\t\t" ;
    cout<<"\n\n\t\tLoading. . . . . . . ";
    Sleep(3000);
    cout<<"\n\n\t\tPress r to roll or q to quit the game "<<endl;
    char ch;
    ch = getch();
    xm:
    if (ch=='r'){
    system("cls");
    call();  }
    else
    exit (0);
    cout<<endl<<endl<<"Press r to roll again q to quit!";
    ch = getch();
    goto xm;
    getch();
}

    void call()
    {
        srand (time(NULL));

        int n;
        n= rand();
        n = 1 + n % 6;

        switch (n)
        {
         case 1:
              one();
              break;
         case 2:
              two();
              break;
         case 3:
              three();
              break;
         case 4:
              four();
              break;
         case 5:
              five();
              break;
         case 6:
              six();
              break;
         default:
                 cout<<"NONUM";

        }
    }

        void one()
        {
        cout << " -----" << endl;
        cout << "|     |" << endl;
        cout << "|  O  |" << endl;
        cout << "|     |" << endl;
        cout <<  " -----" << endl;
        }
        void two()
        {
        cout << " -----" << endl;
        cout << "|    O|" << endl;
        cout << "|     |" << endl;
        cout << "|O    |" << endl;
        cout <<  " -----" << endl;
        }
        void three()
        {
        cout << " -----" << endl;
        cout << "|    O|" << endl;
        cout << "|  O  |" << endl;
        cout << "|O    |" << endl;
        cout <<  " -----" << endl;
        }
        void four()
        {
        cout << " -----" << endl;
        cout << "|O   O|" << endl;
        cout << "|     |" << endl;
        cout << "|O   O|" << endl;
        cout <<  " -----" << endl;
        }
        void five()
        {
        cout << " -----" << endl;
        cout << "|O   O|" << endl;
        cout << "|  O  |" << endl;
        cout << "|O   O|" << endl;
        cout <<  " -----" << endl;
        }
        void six()
        {
        cout << " -----" << endl;
        cout << "|O   O|" << endl;
        cout << "|O   O|" << endl;
        cout << "|O   O|" << endl;
        cout <<  " -----" << endl;
        }


texts:
I have a case study where I need to take data from a REST API do some analysis on the data using an aggregate function, joins etc and use the response data in JSON format to plot some retail graphs.

Approaches being followed till now:

Read the data from JSON store these in python variable and use insert to hit the SQL query. Obviously, it is a costly operation because for every JSON line read it is inserting into the database. For 33k rows it is taking more than 20 mins which is inefficient.
This can be handled in elastic search for faster processing but complex operation like joins are not present in elastic search.

If anybody can suggest what would be the best approach (like preprocessing or post-processing in python) to follow for handling such scenarios it would be helpful.

SQL Script

def store_data(AccountNo)

        db=MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DATABASE, charset="utf8")
        cursor = db.cursor()
        insert_query = "INSERT INTO cstore (AccountNo) VALUES (%s)"
        cursor.execute(insert_query, (AccountNo))
        db.commit()
        cursor.close()
        db.close()
        return

def on_data(file_path):
        #This is the meat of the script...it connects to your mongoDB and stores the tweet
        try:
           # Decode the JSON from Twitter
            testFile = open(file_path)

            datajson = json.load(testFile)
            #print (len(datajson))

            #grab the wanted data from the Tweet
            for i in range(len(datajson)):
                for cosponsor in datajson[i]:
                    AccountNo=cosponsor['AccountNo']
                    store_data( AccountNo)


texts: Reduced Docker Image size for Docker file


texts:
forceTwoDigits = (val) ->
  if val < 10
    return "0#{val}"
  return val

formatDate = (date) ->
  year = date.getFullYear()
  month = forceTwoDigits(date.getMonth()+1)
  day = forceTwoDigits(date.getDate())
  hour = forceTwoDigits(date.getHours())
  minute = forceTwoDigits(date.getMinutes())
  second = forceTwoDigits(date.getSeconds())
  return "#{year}#{month}#{day}#{hour}#{minute}#{second}"

console.log(formatDate(new Date()))

Is there a better way to do this?


texts:
Sum Strings
Codewars kata.
It's supposed to be able to handle big integers.

Question

Given the string representations of two integers, return the string representation of the sum of those integers.
For example:

sumStrings('1','2') // => '3'

A string representation of an integer will contain no characters besides the ten numerals "0" to "9".

Solution
"use strict";
const reverseArr = s => s.split("").reverse();

function sumStrings(a, b) {
   [a, b] = [reverseArr(a), reverseArr(b)];
   let carry = 0;
   const arr = []
   const [mx, mn] = (a.length >= b.length) ? [a, b] : [b, a];
   mx.forEach((itm, idx) => {
      let sm = Number(itm) + (Number(mn[idx]) || 0) + carry;
      [sm, carry] = sm > 9 ? [sm%10, 1] : [sm, 0];
      arr.unshift(sm)
   })
   if (carry) arr.unshift(carry);
   return arr.join("").replace(/^(0+)/, "");
}


texts: Poor error handling: Throw inside Finally

texts:
I have the following code which I am running through fortify. Why it gets marked for poor error handling, throw inside finally?

private String getResourceContent(String fileName) throws IOException {

    try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {
        return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
    } catch (NullPointerException n) {
        throw new ErrorDescriptorException(
                String.format("Error loading Error description data from Resource file [%s].", fileName), n);
    }
}


texts:
This function is used in a ASP.NET web application written in C#. It is heavily used to output summary information of the some prices chosen by a user. We are trying to lessen how much we have to scale horizontally.

Here is the original function:

    private static Dictionary<int, string> Cache = new Dictionary<int, string> {{ 1, "Adult" }, { 2, "Child" }};

    public string Build(List<int> priceTypeIds)
    {
        if (session == null)
        {
            return "";
        }

        var uniquePriceTypeIds = priceTypeIds.Distinct();

        var result = new List<string>();

        foreach (var priceTypeId in uniquePriceTypeIds)
        {
            var count = priceTypeIds.Count(x => x == priceTypeId);

            var description = Cache[priceTypeId];

            result.Add($"{count} {description}");
        }

        return string.Join(", ", result);
    }

I rewrote the function to eliminate the amount of string concatenations. But

private static Dictionary<int, string> Cache = new Dictionary<int, string> {{ 1, "Adult" }, { 2, "Child" }};

public static string CreateSummary()
{
    var sb = new StringBuilder();

    List<int> sample = new List<int> { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };

    foreach (var priceTypeId in sample.Distinct())
    {
        if (sb.Length > 0)
        {
            sb.Append(',');
            sb.Append(' ');
        }

        sb.Append('(');
        sb.Append(Sample.Count(x => x == priceTypeId));
        sb.Append(')');
        sb.Append(' ');
        sb.Append(Cache[priceTypeId.ToString()]);
    }

    return sb.ToString();
}

The sample data in the second function is a common use case as we have classes get purchased with 20-30 kids in a single transaction along with chaperones.


texts: Python one-liner to print permutations of a string

texts:
I have written a Python one-liner that permutes a given string. I wrote this just for fun using list comprehensions and I would like to get feedback from the community.

def permute(c, s=""):
    return [s] if len(s) == len(c) else [x for y in [permute(c, e) for e in [s[0:i]+c[len(s)]+s[i:] for i in xrange(len(s)+1)]] for x in y]

print permute ("omer")